From 7292c12746e5b49fee42ccc34fb2de11ae2595a8 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 03:52:12 +0530 Subject: [PATCH 01/32] chore(agent): rename the module and tighten CI --- .github/workflows/ci.yml | 9 +++++++-- agent/cmd/agent/main.go | 4 ++-- agent/go.mod | 2 +- agent/internal/exec/bridge.go | 2 +- agent/internal/exec/bridge_test.go | 2 +- agent/internal/proxy/proxy.go | 2 +- agent/internal/server/server.go | 8 ++++---- agent/internal/server/server_test.go | 2 +- 8 files changed, 18 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 489da0e..19a1ccc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,9 +10,14 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version-file: agent/go.mod + go-version: stable + cache-dependency-path: agent/go.sum + - name: Format + run: test -z "$(gofmt -l .)" || (gofmt -l . && exit 1) - run: go vet ./... - - run: go test ./... + - run: go test -race ./... + - name: Vulnerability check + run: go run golang.org/x/vuln/cmd/govulncheck@latest ./... app: runs-on: ubuntu-latest defaults: diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go index 72b7cdc..4880d2a 100644 --- a/agent/cmd/agent/main.go +++ b/agent/cmd/agent/main.go @@ -7,8 +7,8 @@ import ( "os" "time" - "github.com/0xLennox07/docker-mobile/agent/internal/config" - "github.com/0xLennox07/docker-mobile/agent/internal/server" + "github.com/retransmit/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/server" ) func main() { diff --git a/agent/go.mod b/agent/go.mod index 60f9854..b51715c 100644 --- a/agent/go.mod +++ b/agent/go.mod @@ -1,4 +1,4 @@ -module github.com/0xLennox07/docker-mobile/agent +module github.com/retransmit/docker-mobile/agent go 1.23 diff --git a/agent/internal/exec/bridge.go b/agent/internal/exec/bridge.go index a21e855..834ac34 100644 --- a/agent/internal/exec/bridge.go +++ b/agent/internal/exec/bridge.go @@ -12,8 +12,8 @@ import ( "strings" "time" - "github.com/0xLennox07/docker-mobile/agent/internal/dockerhost" "github.com/gorilla/websocket" + "github.com/retransmit/docker-mobile/agent/internal/dockerhost" ) // startExecHijack dials the Docker daemon and starts the given exec with a TTY, diff --git a/agent/internal/exec/bridge_test.go b/agent/internal/exec/bridge_test.go index 2803418..2faa811 100644 --- a/agent/internal/exec/bridge_test.go +++ b/agent/internal/exec/bridge_test.go @@ -11,8 +11,8 @@ import ( "testing" "time" - "github.com/0xLennox07/docker-mobile/agent/internal/auth" "github.com/gorilla/websocket" + "github.com/retransmit/docker-mobile/agent/internal/auth" ) // fakeExecStart serves one connection: records the request, replies with diff --git a/agent/internal/proxy/proxy.go b/agent/internal/proxy/proxy.go index e95aa3d..ff0ed2a 100644 --- a/agent/internal/proxy/proxy.go +++ b/agent/internal/proxy/proxy.go @@ -7,7 +7,7 @@ import ( "net/http/httputil" "net/url" - "github.com/0xLennox07/docker-mobile/agent/internal/dockerhost" + "github.com/retransmit/docker-mobile/agent/internal/dockerhost" ) func New(dockerHost string) (http.Handler, error) { diff --git a/agent/internal/server/server.go b/agent/internal/server/server.go index d7f7c6a..2fb089f 100644 --- a/agent/internal/server/server.go +++ b/agent/internal/server/server.go @@ -5,10 +5,10 @@ package server import ( "net/http" - "github.com/0xLennox07/docker-mobile/agent/internal/auth" - "github.com/0xLennox07/docker-mobile/agent/internal/config" - "github.com/0xLennox07/docker-mobile/agent/internal/exec" - "github.com/0xLennox07/docker-mobile/agent/internal/proxy" + "github.com/retransmit/docker-mobile/agent/internal/auth" + "github.com/retransmit/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/exec" + "github.com/retransmit/docker-mobile/agent/internal/proxy" ) func Handler(cfg config.Config) (http.Handler, error) { diff --git a/agent/internal/server/server_test.go b/agent/internal/server/server_test.go index 1f249b4..7af0cae 100644 --- a/agent/internal/server/server_test.go +++ b/agent/internal/server/server_test.go @@ -6,7 +6,7 @@ import ( "net/http/httptest" "testing" - "github.com/0xLennox07/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/config" ) func fakeDaemon() *httptest.Server { From 0a5ac992c70d873cde56778e9ea96c8da44eb65e Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 03:55:33 +0530 Subject: [PATCH 02/32] feat(agent): state folder and device list with hashed tokens --- agent/internal/state/devices.go | 234 ++++++++++++++++++++++++++ agent/internal/state/dir.go | 72 ++++++++ agent/internal/state/state_test.go | 259 +++++++++++++++++++++++++++++ 3 files changed, 565 insertions(+) create mode 100644 agent/internal/state/devices.go create mode 100644 agent/internal/state/dir.go create mode 100644 agent/internal/state/state_test.go diff --git a/agent/internal/state/devices.go b/agent/internal/state/devices.go new file mode 100644 index 0000000..2e6f9b1 --- /dev/null +++ b/agent/internal/state/devices.go @@ -0,0 +1,234 @@ +package state + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "sort" + "strings" + "sync" + "time" + "unicode" +) + +// Role is what a paired device may do. +type Role string + +const ( + RoleFull Role = "full" + RoleReadOnly Role = "readonly" +) + +// Valid reports whether r is a known role. +func (r Role) Valid() bool { return r == RoleFull || r == RoleReadOnly } + +// Device is one paired phone. The token itself is never stored, only its hash. +type Device struct { + ID string `json:"id"` + Name string `json:"name"` + Role Role `json:"role"` + TokenHash string `json:"tokenHash"` + CreatedAt time.Time `json:"createdAt"` + LastSeenAt time.Time `json:"lastSeenAt"` +} + +const ( + devicesFile = "devices.json" + tokenPrefix = "dm1." + // lastSeenEvery limits how often a last-seen time reaches the disk. + lastSeenEvery = time.Minute + maxNameRunes = 40 +) + +// Devices is the persisted list of paired devices, safe for concurrent use. +type Devices struct { + dir *Dir + now func() time.Time + rand io.Reader + + mu sync.Mutex + byID map[string]*Device + persisted map[string]time.Time // last-seen value already on disk, per id +} + +// LoadDevices reads the list from the folder. A missing file is an empty +// list. A file that cannot be parsed is an error, so the agent never starts +// as if nobody had been paired. +func LoadDevices(dir *Dir, now func() time.Time) (*Devices, error) { + s := &Devices{dir: dir, now: now, rand: rand.Reader, byID: map[string]*Device{}, persisted: map[string]time.Time{}} + data, err := dir.ReadFile(devicesFile) + if errors.Is(err, os.ErrNotExist) { + return s, nil + } + if err != nil { + return nil, fmt.Errorf("read %s: %w", devicesFile, err) + } + const hint = "fix or remove it (removing it unpairs every device)" + var list []Device + if err := json.Unmarshal(data, &list); err != nil { + return nil, fmt.Errorf("%s is damaged: %v; %s", devicesFile, err, hint) + } + for i := range list { + d := list[i] + if d.ID == "" || !d.Role.Valid() || len(d.TokenHash) != sha256.Size*2 { + return nil, fmt.Errorf("%s is damaged: entry %d is incomplete; %s", devicesFile, i, hint) + } + s.byID[d.ID] = &d + s.persisted[d.ID] = d.LastSeenAt + } + return s, nil +} + +// CleanName makes a device name safe to store and print: printable +// characters only, trimmed, at most 40 runes, never empty. +func CleanName(name string) string { + var b strings.Builder + n := 0 + for _, r := range strings.TrimSpace(name) { + if !unicode.IsPrint(r) { + continue + } + if n == maxNameRunes { + break + } + b.WriteRune(r) + n++ + } + out := strings.TrimSpace(b.String()) + if out == "" { + return "device" + } + return out +} + +// Add creates a device and returns it with its token. The token exists only +// in this return value; the list keeps its hash. +func (s *Devices) Add(name string, role Role) (Device, string, error) { + if !role.Valid() { + return Device{}, "", fmt.Errorf("unknown role %q", role) + } + s.mu.Lock() + defer s.mu.Unlock() + var id string + for { + raw := make([]byte, 4) + if _, err := io.ReadFull(s.rand, raw); err != nil { + return Device{}, "", fmt.Errorf("random id: %w", err) + } + id = hex.EncodeToString(raw) + if _, taken := s.byID[id]; !taken { + break + } + } + secret := make([]byte, 32) + if _, err := io.ReadFull(s.rand, secret); err != nil { + return Device{}, "", fmt.Errorf("random token: %w", err) + } + token := tokenPrefix + id + "." + base64.RawURLEncoding.EncodeToString(secret) + now := s.now().UTC() + d := &Device{ID: id, Name: CleanName(name), Role: role, TokenHash: hashToken(token), CreatedAt: now, LastSeenAt: now} + s.byID[id] = d + if err := s.saveLocked(); err != nil { + delete(s.byID, id) + return Device{}, "", err + } + return *d, token, nil +} + +// IsDeviceToken reports whether a bearer value has the shape of a device +// token, as opposed to the shared token from the environment. +func IsDeviceToken(token string) bool { return strings.HasPrefix(token, tokenPrefix) } + +// Authenticate returns the device a token belongs to. It records when the +// device was seen, writing that to disk at most once a minute per device. +func (s *Devices) Authenticate(token string) (Device, bool) { + rest, ok := strings.CutPrefix(token, tokenPrefix) + if !ok { + return Device{}, false + } + id, _, ok := strings.Cut(rest, ".") + if !ok { + return Device{}, false + } + s.mu.Lock() + defer s.mu.Unlock() + d, found := s.byID[id] + if !found { + return Device{}, false + } + if subtle.ConstantTimeCompare([]byte(hashToken(token)), []byte(d.TokenHash)) != 1 { + return Device{}, false + } + now := s.now().UTC() + d.LastSeenAt = now + if now.Sub(s.persisted[id]) >= lastSeenEvery { + // Best effort: a failed write must not lock a paired device out. + _ = s.saveLocked() + } + return *d, true +} + +// List returns the devices, oldest first. +func (s *Devices) List() []Device { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]Device, 0, len(s.byID)) + for _, d := range s.byID { + out = append(out, *d) + } + sort.Slice(out, func(i, j int) bool { + if !out[i].CreatedAt.Equal(out[j].CreatedAt) { + return out[i].CreatedAt.Before(out[j].CreatedAt) + } + return out[i].ID < out[j].ID + }) + return out +} + +// Remove deletes a device. The bool is false when no device has that id. +func (s *Devices) Remove(id string) (Device, bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + d, found := s.byID[id] + if !found { + return Device{}, false, nil + } + delete(s.byID, id) + if err := s.saveLocked(); err != nil { + s.byID[id] = d + return Device{}, false, err + } + delete(s.persisted, id) + return *d, true, nil +} + +func (s *Devices) saveLocked() error { + list := make([]Device, 0, len(s.byID)) + for _, d := range s.byID { + list = append(list, *d) + } + sort.Slice(list, func(i, j int) bool { return list[i].ID < list[j].ID }) + data, err := json.MarshalIndent(list, "", " ") + if err != nil { + return fmt.Errorf("encode %s: %w", devicesFile, err) + } + if err := s.dir.WriteFile(devicesFile, append(data, '\n')); err != nil { + return err + } + for _, d := range list { + s.persisted[d.ID] = d.LastSeenAt + } + return nil +} + +func hashToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} diff --git a/agent/internal/state/dir.go b/agent/internal/state/dir.go new file mode 100644 index 0000000..88b9227 --- /dev/null +++ b/agent/internal/state/dir.go @@ -0,0 +1,72 @@ +// Package state keeps what the agent must remember between runs: the folder +// it owns and the list of paired devices. +package state + +import ( + "errors" + "fmt" + "os" + "path/filepath" +) + +// Dir is the state folder. Only the user the agent runs as may enter it. +type Dir struct{ path string } + +// Open creates the folder if needed (mode 0700) and checks it is writable. +func Open(path string) (*Dir, error) { + if path == "" { + return nil, errors.New("state folder path is empty") + } + if err := os.MkdirAll(path, 0o700); err != nil { + return nil, fmt.Errorf("state folder %s: %w", path, err) + } + if err := os.Chmod(path, 0o700); err != nil { + return nil, fmt.Errorf("state folder %s: %w", path, err) + } + probe, err := os.CreateTemp(path, ".probe-*") + if err != nil { + return nil, fmt.Errorf("state folder %s is not writable: %w", path, err) + } + probe.Close() + os.Remove(probe.Name()) + return &Dir{path: path}, nil +} + +// Path returns the full path of a file in the folder. +func (d *Dir) Path(name string) string { return filepath.Join(d.path, name) } + +// ReadFile reads a file from the folder. +func (d *Dir) ReadFile(name string) ([]byte, error) { return os.ReadFile(d.Path(name)) } + +// WriteFile replaces a file atomically: the data goes to a temporary file in +// the same folder (mode 0600), is synced, then renamed over the target. +func (d *Dir) WriteFile(name string, data []byte) error { + tmp, err := os.CreateTemp(d.path, "."+name+".*") + if err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + tmpName := tmp.Name() + fail := func(err error) error { + tmp.Close() + os.Remove(tmpName) + return fmt.Errorf("write %s: %w", name, err) + } + if err := tmp.Chmod(0o600); err != nil { + return fail(err) + } + if _, err := tmp.Write(data); err != nil { + return fail(err) + } + if err := tmp.Sync(); err != nil { + return fail(err) + } + if err := tmp.Close(); err != nil { + os.Remove(tmpName) + return fmt.Errorf("write %s: %w", name, err) + } + if err := os.Rename(tmpName, d.Path(name)); err != nil { + os.Remove(tmpName) + return fmt.Errorf("write %s: %w", name, err) + } + return nil +} diff --git a/agent/internal/state/state_test.go b/agent/internal/state/state_test.go new file mode 100644 index 0000000..6c7d9a4 --- /dev/null +++ b/agent/internal/state/state_test.go @@ -0,0 +1,259 @@ +package state + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func openTemp(t *testing.T) *Dir { + t.Helper() + d, err := Open(filepath.Join(t.TempDir(), "data")) + if err != nil { + t.Fatalf("Open: %v", err) + } + return d +} + +type clock struct{ t time.Time } + +func (c *clock) now() time.Time { return c.t } +func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) } + +func newClock() *clock { return &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} } + +func TestOpenCreatesAPrivateFolder(t *testing.T) { + path := filepath.Join(t.TempDir(), "a", "b") + if _, err := Open(path); err != nil { + t.Fatalf("Open: %v", err) + } + info, err := os.Stat(path) + if err != nil || !info.IsDir() { + t.Fatalf("folder missing: %v", err) + } + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o700 { + t.Fatalf("mode = %v, want 0700", info.Mode().Perm()) + } +} + +func TestOpenRejectsAnEmptyPathAndAFile(t *testing.T) { + if _, err := Open(""); err == nil { + t.Fatal("empty path accepted") + } + file := filepath.Join(t.TempDir(), "f") + if err := os.WriteFile(file, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := Open(file); err == nil { + t.Fatal("a plain file accepted as the state folder") + } +} + +func TestWriteFileIsAtomicAndPrivate(t *testing.T) { + d := openTemp(t) + if err := d.WriteFile("x.json", []byte("one")); err != nil { + t.Fatalf("WriteFile: %v", err) + } + if err := d.WriteFile("x.json", []byte("two")); err != nil { + t.Fatalf("WriteFile: %v", err) + } + got, err := d.ReadFile("x.json") + if err != nil || string(got) != "two" { + t.Fatalf("read = %q, %v", got, err) + } + entries, _ := os.ReadDir(filepath.Dir(d.Path("x.json"))) + if len(entries) != 1 { + t.Fatalf("leftover files: %v", entries) + } + if runtime.GOOS != "windows" { + info, _ := os.Stat(d.Path("x.json")) + if info.Mode().Perm() != 0o600 { + t.Fatalf("mode = %v, want 0600", info.Mode().Perm()) + } + } +} + +func TestAddReturnsATokenThatAuthenticates(t *testing.T) { + d := openTemp(t) + s, err := LoadDevices(d, newClock().now) + if err != nil { + t.Fatal(err) + } + dev, token, err := s.Add(" Pixel 8\n", RoleReadOnly) + if err != nil { + t.Fatalf("Add: %v", err) + } + if dev.Name != "Pixel 8" || dev.Role != RoleReadOnly || len(dev.ID) != 8 { + t.Fatalf("device = %+v", dev) + } + if !strings.HasPrefix(token, "dm1."+dev.ID+".") || len(token) != len("dm1.")+8+1+43 { + t.Fatalf("token shape = %q", token) + } + if !IsDeviceToken(token) || IsDeviceToken("some-shared-token") { + t.Fatal("IsDeviceToken is wrong") + } + got, ok := s.Authenticate(token) + if !ok || got.ID != dev.ID { + t.Fatalf("Authenticate = %+v, %v", got, ok) + } + for _, bad := range []string{"", "dm1.", "dm1." + dev.ID, "dm1." + dev.ID + ".wrong", "dm1.ffffffff.x", token + "x", strings.ToUpper(token)} { + if _, ok := s.Authenticate(bad); ok { + t.Fatalf("accepted %q", bad) + } + } +} + +func TestTheTokenIsNotStored(t *testing.T) { + d := openTemp(t) + s, _ := LoadDevices(d, newClock().now) + _, token, err := s.Add("phone", RoleFull) + if err != nil { + t.Fatal(err) + } + raw, err := d.ReadFile("devices.json") + if err != nil { + t.Fatal(err) + } + secret := token[strings.LastIndex(token, ".")+1:] + if strings.Contains(string(raw), secret) { + t.Fatal("the token secret is in devices.json") + } +} + +func TestDevicesSurviveAReload(t *testing.T) { + d := openTemp(t) + c := newClock() + s, _ := LoadDevices(d, c.now) + a, tokenA, _ := s.Add("a", RoleFull) + c.advance(time.Second) + b, _, _ := s.Add("b", RoleReadOnly) + + again, err := LoadDevices(d, c.now) + if err != nil { + t.Fatalf("reload: %v", err) + } + list := again.List() + if len(list) != 2 || list[0].ID != a.ID || list[1].ID != b.ID { + t.Fatalf("list = %+v", list) + } + if _, ok := again.Authenticate(tokenA); !ok { + t.Fatal("token no longer authenticates after a reload") + } +} + +func TestRemoveStopsAuthentication(t *testing.T) { + d := openTemp(t) + s, _ := LoadDevices(d, newClock().now) + dev, token, _ := s.Add("phone", RoleFull) + removed, ok, err := s.Remove(dev.ID) + if err != nil || !ok || removed.ID != dev.ID { + t.Fatalf("Remove = %+v, %v, %v", removed, ok, err) + } + if _, ok := s.Authenticate(token); ok { + t.Fatal("a removed device still authenticates") + } + if _, ok, _ := s.Remove(dev.ID); ok { + t.Fatal("removing twice reported success") + } + again, _ := LoadDevices(d, newClock().now) + if len(again.List()) != 0 { + t.Fatal("the removed device came back after a reload") + } +} + +func TestLastSeenReachesTheDiskAtMostOnceAMinute(t *testing.T) { + d := openTemp(t) + c := newClock() + s, _ := LoadDevices(d, c.now) + dev, token, _ := s.Add("phone", RoleFull) + + onDisk := func() time.Time { + t.Helper() + again, err := LoadDevices(d, c.now) + if err != nil { + t.Fatal(err) + } + return again.List()[0].LastSeenAt + } + c.advance(30 * time.Second) + s.Authenticate(token) + if !onDisk().Equal(dev.CreatedAt) { + t.Fatal("last seen was written within the minute") + } + if !s.List()[0].LastSeenAt.Equal(c.now()) { + t.Fatal("last seen is not current in memory") + } + c.advance(31 * time.Second) + s.Authenticate(token) + if !onDisk().Equal(c.now()) { + t.Fatal("last seen was not written after a minute") + } +} + +func TestADamagedFileStopsTheLoad(t *testing.T) { + for name, content := range map[string]string{ + "not json": "{", + "incomplete": `[{"id":"","name":"x","role":"full","tokenHash":""}]`, + "bad role": `[{"id":"abcd1234","name":"x","role":"admin","tokenHash":"` + strings.Repeat("a", 64) + `"}]`, + } { + d := openTemp(t) + if err := d.WriteFile("devices.json", []byte(content)); err != nil { + t.Fatal(err) + } + if _, err := LoadDevices(d, newClock().now); err == nil || !strings.Contains(err.Error(), "damaged") { + t.Fatalf("%s: err = %v, want a damaged-file error", name, err) + } + } +} + +func TestAFailedWriteLeavesNoDeviceBehind(t *testing.T) { + d := openTemp(t) + s, _ := LoadDevices(d, newClock().now) + kept, keptToken, err := s.Add("kept", RoleFull) + if err != nil { + t.Fatal(err) + } + // The folder disappears: nothing can be written any more. + if err := os.RemoveAll(d.Path("")); err != nil { + t.Fatal(err) + } + if _, _, err := s.Add("lost", RoleFull); err == nil { + t.Fatal("Add reported success although nothing could be stored") + } + if list := s.List(); len(list) != 1 || list[0].ID != kept.ID { + t.Fatalf("list = %+v, want only the device that was stored", list) + } + if _, _, err := s.Remove(kept.ID); err == nil { + t.Fatal("Remove reported success although nothing could be stored") + } + // A device whose removal could not be stored keeps working. + if _, ok := s.Authenticate(keptToken); !ok { + t.Fatal("the device was dropped although its removal failed") + } +} + +func TestCleanName(t *testing.T) { + cases := map[string]string{ + "": "device", + " ": "device", + "Pixel 8": "Pixel 8", + "a\x00b\x1b[31mc": "ab[31mc", + strings.Repeat("x", 60): strings.Repeat("x", 40), + "tab\tname": "tabname", + } + for in, want := range cases { + if got := CleanName(in); got != want { + t.Errorf("CleanName(%q) = %q, want %q", in, got, want) + } + } +} + +func TestAddRejectsAnUnknownRole(t *testing.T) { + s, _ := LoadDevices(openTemp(t), newClock().now) + if _, _, err := s.Add("x", Role("admin")); err == nil { + t.Fatal("unknown role accepted") + } +} From 707eb94ba0fc880db3ce1babd205f9483f11637c Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 03:59:12 +0530 Subject: [PATCH 03/32] feat(agent): TLS identity with a pinnable fingerprint --- .../internal/tlsid/testdata/fingerprint.json | 5 + agent/internal/tlsid/tlsid.go | 186 +++++++++++ agent/internal/tlsid/tlsid_test.go | 291 ++++++++++++++++++ 3 files changed, 482 insertions(+) create mode 100644 agent/internal/tlsid/testdata/fingerprint.json create mode 100644 agent/internal/tlsid/tlsid.go create mode 100644 agent/internal/tlsid/tlsid_test.go diff --git a/agent/internal/tlsid/testdata/fingerprint.json b/agent/internal/tlsid/testdata/fingerprint.json new file mode 100644 index 0000000..3add74c --- /dev/null +++ b/agent/internal/tlsid/testdata/fingerprint.json @@ -0,0 +1,5 @@ +{ + "note": "Shared with the app: a certificate (DER, base64) and the fingerprint both sides must compute for it. The fingerprint is SHA-256 over the SubjectPublicKeyInfo, base64url without padding.", + "certificateDerBase64": "MIIBkDCCATWgAwIBAgIQTlYK/6Ng/przNr5TaGAH+zAKBggqhkjOPQQDAjAeMRwwGgYDVQQDExNkb2NrZXItbW9iaWxlLWFnZW50MB4XDTI2MTAwNjIzMDAwMFoXDTM2MTAwNDAwMDAwMFowHjEcMBoGA1UEAxMTZG9ja2VyLW1vYmlsZS1hZ2VudDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABIpvPZWDBjV6m4jtmCvLMQDnsu9QVaGkH9UpanF9uD7HhWvbvBRv7ec0S1Am2wWRPco5T3JB1KRjXTRZgUGpiOyjVTBTMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMB4GA1UdEQQXMBWCE2RvY2tlci1tb2JpbGUtYWdlbnQwCgYIKoZIzj0EAwIDSQAwRgIhAKrSPOzFRTr7ajlxCvyfE2nuYJom67O9/mos+ebp/TtVAiEApIRIJFcOTl5RBXW+QAkFwsNa2om4gaP6rxsEAEg5C60=", + "fingerprint": "OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI" +} diff --git a/agent/internal/tlsid/tlsid.go b/agent/internal/tlsid/tlsid.go new file mode 100644 index 0000000..8467b03 --- /dev/null +++ b/agent/internal/tlsid/tlsid.go @@ -0,0 +1,186 @@ +// Package tlsid owns the agent's TLS identity: one long-lived key, a +// self-signed certificate around it, and the fingerprint phones pin. +package tlsid + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/pem" + "errors" + "fmt" + "math/big" + "os" + "path/filepath" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/state" +) + +const ( + keyFile = "tls.key" + certFile = "tls.crt" + // validity is how long a certificate lasts. Phones pin the key, not the + // certificate, so a renewal changes nothing for them. + validity = 10 * 365 * 24 * time.Hour + // renewBefore is how close to expiry a certificate is reissued. + renewBefore = 30 * 24 * time.Hour +) + +// ServerName is the name the certificate is issued for. Phones do not check +// it (they pin the key); the agent's own health check does. +const ServerName = "docker-mobile-agent" + +// Fingerprint identifies the agent: SHA-256 over the DER encoding of the +// certificate's SubjectPublicKeyInfo. +type Fingerprint [sha256.Size]byte + +// String is the form used in pairing links: base64url without padding. +func (f Fingerprint) String() string { return base64.RawURLEncoding.EncodeToString(f[:]) } + +// Display is the form shown to people, in the style of an SSH key fingerprint. +func (f Fingerprint) Display() string { return "SHA256:" + f.String() } + +// LoadOrCreate returns the identity stored in dir. On first use it creates a +// P-256 key and a self-signed certificate. A certificate close to expiry is +// reissued around the same key. +func LoadOrCreate(dir *state.Dir, now time.Time) (tls.Certificate, error) { + keyPEM, keyErr := dir.ReadFile(keyFile) + certPEM, certErr := dir.ReadFile(certFile) + switch { + case errors.Is(keyErr, os.ErrNotExist) && errors.Is(certErr, os.ErrNotExist): + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return tls.Certificate{}, fmt.Errorf("generate key: %w", err) + } + der, err := x509.MarshalECPrivateKey(key) + if err != nil { + return tls.Certificate{}, fmt.Errorf("encode key: %w", err) + } + if err := dir.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})); err != nil { + return tls.Certificate{}, err + } + return issue(dir, key, now) + case keyErr != nil: + return tls.Certificate{}, fmt.Errorf("read %s: %w", keyFile, keyErr) + } + + key, err := parseKey(keyPEM) + if err != nil { + return tls.Certificate{}, fmt.Errorf("%s: %w", keyFile, err) + } + if errors.Is(certErr, os.ErrNotExist) { + return issue(dir, key, now) + } + if certErr != nil { + return tls.Certificate{}, fmt.Errorf("read %s: %w", certFile, certErr) + } + cert, err := tls.X509KeyPair(certPEM, keyPEM) + if err != nil { + return tls.Certificate{}, fmt.Errorf("%s does not belong to %s: %w", certFile, keyFile, err) + } + leaf, err := x509.ParseCertificate(cert.Certificate[0]) + if err != nil { + return tls.Certificate{}, fmt.Errorf("%s: %w", certFile, err) + } + if now.After(leaf.NotAfter.Add(-renewBefore)) { + return issue(dir, key, now) + } + cert.Leaf = leaf + return cert, nil +} + +func parseKey(keyPEM []byte) (*ecdsa.PrivateKey, error) { + block, _ := pem.Decode(keyPEM) + if block == nil || block.Type != "EC PRIVATE KEY" { + return nil, errors.New("not an EC private key in PEM form") + } + return x509.ParseECPrivateKey(block.Bytes) +} + +// issue writes a fresh self-signed certificate for key and returns the pair. +func issue(dir *state.Dir, key *ecdsa.PrivateKey, now time.Time) (tls.Certificate, error) { + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127)) + if err != nil { + return tls.Certificate{}, fmt.Errorf("serial: %w", err) + } + tmpl := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: ServerName}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(validity), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: []string{ServerName}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + return tls.Certificate{}, fmt.Errorf("create certificate: %w", err) + } + if err := dir.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})); err != nil { + return tls.Certificate{}, err + } + leaf, err := x509.ParseCertificate(der) + if err != nil { + return tls.Certificate{}, fmt.Errorf("parse new certificate: %w", err) + } + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: leaf}, nil +} + +// FingerprintOf returns the fingerprint of a loaded identity. +func FingerprintOf(cert tls.Certificate) (Fingerprint, error) { + if len(cert.Certificate) == 0 { + return Fingerprint{}, errors.New("no certificate") + } + return FingerprintOfDER(cert.Certificate[0]) +} + +// FingerprintOfDER returns the fingerprint of a DER-encoded certificate. +func FingerprintOfDER(der []byte) (Fingerprint, error) { + leaf, err := x509.ParseCertificate(der) + if err != nil { + return Fingerprint{}, fmt.Errorf("parse certificate: %w", err) + } + return sha256.Sum256(leaf.RawSubjectPublicKeyInfo), nil +} + +// ReadFingerprint returns the fingerprint of the certificate stored in the +// state folder dataDir, without creating anything. +func ReadFingerprint(dataDir string) (Fingerprint, error) { + certPEM, err := os.ReadFile(filepath.Join(dataDir, certFile)) + if err != nil { + return Fingerprint{}, err + } + block, _ := pem.Decode(certPEM) + if block == nil || block.Type != "CERTIFICATE" { + return Fingerprint{}, fmt.Errorf("%s is not a certificate in PEM form", certFile) + } + return FingerprintOfDER(block.Bytes) +} + +// LocalClientConfig is for a client on the same machine, such as the health +// check: it trusts exactly the certificate stored in the state folder +// dataDir, and nothing else. +func LocalClientConfig(dataDir string) (*tls.Config, error) { + certPEM, err := os.ReadFile(filepath.Join(dataDir, certFile)) + if err != nil { + return nil, err + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(certPEM) { + return nil, fmt.Errorf("%s is not a certificate in PEM form", certFile) + } + return &tls.Config{RootCAs: pool, ServerName: ServerName, MinVersion: tls.VersionTLS13}, nil +} + +// ServerConfig is the TLS configuration the agent listens with: its single +// certificate, TLS 1.3 only. +func ServerConfig(cert tls.Certificate) *tls.Config { + return &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13} +} diff --git a/agent/internal/tlsid/tlsid_test.go b/agent/internal/tlsid/tlsid_test.go new file mode 100644 index 0000000..38e2d9b --- /dev/null +++ b/agent/internal/tlsid/tlsid_test.go @@ -0,0 +1,291 @@ +package tlsid + +import ( + "crypto/ecdsa" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/json" + "net" + "os" + "path/filepath" + "testing" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/state" +) + +var t0 = time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + +func openTemp(t *testing.T) *state.Dir { + t.Helper() + d, err := state.Open(filepath.Join(t.TempDir(), "data")) + if err != nil { + t.Fatalf("Open: %v", err) + } + return d +} + +func TestFirstUseCreatesAP256IdentityValidForTenYears(t *testing.T) { + d := openTemp(t) + cert, err := LoadOrCreate(d, t0) + if err != nil { + t.Fatalf("LoadOrCreate: %v", err) + } + key, ok := cert.PrivateKey.(*ecdsa.PrivateKey) + if !ok || key.Curve.Params().Name != "P-256" { + t.Fatalf("key = %T, want ECDSA P-256", cert.PrivateKey) + } + if cert.Leaf == nil { + t.Fatal("Leaf is not set") + } + if got := cert.Leaf.NotAfter.Sub(t0); got != validity { + t.Fatalf("validity = %v, want %v", got, validity) + } + for _, name := range []string{"tls.key", "tls.crt"} { + if _, err := os.Stat(d.Path(name)); err != nil { + t.Fatalf("%s was not written: %v", name, err) + } + } +} + +func TestASecondLoadReturnsTheSameIdentity(t *testing.T) { + d := openTemp(t) + first, _ := LoadOrCreate(d, t0) + second, err := LoadOrCreate(d, t0.Add(24*time.Hour)) + if err != nil { + t.Fatalf("LoadOrCreate: %v", err) + } + if string(first.Certificate[0]) != string(second.Certificate[0]) { + t.Fatal("the certificate changed between two loads") + } +} + +func TestACertificateCloseToExpiryIsReissuedAroundTheSameKey(t *testing.T) { + d := openTemp(t) + first, _ := LoadOrCreate(d, t0) + fpBefore, _ := FingerprintOf(first) + + late := t0.Add(validity - 29*24*time.Hour) + second, err := LoadOrCreate(d, late) + if err != nil { + t.Fatalf("LoadOrCreate: %v", err) + } + if string(first.Certificate[0]) == string(second.Certificate[0]) { + t.Fatal("the certificate was not reissued") + } + if got := second.Leaf.NotAfter.Sub(late); got != validity { + t.Fatalf("new validity = %v, want %v", got, validity) + } + fpAfter, _ := FingerprintOf(second) + if fpBefore != fpAfter { + t.Fatal("the fingerprint changed with the renewal") + } +} + +func TestACertificateWithMoreThanThirtyDaysLeftIsKept(t *testing.T) { + d := openTemp(t) + first, _ := LoadOrCreate(d, t0) + second, err := LoadOrCreate(d, t0.Add(validity-31*24*time.Hour)) + if err != nil { + t.Fatalf("LoadOrCreate: %v", err) + } + if string(first.Certificate[0]) != string(second.Certificate[0]) { + t.Fatal("the certificate was reissued too early") + } +} + +func TestAMissingCertificateIsReissuedForAnExistingKey(t *testing.T) { + d := openTemp(t) + first, _ := LoadOrCreate(d, t0) + fpBefore, _ := FingerprintOf(first) + if err := os.Remove(d.Path("tls.crt")); err != nil { + t.Fatal(err) + } + second, err := LoadOrCreate(d, t0) + if err != nil { + t.Fatalf("LoadOrCreate: %v", err) + } + fpAfter, _ := FingerprintOf(second) + if fpBefore != fpAfter { + t.Fatal("a new key was made although the old one was there") + } +} + +func TestDamagedFilesAreErrors(t *testing.T) { + d := openTemp(t) + LoadOrCreate(d, t0) + if err := d.WriteFile("tls.key", []byte("not a key")); err != nil { + t.Fatal(err) + } + if _, err := LoadOrCreate(d, t0); err == nil { + t.Fatal("a damaged key was accepted") + } + + d2 := openTemp(t) + LoadOrCreate(d2, t0) + other := openTemp(t) + LoadOrCreate(other, t0) + foreign, _ := other.ReadFile("tls.crt") + if err := d2.WriteFile("tls.crt", foreign); err != nil { + t.Fatal(err) + } + if _, err := LoadOrCreate(d2, t0); err == nil { + t.Fatal("a certificate for another key was accepted") + } + + d3 := openTemp(t) + LoadOrCreate(d3, t0) + if err := os.Remove(d3.Path("tls.key")); err != nil { + t.Fatal(err) + } + if _, err := LoadOrCreate(d3, t0); err == nil { + t.Fatal("a certificate without its key was accepted") + } +} + +func TestFingerprintMatchesTheSharedVector(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("testdata", "fingerprint.json")) + if err != nil { + t.Fatal(err) + } + var v struct { + CertificateDerBase64 string `json:"certificateDerBase64"` + Fingerprint string `json:"fingerprint"` + } + if err := json.Unmarshal(raw, &v); err != nil { + t.Fatal(err) + } + der, err := base64.StdEncoding.DecodeString(v.CertificateDerBase64) + if err != nil { + t.Fatal(err) + } + fp, err := FingerprintOfDER(der) + if err != nil { + t.Fatalf("FingerprintOfDER: %v", err) + } + if fp.String() != v.Fingerprint { + t.Fatalf("fingerprint = %s, want %s", fp, v.Fingerprint) + } + if fp.Display() != "SHA256:"+v.Fingerprint { + t.Fatalf("Display = %s", fp.Display()) + } + if _, err := FingerprintOfDER([]byte("junk")); err == nil { + t.Fatal("junk accepted as a certificate") + } +} + +func TestServerConfigSpeaksTLS13OnlyAndPresentsTheIdentity(t *testing.T) { + cert, _ := LoadOrCreate(openTemp(t), time.Now()) + want, _ := FingerprintOf(cert) + ln, err := tls.Listen("tcp", "127.0.0.1:0", ServerConfig(cert)) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func() { + c.(*tls.Conn).Handshake() + c.Close() + }() + } + }() + + var seen Fingerprint + client := &tls.Config{ + InsecureSkipVerify: true, + VerifyPeerCertificate: func(raw [][]byte, _ [][]*x509.Certificate) error { + fp, err := FingerprintOfDER(raw[0]) + seen = fp + return err + }, + } + conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 3 * time.Second}, "tcp", ln.Addr().String(), client) + if err != nil { + t.Fatalf("TLS 1.3 handshake: %v", err) + } + if conn.ConnectionState().Version != tls.VersionTLS13 { + t.Fatalf("version = %x", conn.ConnectionState().Version) + } + conn.Close() + if seen != want { + t.Fatal("the client saw a different fingerprint") + } + + old := &tls.Config{InsecureSkipVerify: true, MaxVersion: tls.VersionTLS12} + if c, err := tls.DialWithDialer(&net.Dialer{Timeout: 3 * time.Second}, "tcp", ln.Addr().String(), old); err == nil { + c.Close() + t.Fatal("a TLS 1.2 client was accepted") + } +} + +func TestReadFingerprintReadsWithoutCreating(t *testing.T) { + d := openTemp(t) + if _, err := ReadFingerprint(d.Path("")); !os.IsNotExist(err) { + t.Fatalf("err = %v, want not-exist", err) + } + if _, err := os.Stat(d.Path("tls.key")); !os.IsNotExist(err) { + t.Fatal("reading the fingerprint created a key") + } + cert, _ := LoadOrCreate(d, t0) + want, _ := FingerprintOf(cert) + got, err := ReadFingerprint(d.Path("")) + if err != nil || got != want { + t.Fatalf("ReadFingerprint = %v, %v", got, err) + } + if err := d.WriteFile("tls.crt", []byte("junk")); err != nil { + t.Fatal(err) + } + if _, err := ReadFingerprint(d.Path("")); err == nil { + t.Fatal("junk was accepted as a certificate") + } +} + +func TestLocalClientConfigTrustsOnlyTheStoredCertificate(t *testing.T) { + serve := func(cert tls.Certificate) string { + ln, err := tls.Listen("tcp", "127.0.0.1:0", ServerConfig(cert)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func() { + c.(*tls.Conn).Handshake() + c.Close() + }() + } + }() + return ln.Addr().String() + } + mine := openTemp(t) + myCert, _ := LoadOrCreate(mine, time.Now()) + otherCert, _ := LoadOrCreate(openTemp(t), time.Now()) + + cfg, err := LocalClientConfig(mine.Path("")) + if err != nil { + t.Fatalf("LocalClientConfig: %v", err) + } + dialer := &net.Dialer{Timeout: 3 * time.Second} + conn, err := tls.DialWithDialer(dialer, "tcp", serve(myCert), cfg) + if err != nil { + t.Fatalf("the agent's own certificate was refused: %v", err) + } + conn.Close() + if c, err := tls.DialWithDialer(dialer, "tcp", serve(otherCert), cfg); err == nil { + c.Close() + t.Fatal("another agent's certificate was accepted") + } + if _, err := LocalClientConfig(openTemp(t).Path("")); err == nil { + t.Fatal("a folder without a certificate was accepted") + } +} From 602f59f2a25603e24213aa7f5c0875ab614e9f80 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 04:03:50 +0530 Subject: [PATCH 04/32] feat(agent): pairing codes, proofs and links --- agent/internal/pairing/code.go | 137 ++++++++++++++++ agent/internal/pairing/code_test.go | 162 +++++++++++++++++++ agent/internal/pairing/testdata/vectors.json | 70 ++++++++ 3 files changed, 369 insertions(+) create mode 100644 agent/internal/pairing/code.go create mode 100644 agent/internal/pairing/code_test.go create mode 100644 agent/internal/pairing/testdata/vectors.json diff --git a/agent/internal/pairing/code.go b/agent/internal/pairing/code.go new file mode 100644 index 0000000..5f24337 --- /dev/null +++ b/agent/internal/pairing/code.go @@ -0,0 +1,137 @@ +// Package pairing implements how a phone and the agent first come to trust +// each other: a one-time code shown on the server, and a proof exchange that +// binds that code to the agent's certificate without ever sending it. +package pairing + +import ( + "crypto/hmac" + "crypto/sha256" + "fmt" + "io" + "net/url" + "strings" +) + +// CodeLen is the number of characters in a pairing code: 12 symbols of +// 5 bits each, 60 bits in all. +const CodeLen = 12 + +// alphabet is Crockford base32: digits and letters without I, L, O and U. +const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" + +// NewCode draws a random code from rand. +func NewCode(rand io.Reader) (string, error) { + raw := make([]byte, CodeLen) + if _, err := io.ReadFull(rand, raw); err != nil { + return "", fmt.Errorf("random code: %w", err) + } + out := make([]byte, CodeLen) + for i, b := range raw { + out[i] = alphabet[b&31] + } + return string(out), nil +} + +// Normalize turns what a person typed into the canonical code: upper case, +// hyphens and spaces dropped, O read as 0, I and L as 1. The bool is false +// when the result is not a valid code. +func Normalize(input string) (string, bool) { + var b strings.Builder + for _, r := range strings.ToUpper(input) { + switch r { + case '-', ' ': + continue + case 'O': + r = '0' + case 'I', 'L': + r = '1' + } + if r > 127 || !strings.ContainsRune(alphabet, r) { + return "", false + } + b.WriteRune(r) + } + if b.Len() != CodeLen { + return "", false + } + return b.String(), true +} + +// Format shows a canonical code in three groups: XXXX-XXXX-XXXX. +func Format(code string) string { + if len(code) != CodeLen { + return code + } + return code[0:4] + "-" + code[4:8] + "-" + code[8:12] +} + +const context = "docker-mobile pair v1" + +// NonceLen is the length of the random value each side contributes. +const NonceLen = 32 + +// PhoneProof is what the phone sends: an HMAC keyed with the code over the +// fingerprint the phone sees on its connection and its own nonce. +// fingerprint is 32 bytes, or empty when the agent has no certificate of its +// own (it runs behind a proxy that terminates TLS). +func PhoneProof(code string, fingerprint, phoneNonce []byte) []byte { + return proof(code, "phone", fingerprint, phoneNonce) +} + +// AgentProof is the answer: the same construction with the other label and +// both nonces, so the phone knows the agent holds the code too. +func AgentProof(code string, fingerprint, phoneNonce, agentNonce []byte) []byte { + return proof(code, "agent", fingerprint, phoneNonce, agentNonce) +} + +func proof(code, who string, fingerprint []byte, nonces ...[]byte) []byte { + mac := hmac.New(sha256.New, []byte(code)) + mac.Write([]byte(context)) + mac.Write([]byte{0}) + mac.Write([]byte(who)) + mac.Write([]byte{0}) + mac.Write([]byte{byte(len(fingerprint))}) + mac.Write(fingerprint) + for _, n := range nonces { + mac.Write(n) + } + return mac.Sum(nil) +} + +// LinkParams is what a pairing link carries. +type LinkParams struct { + // Host and Port say where the agent is reachable; both may be empty, + // and the app then asks for the address. + Host string + Port string + // Fingerprint is the pinned form (base64url); empty without a pin. + Fingerprint string + // Scheme is "https" or "http" when there is no pin; empty otherwise. + Scheme string + Code string + // Name is how the agent calls itself, shown on the confirm step. + Name string +} + +// Link builds the dockermobile://pair link, which is also the QR content. +func Link(p LinkParams) string { + q := url.Values{} + q.Set("v", "1") + if p.Host != "" { + q.Set("h", p.Host) + } + if p.Port != "" { + q.Set("p", p.Port) + } + if p.Fingerprint != "" { + q.Set("f", p.Fingerprint) + } + if p.Scheme != "" { + q.Set("s", p.Scheme) + } + q.Set("c", p.Code) + if p.Name != "" { + q.Set("n", p.Name) + } + return "dockermobile://pair?" + q.Encode() +} diff --git a/agent/internal/pairing/code_test.go b/agent/internal/pairing/code_test.go new file mode 100644 index 0000000..a2311b1 --- /dev/null +++ b/agent/internal/pairing/code_test.go @@ -0,0 +1,162 @@ +package pairing + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +type vectors struct { + Proofs []struct { + Name string `json:"name"` + Code string `json:"code"` + FingerprintHex string `json:"fingerprintHex"` + PhoneNonceHex string `json:"phoneNonceHex"` + AgentNonceHex string `json:"agentNonceHex"` + PhoneProofHex string `json:"phoneProofHex"` + AgentProofHex string `json:"agentProofHex"` + } `json:"proofs"` + Normalization []struct { + Input string `json:"input"` + Code *string `json:"code"` + } `json:"normalization"` +} + +func loadVectors(t *testing.T) vectors { + t.Helper() + raw, err := os.ReadFile(filepath.Join("testdata", "vectors.json")) + if err != nil { + t.Fatal(err) + } + var v vectors + if err := json.Unmarshal(raw, &v); err != nil { + t.Fatal(err) + } + if len(v.Proofs) == 0 || len(v.Normalization) == 0 { + t.Fatal("the vectors file is empty") + } + return v +} + +func unhex(t *testing.T, s string) []byte { + t.Helper() + b, err := hex.DecodeString(s) + if err != nil { + t.Fatal(err) + } + return b +} + +func TestProofsMatchTheSharedVectors(t *testing.T) { + for _, p := range loadVectors(t).Proofs { + fp, np, na := unhex(t, p.FingerprintHex), unhex(t, p.PhoneNonceHex), unhex(t, p.AgentNonceHex) + if got := hex.EncodeToString(PhoneProof(p.Code, fp, np)); got != p.PhoneProofHex { + t.Errorf("%s: phone proof = %s, want %s", p.Name, got, p.PhoneProofHex) + } + if got := hex.EncodeToString(AgentProof(p.Code, fp, np, na)); got != p.AgentProofHex { + t.Errorf("%s: agent proof = %s, want %s", p.Name, got, p.AgentProofHex) + } + } +} + +func TestNormalizeMatchesTheSharedVectors(t *testing.T) { + for _, n := range loadVectors(t).Normalization { + got, ok := Normalize(n.Input) + switch { + case n.Code == nil && ok: + t.Errorf("Normalize(%q) = %q, want rejected", n.Input, got) + case n.Code != nil && (!ok || got != *n.Code): + t.Errorf("Normalize(%q) = %q, %v, want %q", n.Input, got, ok, *n.Code) + } + } +} + +func TestAProofDependsOnEveryInput(t *testing.T) { + fp := bytes.Repeat([]byte{1}, 32) + np := bytes.Repeat([]byte{2}, 32) + na := bytes.Repeat([]byte{3}, 32) + base := hex.EncodeToString(PhoneProof("K7QM2XPA9TRC", fp, np)) + other := bytes.Repeat([]byte{9}, 32) + for name, got := range map[string][]byte{ + "another code": PhoneProof("K7QM2XPA9TRD", fp, np), + "another fingerprint": PhoneProof("K7QM2XPA9TRC", other, np), + "no fingerprint": PhoneProof("K7QM2XPA9TRC", nil, np), + "another nonce": PhoneProof("K7QM2XPA9TRC", fp, other), + "the agent's label": AgentProof("K7QM2XPA9TRC", fp, np, nil), + } { + if hex.EncodeToString(got) == base { + t.Errorf("%s gives the same proof", name) + } + } + if bytes.Equal(AgentProof("K7QM2XPA9TRC", fp, np, na), AgentProof("K7QM2XPA9TRC", fp, np, other)) { + t.Error("the agent proof ignores the agent nonce") + } +} + +func TestNewCodeIsCanonicalAndVaries(t *testing.T) { + seen := map[string]bool{} + for i := 0; i < 200; i++ { + code, err := NewCode(rand.Reader) + if err != nil { + t.Fatal(err) + } + if got, ok := Normalize(code); !ok || got != code { + t.Fatalf("NewCode gave %q, which is not canonical", code) + } + seen[code] = true + } + if len(seen) != 200 { + t.Fatalf("only %d distinct codes in 200 draws", len(seen)) + } + if _, err := NewCode(bytes.NewReader([]byte{1, 2, 3})); err == nil { + t.Fatal("a short random source was accepted") + } +} + +func TestNewCodeUsesTheWholeAlphabet(t *testing.T) { + raw := make([]byte, 0, 36) + for i := 0; i < 36; i++ { + raw = append(raw, byte(i)) + } + var all strings.Builder + r := bytes.NewReader(raw) + for i := 0; i < 3; i++ { + code, err := NewCode(r) + if err != nil { + t.Fatal(err) + } + all.WriteString(code) + } + if got := all.String(); got != "0123456789ABCDEFGHJKMNPQRSTVWXYZ0123" { + t.Fatalf("codes = %s", got) + } +} + +func TestFormat(t *testing.T) { + if got := Format("K7QM2XPA9TRC"); got != "K7QM-2XPA-9TRC" { + t.Fatalf("Format = %s", got) + } + if got := Format("short"); got != "short" { + t.Fatalf("Format(short) = %s", got) + } +} + +func TestLink(t *testing.T) { + got := Link(LinkParams{Host: "my-server.lan", Port: "8443", Fingerprint: "OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI", Code: "K7QM2XPA9TRC", Name: "home lab"}) + want := "dockermobile://pair?c=K7QM2XPA9TRC&f=OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI&h=my-server.lan&n=home+lab&p=8443&v=1" + if got != want { + t.Fatalf("Link =\n %s\nwant\n %s", got, want) + } + bare := Link(LinkParams{Scheme: "https", Host: "docker.example.com", Code: "K7QM2XPA9TRC"}) + if bare != "dockermobile://pair?c=K7QM2XPA9TRC&h=docker.example.com&s=https&v=1" { + t.Fatalf("Link without a pin = %s", bare) + } + if only := Link(LinkParams{Fingerprint: "abc", Code: "K7QM2XPA9TRC"}); only != "dockermobile://pair?c=K7QM2XPA9TRC&f=abc&v=1" { + t.Fatalf("Link without an address = %s", only) + } +} diff --git a/agent/internal/pairing/testdata/vectors.json b/agent/internal/pairing/testdata/vectors.json new file mode 100644 index 0000000..ec83249 --- /dev/null +++ b/agent/internal/pairing/testdata/vectors.json @@ -0,0 +1,70 @@ +{ + "note": "Shared with the app. proofs: HMAC-SHA256 keyed with the 12 ASCII bytes of the code over 'docker-mobile pair v1' 00 'phone'|'agent' 00 len(fingerprint) fingerprint phoneNonce [agentNonce]. normalization: what a typed code becomes (null = rejected).", + "proofs": [ + { + "name": "pinned certificate", + "code": "K7QM2XPA9TRC", + "fingerprintHex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "phoneNonceHex": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + "agentNonceHex": "5f5e5d5c5b5a595857565554535251505f5e5d5c5b5a59585756555453525150", + "phoneProofHex": "ffab0ccdb7d16bb8e6cbdc3d2ce216c8467ca695f06ee000ce394fbc9470f69e", + "agentProofHex": "de7767c3976036648cd8644bb2e77983229a72cf95c19b59592497984d2fc2d9" + }, + { + "name": "second pinned certificate", + "code": "0123456789AB", + "fingerprintHex": "03a231792349424dc65f1b5f9ca83beff282966a02fb57741bb89c83c2651119", + "phoneNonceHex": "4bb55ab4d5a8a2bb16af8bd6e966b60ac68dd4e482b8d9085d4dc83f3a237027", + "agentNonceHex": "d3a5a4f9f1621065d377bfc50571af708b54b666e77a923242485bb476b8b91d", + "phoneProofHex": "4b5178f9945bcfec0126c81ff6d20680a875ad0629849011f51bb7cd59e1c70b", + "agentProofHex": "d60a80c27fa89919513ac9d7f9c3fcf617887a20761b36df9d96512860a22e9c" + }, + { + "name": "no pinned certificate (behind a proxy)", + "code": "ZZZZZZZZZZZZ", + "fingerprintHex": "", + "phoneNonceHex": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + "agentNonceHex": "5f5e5d5c5b5a595857565554535251505f5e5d5c5b5a59585756555453525150", + "phoneProofHex": "cb1e6223e27a87a68bab5c8f93777aabc5a03f451c72dd3fba342cbdbf7ea3ed", + "agentProofHex": "830537614741d294c08417a6ef8a1b0a02b2e2749d84da74a7ab67f18757ef4f" + } + ], + "normalization": [ + { + "input": "K7QM-2XPA-9TRC", + "code": "K7QM2XPA9TRC" + }, + { + "input": "k7qm 2xpa 9trc", + "code": "K7QM2XPA9TRC" + }, + { + "input": " k7qm2xpa9trc ", + "code": "K7QM2XPA9TRC" + }, + { + "input": "OIL0-oil0-OIL0", + "code": "011001100110" + }, + { + "input": "K7QM-2XPA-9TR", + "code": null + }, + { + "input": "K7QM-2XPA-9TRCC", + "code": null + }, + { + "input": "K7QM-2XPA-9TRU", + "code": null + }, + { + "input": "K7QM_2XPA_9TRC", + "code": null + }, + { + "input": "", + "code": null + } + ] +} From 37e9d92b93880915fbf45aba3b6a73a55578ccd1 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 04:11:59 +0530 Subject: [PATCH 05/32] fix(agent): state writes survive a power cut --- agent/internal/state/devices.go | 4 +- agent/internal/state/dir.go | 30 +++++++- agent/internal/state/state_test.go | 115 +++++++++++++++++++++++++++-- 3 files changed, 141 insertions(+), 8 deletions(-) diff --git a/agent/internal/state/devices.go b/agent/internal/state/devices.go index 2e6f9b1..da4ae15 100644 --- a/agent/internal/state/devices.go +++ b/agent/internal/state/devices.go @@ -192,7 +192,9 @@ func (s *Devices) List() []Device { return out } -// Remove deletes a device. The bool is false when no device has that id. +// Remove deletes a device. Check the error first: when it is set the removal +// was not stored and the device is still paired, whatever the bool says. +// Without an error the bool is false when no device has that id. func (s *Devices) Remove(id string) (Device, bool, error) { s.mu.Lock() defer s.mu.Unlock() diff --git a/agent/internal/state/dir.go b/agent/internal/state/dir.go index 88b9227..2754b09 100644 --- a/agent/internal/state/dir.go +++ b/agent/internal/state/dir.go @@ -7,6 +7,8 @@ import ( "fmt" "os" "path/filepath" + "runtime" + "syscall" ) // Dir is the state folder. Only the user the agent runs as may enter it. @@ -39,7 +41,10 @@ func (d *Dir) Path(name string) string { return filepath.Join(d.path, name) } func (d *Dir) ReadFile(name string) ([]byte, error) { return os.ReadFile(d.Path(name)) } // WriteFile replaces a file atomically: the data goes to a temporary file in -// the same folder (mode 0600), is synced, then renamed over the target. +// the same folder (mode 0600), is synced, then renamed over the target, and +// the folder is synced so the rename survives a power cut. When only that +// last step fails the target has already been replaced: the error then means +// "replaced, but not known to be durable". func (d *Dir) WriteFile(name string, data []byte) error { tmp, err := os.CreateTemp(d.path, "."+name+".*") if err != nil { @@ -68,5 +73,28 @@ func (d *Dir) WriteFile(name string, data []byte) error { os.Remove(tmpName) return fmt.Errorf("write %s: %w", name, err) } + if err := syncDir(d.path); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } return nil } + +// syncDir makes a rename inside the folder durable. Windows cannot sync a +// folder and a few file systems refuse to (EINVAL); both are left alone. +func syncDir(path string) error { + if runtime.GOOS == "windows" { + return nil + } + f, err := os.Open(path) + if err != nil { + return err + } + err = f.Sync() + if closeErr := f.Close(); err == nil { + err = closeErr + } + if errors.Is(err, syscall.EINVAL) { + return nil + } + return err +} diff --git a/agent/internal/state/state_test.go b/agent/internal/state/state_test.go index 6c7d9a4..a0fb9ba 100644 --- a/agent/internal/state/state_test.go +++ b/agent/internal/state/state_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "runtime" "strings" + "sync" "testing" "time" ) @@ -18,10 +19,23 @@ func openTemp(t *testing.T) *Dir { return d } -type clock struct{ t time.Time } +// clock is a time source the tests set by hand. Goroutines may share it. +type clock struct { + mu sync.Mutex + t time.Time +} + +func (c *clock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} -func (c *clock) now() time.Time { return c.t } -func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) } +func (c *clock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} func newClock() *clock { return &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} } @@ -211,7 +225,8 @@ func TestADamagedFileStopsTheLoad(t *testing.T) { func TestAFailedWriteLeavesNoDeviceBehind(t *testing.T) { d := openTemp(t) - s, _ := LoadDevices(d, newClock().now) + c := newClock() + s, _ := LoadDevices(d, c.now) kept, keptToken, err := s.Add("kept", RoleFull) if err != nil { t.Fatal(err) @@ -229,9 +244,12 @@ func TestAFailedWriteLeavesNoDeviceBehind(t *testing.T) { if _, _, err := s.Remove(kept.ID); err == nil { t.Fatal("Remove reported success although nothing could be stored") } - // A device whose removal could not be stored keeps working. + // A device whose removal could not be stored keeps working. Two minutes + // on its last-seen time is due on disk; that write fails as well and + // must not lock the device out either. + c.advance(2 * time.Minute) if _, ok := s.Authenticate(keptToken); !ok { - t.Fatal("the device was dropped although its removal failed") + t.Fatal("the device stopped working although only writes failed") } } @@ -257,3 +275,88 @@ func TestAddRejectsAnUnknownRole(t *testing.T) { t.Fatal("unknown role accepted") } } + +func TestConcurrentUse(t *testing.T) { + d := openTemp(t) + c := newClock() + s, err := LoadDevices(d, c.now) + if err != nil { + t.Fatal(err) + } + first, token, err := s.Add("first", RoleFull) + if err != nil { + t.Fatal(err) + } + + var wg sync.WaitGroup + for i := 0; i < 4; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 300; j++ { + if got, ok := s.Authenticate(token); !ok || got.ID != first.ID { + t.Errorf("Authenticate = %+v, %v", got, ok) + return + } + } + }() + } + + // Every second device added here is removed again; the others stay. + var kept []string + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 60; i++ { + dev, _, err := s.Add("other", RoleReadOnly) + if err != nil { + t.Errorf("Add: %v", err) + return + } + if len(s.List()) < 2 { + t.Errorf("the list lost a device") + return + } + if i%2 == 0 { + kept = append(kept, dev.ID) + continue + } + if _, ok, err := s.Remove(dev.ID); err != nil || !ok { + t.Errorf("Remove = %v, %v", ok, err) + return + } + } + }() + + // The clock passes a minute five times, so last-seen times become due on + // disk while the others are at work. + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 300; i++ { + if i%60 == 0 { + c.advance(61 * time.Second) + } + s.List() + } + }() + + wg.Wait() + + if _, ok := s.Authenticate(token); !ok { + t.Fatal("the first device no longer authenticates") + } + want := map[string]bool{first.ID: true} + for _, id := range kept { + want[id] = true + } + list := s.List() + if len(list) != len(want) { + t.Fatalf("list has %d devices, want %d", len(list), len(want)) + } + for _, dev := range list { + if !want[dev.ID] { + t.Fatalf("device %s is in the list but was removed", dev.ID) + } + } +} From 71a5c68271040725f1386acebb22eac5823acfd5 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 04:15:17 +0530 Subject: [PATCH 06/32] feat(agent): pending pairing with expiry and a try limit --- agent/internal/pairing/manager.go | 180 +++++++++++++++++++ agent/internal/pairing/manager_test.go | 238 +++++++++++++++++++++++++ 2 files changed, 418 insertions(+) create mode 100644 agent/internal/pairing/manager.go create mode 100644 agent/internal/pairing/manager_test.go diff --git a/agent/internal/pairing/manager.go b/agent/internal/pairing/manager.go new file mode 100644 index 0000000..4a02638 --- /dev/null +++ b/agent/internal/pairing/manager.go @@ -0,0 +1,180 @@ +package pairing + +import ( + "crypto/hmac" + "encoding/hex" + "errors" + "fmt" + "io" + "sync" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/state" +) + +const ( + // Lifetime is how long a pairing code stays valid. + Lifetime = 5 * time.Minute + // MaxTries is how many wrong proofs void a pairing. + MaxTries = 5 +) + +// Outcome says how a pairing ended. +type Outcome string + +const ( + Paired Outcome = "paired" + Expired Outcome = "expired" + Replaced Outcome = "replaced" + Voided Outcome = "voided" + Cancelled Outcome = "cancelled" + Failed Outcome = "failed" +) + +// Result is delivered once to whoever started the pairing. +type Result struct { + Outcome Outcome + Device state.Device // set for Paired + Err string // set for Failed +} + +// Pairing is a pending pairing as its starter sees it. +type Pairing struct { + ID string + Code string + Role state.Role + Name string + ExpiresAt time.Time +} + +var ( + // ErrNone means there is no pairing to redeem: none was started, or it + // expired, was used, or was voided. + ErrNone = errors.New("no pairing in progress") + // ErrWrongProof means the proof did not match the pending code and the + // fingerprint of this agent. + ErrWrongProof = errors.New("wrong proof") +) + +// Redeemed is what a phone gets for a correct proof. +type Redeemed struct { + Device state.Device + Token string + AgentNonce []byte + AgentProof []byte +} + +// CreateDevice stores a new device and returns it with its token. +type CreateDevice func(name string, role state.Role) (state.Device, string, error) + +// Manager holds at most one pending pairing, in memory only. +type Manager struct { + now func() time.Time + rand io.Reader + + mu sync.Mutex + cur *pending +} + +type pending struct { + Pairing + tries int + done chan Result +} + +// NewManager returns a manager that reads time and randomness from the +// given sources. +func NewManager(now func() time.Time, rand io.Reader) *Manager { + return &Manager{now: now, rand: rand} +} + +// Start begins a pairing, replacing any pending one. The channel delivers +// exactly one Result. +func (m *Manager) Start(role state.Role, name string) (Pairing, <-chan Result, error) { + if !role.Valid() { + return Pairing{}, nil, fmt.Errorf("unknown role %q", role) + } + code, err := NewCode(m.rand) + if err != nil { + return Pairing{}, nil, err + } + idRaw := make([]byte, 8) + if _, err := io.ReadFull(m.rand, idRaw); err != nil { + return Pairing{}, nil, fmt.Errorf("random id: %w", err) + } + if name != "" { + name = state.CleanName(name) + } + p := &pending{ + Pairing: Pairing{ID: hex.EncodeToString(idRaw), Code: code, Role: role, Name: name, ExpiresAt: m.now().Add(Lifetime)}, + done: make(chan Result, 1), + } + m.mu.Lock() + defer m.mu.Unlock() + m.endLocked(Result{Outcome: Replaced}) + m.cur = p + return p.Pairing, p.done, nil +} + +// Cancel ends the pairing with that id, if it is still pending. +func (m *Manager) Cancel(id string) { m.endIf(id, Result{Outcome: Cancelled}) } + +// Expire ends the pairing with that id as expired, if it is still pending. +func (m *Manager) Expire(id string) { m.endIf(id, Result{Outcome: Expired}) } + +func (m *Manager) endIf(id string, r Result) { + m.mu.Lock() + defer m.mu.Unlock() + if m.cur != nil && m.cur.ID == id { + m.endLocked(r) + } +} + +// endLocked delivers r to the pending pairing's starter and forgets it. +func (m *Manager) endLocked(r Result) { + if m.cur == nil { + return + } + m.cur.done <- r + m.cur = nil +} + +// Redeem checks a phone's proof against the pending pairing. fingerprint is +// this agent's own (empty when it has no certificate). A correct proof uses +// the pairing up: create stores the device, and the answer carries the +// agent's proof and the token. +func (m *Manager) Redeem(fingerprint, phoneNonce, proof []byte, phoneName string, create CreateDevice) (Redeemed, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.cur != nil && !m.now().Before(m.cur.ExpiresAt) { + m.endLocked(Result{Outcome: Expired}) + } + p := m.cur + if p == nil { + return Redeemed{}, ErrNone + } + if len(phoneNonce) != NonceLen || !hmac.Equal(proof, PhoneProof(p.Code, fingerprint, phoneNonce)) { + p.tries++ + if p.tries >= MaxTries { + m.endLocked(Result{Outcome: Voided}) + } + return Redeemed{}, ErrWrongProof + } + agentNonce := make([]byte, NonceLen) + if _, err := io.ReadFull(m.rand, agentNonce); err != nil { + m.endLocked(Result{Outcome: Failed, Err: err.Error()}) + return Redeemed{}, fmt.Errorf("random nonce: %w", err) + } + name := p.Name + if name == "" { + name = phoneName + } + dev, token, err := create(name, p.Role) + if err != nil { + m.endLocked(Result{Outcome: Failed, Err: err.Error()}) + return Redeemed{}, fmt.Errorf("store device: %w", err) + } + out := Redeemed{Device: dev, Token: token, AgentNonce: agentNonce, AgentProof: AgentProof(p.Code, fingerprint, phoneNonce, agentNonce)} + m.endLocked(Result{Outcome: Paired, Device: dev}) + return out, nil +} diff --git a/agent/internal/pairing/manager_test.go b/agent/internal/pairing/manager_test.go new file mode 100644 index 0000000..cf4e5f2 --- /dev/null +++ b/agent/internal/pairing/manager_test.go @@ -0,0 +1,238 @@ +package pairing + +import ( + "bytes" + "crypto/rand" + "errors" + "testing" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/state" +) + +type clock struct{ t time.Time } + +func (c *clock) now() time.Time { return c.t } +func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) } + +func newClock() *clock { return &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} } + +var ( + agentFP = bytes.Repeat([]byte{7}, 32) + nonce = bytes.Repeat([]byte{4}, NonceLen) +) + +// creator records what Redeem asked to store. +type creator struct { + calls []string + err error +} + +func (c *creator) create(name string, role state.Role) (state.Device, string, error) { + c.calls = append(c.calls, name+"/"+string(role)) + if c.err != nil { + return state.Device{}, "", c.err + } + return state.Device{ID: "abcd1234", Name: name, Role: role}, "dm1.abcd1234.secret", nil +} + +func result(t *testing.T, ch <-chan Result) Result { + t.Helper() + select { + case r := <-ch: + return r + default: + t.Fatal("no result was delivered") + return Result{} + } +} + +func pendingStill(t *testing.T, ch <-chan Result) { + t.Helper() + select { + case r := <-ch: + t.Fatalf("the pairing ended early: %+v", r) + default: + } +} + +func TestACorrectProofPairsOnce(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + p, done, err := m.Start(state.RoleReadOnly, "") + if err != nil { + t.Fatal(err) + } + if len(p.Code) != CodeLen || p.Role != state.RoleReadOnly || p.ID == "" { + t.Fatalf("pairing = %+v", p) + } + c := &creator{} + got, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "Pixel 8", c.create) + if err != nil { + t.Fatalf("Redeem: %v", err) + } + if got.Token != "dm1.abcd1234.secret" || got.Device.Name != "Pixel 8" || got.Device.Role != state.RoleReadOnly { + t.Fatalf("redeemed = %+v", got) + } + if len(got.AgentNonce) != NonceLen || !bytes.Equal(got.AgentProof, AgentProof(p.Code, agentFP, nonce, got.AgentNonce)) { + t.Fatal("the agent proof does not verify") + } + if r := result(t, done); r.Outcome != Paired || r.Device.ID != "abcd1234" { + t.Fatalf("result = %+v", r) + } + // Single use: the same proof again finds nothing. + if _, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "again", c.create); !errors.Is(err, ErrNone) { + t.Fatalf("second redeem err = %v, want ErrNone", err) + } + if len(c.calls) != 1 { + t.Fatalf("create calls = %v", c.calls) + } +} + +func TestTheNameGivenAtStartWins(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + p, _, _ := m.Start(state.RoleFull, " kitchen tablet ") + if p.Name != "kitchen tablet" { + t.Fatalf("name = %q", p.Name) + } + c := &creator{} + if _, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "Pixel 8", c.create); err != nil { + t.Fatal(err) + } + if c.calls[0] != "kitchen tablet/full" { + t.Fatalf("create got %v", c.calls) + } +} + +func TestSomeoneInTheMiddleCannotPair(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + p, done, _ := m.Start(state.RoleFull, "") + c := &creator{} + // The phone saw the attacker's certificate, so its proof is bound to that. + attackerFP := bytes.Repeat([]byte{8}, 32) + relayed := PhoneProof(p.Code, attackerFP, nonce) + if _, err := m.Redeem(agentFP, nonce, relayed, "Pixel 8", c.create); !errors.Is(err, ErrWrongProof) { + t.Fatalf("err = %v, want ErrWrongProof", err) + } + if len(c.calls) != 0 { + t.Fatal("a device was created for a relayed proof") + } + pendingStill(t, done) +} + +func TestFiveWrongProofsVoidThePairing(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + p, done, _ := m.Start(state.RoleFull, "") + c := &creator{} + wrong := bytes.Repeat([]byte{0}, 32) + for i := 1; i <= MaxTries; i++ { + if i == MaxTries { + pendingStill(t, done) + } + if _, err := m.Redeem(agentFP, nonce, wrong, "x", c.create); !errors.Is(err, ErrWrongProof) { + t.Fatalf("try %d: err = %v", i, err) + } + } + if r := result(t, done); r.Outcome != Voided { + t.Fatalf("result = %+v", r) + } + if _, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "x", c.create); !errors.Is(err, ErrNone) { + t.Fatalf("the right proof after voiding: err = %v, want ErrNone", err) + } +} + +func TestAWrongNonceLengthIsAWrongProof(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + p, _, _ := m.Start(state.RoleFull, "") + short := []byte{1, 2, 3} + if _, err := m.Redeem(agentFP, short, PhoneProof(p.Code, agentFP, short), "x", (&creator{}).create); !errors.Is(err, ErrWrongProof) { + t.Fatalf("err = %v, want ErrWrongProof", err) + } +} + +func TestACodeExpiresAfterFiveMinutes(t *testing.T) { + c := newClock() + m := NewManager(c.now, rand.Reader) + p, done, _ := m.Start(state.RoleFull, "") + if !p.ExpiresAt.Equal(c.now().Add(Lifetime)) { + t.Fatalf("expiry = %v", p.ExpiresAt) + } + c.advance(Lifetime - time.Second) + pendingStill(t, done) + c.advance(time.Second) + if _, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "x", (&creator{}).create); !errors.Is(err, ErrNone) { + t.Fatalf("err = %v, want ErrNone", err) + } + if r := result(t, done); r.Outcome != Expired { + t.Fatalf("result = %+v", r) + } +} + +func TestANewPairingReplacesThePendingOne(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + first, firstDone, _ := m.Start(state.RoleFull, "") + second, secondDone, _ := m.Start(state.RoleFull, "") + if r := result(t, firstDone); r.Outcome != Replaced { + t.Fatalf("first result = %+v", r) + } + c := &creator{} + if _, err := m.Redeem(agentFP, nonce, PhoneProof(first.Code, agentFP, nonce), "x", c.create); !errors.Is(err, ErrWrongProof) { + t.Fatalf("the replaced code: err = %v, want ErrWrongProof", err) + } + if _, err := m.Redeem(agentFP, nonce, PhoneProof(second.Code, agentFP, nonce), "x", c.create); err != nil { + t.Fatalf("the new code: %v", err) + } + if r := result(t, secondDone); r.Outcome != Paired { + t.Fatalf("second result = %+v", r) + } +} + +func TestCancelAndExpireOnlyTouchTheirOwnPairing(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + old, _, _ := m.Start(state.RoleFull, "") + cur, done, _ := m.Start(state.RoleFull, "") + m.Cancel(old.ID) + m.Expire(old.ID) + pendingStill(t, done) + m.Cancel(cur.ID) + if r := result(t, done); r.Outcome != Cancelled { + t.Fatalf("result = %+v", r) + } + m.Cancel(cur.ID) // already gone: nothing happens + + p, done2, _ := m.Start(state.RoleFull, "") + m.Expire(p.ID) + if r := result(t, done2); r.Outcome != Expired { + t.Fatalf("result = %+v", r) + } +} + +func TestAFailedStoreEndsThePairingAsFailed(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + p, done, _ := m.Start(state.RoleFull, "") + c := &creator{err: errors.New("disk full")} + if _, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "x", c.create); err == nil { + t.Fatal("a failed store was reported as success") + } + if r := result(t, done); r.Outcome != Failed || r.Err != "disk full" { + t.Fatalf("result = %+v", r) + } +} + +func TestPairingWithoutACertificateUsesAnEmptyFingerprint(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + p, _, _ := m.Start(state.RoleFull, "") + c := &creator{} + if _, err := m.Redeem(nil, nonce, PhoneProof(p.Code, agentFP, nonce), "x", c.create); !errors.Is(err, ErrWrongProof) { + t.Fatalf("a proof bound to a fingerprint was accepted without one: %v", err) + } + if _, err := m.Redeem(nil, nonce, PhoneProof(p.Code, nil, nonce), "x", c.create); err != nil { + t.Fatalf("Redeem: %v", err) + } +} + +func TestStartRejectsAnUnknownRole(t *testing.T) { + m := NewManager(newClock().now, rand.Reader) + if _, _, err := m.Start(state.Role("admin"), ""); err == nil { + t.Fatal("unknown role accepted") + } +} From ca7828ac0ede849e5f505c1f182a7ab69574c82c Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 04:20:15 +0530 Subject: [PATCH 07/32] feat(agent): allow list for read-only devices --- agent/internal/policy/policy.go | 68 ++++++++++ agent/internal/policy/policy_test.go | 182 +++++++++++++++++++++++++++ 2 files changed, 250 insertions(+) create mode 100644 agent/internal/policy/policy.go create mode 100644 agent/internal/policy/policy_test.go diff --git a/agent/internal/policy/policy.go b/agent/internal/policy/policy.go new file mode 100644 index 0000000..9b9835b --- /dev/null +++ b/agent/internal/policy/policy.go @@ -0,0 +1,68 @@ +// Package policy decides which Docker requests a read-only device may send. +// It denies by default: only requests on a short list of reads pass. +package policy + +import ( + "net/http" + "regexp" + "strings" +) + +// Segment shapes. An id or name starts with a letter or digit; an image +// reference may also contain "/", ":" and "@". +const ( + idSeg = `[A-Za-z0-9][A-Za-z0-9_.-]*` + imageSeg = `[A-Za-z0-9][A-Za-z0-9_.:@/-]*` +) + +var apiVersion = regexp.MustCompile(`^/v[0-9]+\.[0-9]+(/|$)`) + +// readOnly is every read the app performs. +var readOnly = []*regexp.Regexp{ + regexp.MustCompile(`^/_ping$`), + regexp.MustCompile(`^/version$`), + regexp.MustCompile(`^/info$`), + regexp.MustCompile(`^/system/df$`), + regexp.MustCompile(`^/events$`), + regexp.MustCompile(`^/containers/json$`), + regexp.MustCompile(`^/containers/` + idSeg + `/(json|logs|stats)$`), + regexp.MustCompile(`^/images/json$`), + regexp.MustCompile(`^/images/` + imageSeg + `/(json|history)$`), + regexp.MustCompile(`^/networks$`), + regexp.MustCompile(`^/networks/` + idSeg + `$`), + regexp.MustCompile(`^/volumes$`), + regexp.MustCompile(`^/volumes/` + idSeg + `$`), + regexp.MustCompile(`^/agent/v1/whoami$`), +} + +// AllowedReadOnly reports whether a read-only device may send a request with +// this method and path. escapedPath is the path exactly as it will be +// forwarded (r.URL.EscapedPath()). +func AllowedReadOnly(method, escapedPath string) bool { + if method != http.MethodGet && method != http.MethodHead { + return false + } + // Refuse anything a server further down might read differently than we + // do: percent-encoding, dot segments, empty segments, backslashes. + if strings.ContainsAny(escapedPath, `%\`) || strings.Contains(escapedPath, "//") { + return false + } + for _, seg := range strings.Split(escapedPath, "/") { + if seg == "." || seg == ".." { + return false + } + } + path := escapedPath + if loc := apiVersion.FindStringIndex(path); loc != nil { + path = path[loc[1]-1:] + if !strings.HasPrefix(path, "/") { + return false + } + } + for _, re := range readOnly { + if re.MatchString(path) { + return true + } + } + return false +} diff --git a/agent/internal/policy/policy_test.go b/agent/internal/policy/policy_test.go new file mode 100644 index 0000000..50855a4 --- /dev/null +++ b/agent/internal/policy/policy_test.go @@ -0,0 +1,182 @@ +package policy + +import "testing" + +const id = "3f2a9c1b7d4e5f60718293a4b5c6d7e8f9a0b1c2d3e4f5061728394a5b6c7d8e" + +func TestEveryReadTheAppMakesIsAllowed(t *testing.T) { + paths := []string{ + "/_ping", + "/version", + "/info", + "/system/df", + "/events", + "/containers/json", + "/containers/" + id + "/json", + "/containers/" + id + "/logs", + "/containers/" + id + "/stats", + "/containers/my_web-1.2/json", + "/images/json", + "/images/sha256:" + id + "/json", + "/images/sha256:" + id + "/history", + "/images/nginx:1.27/json", + "/images/ghcr.io/owner/app:latest/json", + "/images/registry.example.com:5000/team/app@sha256:" + id + "/history", + "/networks", + "/networks/" + id, + "/networks/bridge", + "/volumes", + "/volumes/pg_data", + "/agent/v1/whoami", + } + for _, p := range paths { + for _, prefix := range []string{"", "/v1.45", "/v1.41"} { + for _, method := range []string{"GET", "HEAD"} { + if !AllowedReadOnly(method, prefix+p) { + t.Errorf("%s %s%s was refused", method, prefix, p) + } + } + } + } +} + +func TestEverythingThatChangesSomethingIsRefused(t *testing.T) { + writes := []struct{ method, path string }{ + {"POST", "/containers/create"}, + {"POST", "/containers/" + id + "/start"}, + {"POST", "/containers/" + id + "/stop"}, + {"POST", "/containers/" + id + "/restart"}, + {"POST", "/containers/" + id + "/kill"}, + {"POST", "/containers/" + id + "/pause"}, + {"POST", "/containers/" + id + "/unpause"}, + {"POST", "/containers/" + id + "/rename"}, + {"POST", "/containers/" + id + "/exec"}, + {"POST", "/containers/prune"}, + {"DELETE", "/containers/" + id}, + {"POST", "/exec/" + id + "/resize"}, + {"POST", "/exec/" + id + "/start"}, + {"POST", "/images/create"}, + {"POST", "/images/" + id + "/tag"}, + {"POST", "/images/prune"}, + {"DELETE", "/images/" + id}, + {"POST", "/networks/create"}, + {"POST", "/networks/prune"}, + {"DELETE", "/networks/" + id}, + {"POST", "/volumes/create"}, + {"POST", "/volumes/prune"}, + {"DELETE", "/volumes/pg_data"}, + {"POST", "/build/prune"}, + {"POST", "/build"}, + {"PUT", "/containers/" + id + "/archive"}, + // A read path with a method that is not a read. + {"POST", "/containers/json"}, + {"DELETE", "/containers/" + id + "/json"}, + {"PUT", "/info"}, + {"PATCH", "/version"}, + {"OPTIONS", "/events"}, + {"CONNECT", "/_ping"}, + } + for _, w := range writes { + for _, prefix := range []string{"", "/v1.45"} { + if AllowedReadOnly(w.method, prefix+w.path) { + t.Errorf("%s %s%s was allowed", w.method, prefix, w.path) + } + } + } +} + +func TestReadsThatLeakOrAreNotUsedAreRefused(t *testing.T) { + paths := []string{ + "/", + "", + "/containers/" + id + "/archive", + "/containers/" + id + "/export", + "/containers/" + id + "/changes", + "/containers/" + id + "/top", + "/containers/" + id + "/attach/ws", + "/containers/" + id, + "/exec/" + id + "/json", + "/exec/" + id + "/ws", + "/images/get", + "/images/" + id + "/get", + "/images/search", + "/secrets", + "/configs", + "/swarm", + "/swarm/unlockkey", + "/nodes", + "/services", + "/plugins", + "/session", + "/agent/v1/pair", + "/agent/v1/devices", + "/healthz/extra", + } + for _, p := range paths { + if AllowedReadOnly("GET", p) { + t.Errorf("GET %s was allowed", p) + } + } +} + +func TestPathTricksAreRefused(t *testing.T) { + paths := []string{ + "/containers/../containers/json", + "/containers/json/..", + "/containers/./json", + "/./containers/json", + "//containers/json", + "/containers//json", + "/containers/json/", + "/containers/" + id + "/json/", + "/containers/%2e%2e/json", + "/containers/abc%2Fjson", + "/containers/abc%2fstart/json", + "/containers/abc%5cjson", + `/containers/abc\json`, + "/containers/abc/json%00", + "/containers/abc/json;x", + "/containers/abc/json?x", + "/containers/-abc/json", + "/containers/.hidden/json", + "/volumes/..", + "/networks/a/b", + "/v1.45", + "/v1.45/", + "/v1.45/v1.45/containers/json", + "/v1.45x/containers/json", + "/v1/containers/json", + "/vv1.45/containers/json", + "/images/../containers/x/json", + "/images/a/../../info/json", + "/CONTAINERS/json", + " /containers/json", + } + for _, p := range paths { + if AllowedReadOnly("GET", p) { + t.Errorf("GET %q was allowed", p) + } + } +} + +func TestImageNamesMayContainSlashesButNotReachOtherRoutes(t *testing.T) { + // An image reference may hold "/", so the suffix decides: only json and + // history are reads. + for _, p := range []string{ + "/images/library/nginx/json", + "/images/a/b/c/history", + } { + if !AllowedReadOnly("GET", p) { + t.Errorf("GET %s was refused", p) + } + } + for _, p := range []string{ + "/images/library/nginx/get", + "/images/library/nginx/push", + "/images/a/json/tag", + } { + if AllowedReadOnly("GET", p) { + t.Errorf("GET %s was allowed", p) + } + } +} From 007474e6554711363613f670234a4e9a2fdedd94 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 04:32:19 +0530 Subject: [PATCH 08/32] fix(agent): stretch the pairing code before it keys the proofs --- agent/go.mod | 2 +- agent/internal/pairing/code.go | 69 ++++++++++++---- agent/internal/pairing/code_test.go | 24 +++++- agent/internal/pairing/testdata/vectors.json | 82 ++++++++++++++++++-- 4 files changed, 154 insertions(+), 23 deletions(-) diff --git a/agent/go.mod b/agent/go.mod index b51715c..027be07 100644 --- a/agent/go.mod +++ b/agent/go.mod @@ -1,5 +1,5 @@ module github.com/retransmit/docker-mobile/agent -go 1.23 +go 1.24 require github.com/gorilla/websocket v1.5.3 diff --git a/agent/internal/pairing/code.go b/agent/internal/pairing/code.go index 5f24337..93ad307 100644 --- a/agent/internal/pairing/code.go +++ b/agent/internal/pairing/code.go @@ -5,6 +5,7 @@ package pairing import ( "crypto/hmac" + "crypto/pbkdf2" "crypto/sha256" "fmt" "io" @@ -32,12 +33,22 @@ func NewCode(rand io.Reader) (string, error) { return string(out), nil } -// Normalize turns what a person typed into the canonical code: upper case, -// hyphens and spaces dropped, O read as 0, I and L as 1. The bool is false -// when the result is not a valid code. +// Normalize turns what a person typed into the canonical code: the letters a +// to z made upper case, hyphens and spaces dropped, O read as 0, I and L as +// 1. The bool is false when the result is not a valid code. +// +// Only ASCII is accepted. Anything above 127 is refused as it is, before any +// change of case, so that no letter of another script can turn into one of +// the alphabet on the way. func Normalize(input string) (string, bool) { var b strings.Builder - for _, r := range strings.ToUpper(input) { + for _, r := range input { + if r > 127 { + return "", false + } + if r >= 'a' && r <= 'z' { + r -= 'a' - 'A' + } switch r { case '-', ' ': continue @@ -46,7 +57,7 @@ func Normalize(input string) (string, bool) { case 'I', 'L': r = '1' } - if r > 127 || !strings.ContainsRune(alphabet, r) { + if !strings.ContainsRune(alphabet, r) { return "", false } b.WriteRune(r) @@ -65,28 +76,58 @@ func Format(code string) string { return code[0:4] + "-" + code[4:8] + "-" + code[8:12] } -const context = "docker-mobile pair v1" +// proofContext names the exchange and its version. It is the salt of the +// key and the first part of what both proofs authenticate. +const proofContext = "docker-mobile pair v1" + +// stretchRounds is how many rounds of PBKDF2 turn a code into the key of the +// proofs. A code holds only 60 bits, so whoever has seen one proof can try +// every code against it; the rounds make each of those tries cost this many +// times more. +const stretchRounds = 100000 // NonceLen is the length of the random value each side contributes. const NonceLen = 32 -// PhoneProof is what the phone sends: an HMAC keyed with the code over the -// fingerprint the phone sees on its connection and its own nonce. -// fingerprint is 32 bytes, or empty when the agent has no certificate of its -// own (it runs behind a proxy that terminates TLS). +// PhoneProof is what the phone sends: an HMAC keyed with the stretched code +// over the fingerprint the phone sees on its connection and its own nonce. +// +// code is a canonical code of CodeLen characters. fingerprint is 32 bytes, +// or empty when the agent has no certificate of its own (it runs behind a +// proxy that terminates TLS). phoneNonce is NonceLen bytes. None of this is +// checked here: the length of the fingerprint is written as a single byte +// and the nonce is written without one, so the caller must check the length +// of anything that came from the network before calling. func PhoneProof(code string, fingerprint, phoneNonce []byte) []byte { return proof(code, "phone", fingerprint, phoneNonce) } -// AgentProof is the answer: the same construction with the other label and -// both nonces, so the phone knows the agent holds the code too. +// AgentProof is the answer: the same construction, keyed with the stretched +// code as well, with the other label and both nonces, so the phone knows the +// agent holds the code too. +// +// It expects what PhoneProof expects, and agentNonce is NonceLen bytes too. +// The two nonces are written one after the other with nothing between them, +// so here as well the caller must check the lengths of anything that came +// from the network before calling. func AgentProof(code string, fingerprint, phoneNonce, agentNonce []byte) []byte { return proof(code, "agent", fingerprint, phoneNonce, agentNonce) } +// proofKey stretches a code into the 32-byte key of both proofs. +func proofKey(code string) []byte { + key, err := pbkdf2.Key(sha256.New, code, []byte(proofContext), stretchRounds, sha256.Size) + if err != nil { + // Only parameters the library refuses lead here, and every one of + // them is a constant. + panic("pairing: stretching the code: " + err.Error()) + } + return key +} + func proof(code, who string, fingerprint []byte, nonces ...[]byte) []byte { - mac := hmac.New(sha256.New, []byte(code)) - mac.Write([]byte(context)) + mac := hmac.New(sha256.New, proofKey(code)) + mac.Write([]byte(proofContext)) mac.Write([]byte{0}) mac.Write([]byte(who)) mac.Write([]byte{0}) diff --git a/agent/internal/pairing/code_test.go b/agent/internal/pairing/code_test.go index a2311b1..faf2643 100644 --- a/agent/internal/pairing/code_test.go +++ b/agent/internal/pairing/code_test.go @@ -18,6 +18,7 @@ type vectors struct { FingerprintHex string `json:"fingerprintHex"` PhoneNonceHex string `json:"phoneNonceHex"` AgentNonceHex string `json:"agentNonceHex"` + KeyHex string `json:"keyHex"` PhoneProofHex string `json:"phoneProofHex"` AgentProofHex string `json:"agentProofHex"` } `json:"proofs"` @@ -25,6 +26,15 @@ type vectors struct { Input string `json:"input"` Code *string `json:"code"` } `json:"normalization"` + Links []struct { + Host string `json:"host"` + Port string `json:"port"` + Fingerprint string `json:"fingerprint"` + Scheme string `json:"scheme"` + Code string `json:"code"` + Name string `json:"name"` + Link string `json:"link"` + } `json:"links"` } func loadVectors(t *testing.T) vectors { @@ -37,7 +47,7 @@ func loadVectors(t *testing.T) vectors { if err := json.Unmarshal(raw, &v); err != nil { t.Fatal(err) } - if len(v.Proofs) == 0 || len(v.Normalization) == 0 { + if len(v.Proofs) == 0 || len(v.Normalization) == 0 || len(v.Links) == 0 { t.Fatal("the vectors file is empty") } return v @@ -55,6 +65,9 @@ func unhex(t *testing.T, s string) []byte { func TestProofsMatchTheSharedVectors(t *testing.T) { for _, p := range loadVectors(t).Proofs { fp, np, na := unhex(t, p.FingerprintHex), unhex(t, p.PhoneNonceHex), unhex(t, p.AgentNonceHex) + if got := hex.EncodeToString(proofKey(p.Code)); got != p.KeyHex { + t.Errorf("%s: key = %s, want %s", p.Name, got, p.KeyHex) + } if got := hex.EncodeToString(PhoneProof(p.Code, fp, np)); got != p.PhoneProofHex { t.Errorf("%s: phone proof = %s, want %s", p.Name, got, p.PhoneProofHex) } @@ -160,3 +173,12 @@ func TestLink(t *testing.T) { t.Fatalf("Link without an address = %s", only) } } + +func TestLinkMatchesTheSharedVectors(t *testing.T) { + for _, l := range loadVectors(t).Links { + got := Link(LinkParams{Host: l.Host, Port: l.Port, Fingerprint: l.Fingerprint, Scheme: l.Scheme, Code: l.Code, Name: l.Name}) + if got != l.Link { + t.Errorf("Link for %q =\n %s\nwant\n %s", l.Name, got, l.Link) + } + } +} diff --git a/agent/internal/pairing/testdata/vectors.json b/agent/internal/pairing/testdata/vectors.json index ec83249..6f934dc 100644 --- a/agent/internal/pairing/testdata/vectors.json +++ b/agent/internal/pairing/testdata/vectors.json @@ -1,5 +1,5 @@ { - "note": "Shared with the app. proofs: HMAC-SHA256 keyed with the 12 ASCII bytes of the code over 'docker-mobile pair v1' 00 'phone'|'agent' 00 len(fingerprint) fingerprint phoneNonce [agentNonce]. normalization: what a typed code becomes (null = rejected).", + "note": "Shared with the app. key: PBKDF2-HMAC-SHA256(password = the 12 ASCII bytes of the code, salt = 'docker-mobile pair v1', rounds = 100000, length = 32 bytes). proofs: HMAC-SHA256 keyed with that key over 'docker-mobile pair v1' 00 'phone'|'agent' 00 len(fingerprint) fingerprint phoneNonce [agentNonce]. normalization: what a typed code becomes (null = rejected). links: the link the agent shows for the six fields; an empty host, port, fingerprint, scheme or name is left out, and values are form-encoded (a space is '+', a reserved or non-ASCII character is %XX for each UTF-8 byte).", "proofs": [ { "name": "pinned certificate", @@ -7,8 +7,9 @@ "fingerprintHex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "phoneNonceHex": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", "agentNonceHex": "5f5e5d5c5b5a595857565554535251505f5e5d5c5b5a59585756555453525150", - "phoneProofHex": "ffab0ccdb7d16bb8e6cbdc3d2ce216c8467ca695f06ee000ce394fbc9470f69e", - "agentProofHex": "de7767c3976036648cd8644bb2e77983229a72cf95c19b59592497984d2fc2d9" + "keyHex": "39231b583a4813def69a652cdfb5cd8c093b7292dcb8d841ceea386eb1c64b04", + "phoneProofHex": "d15073614bee6324b21b429397810e3c305a7c46e8f6f68f6657491e92600a73", + "agentProofHex": "0548c503207f4e5a5262822802b5a740d9b631dc202b6682af065a96dbf9d27d" }, { "name": "second pinned certificate", @@ -16,8 +17,9 @@ "fingerprintHex": "03a231792349424dc65f1b5f9ca83beff282966a02fb57741bb89c83c2651119", "phoneNonceHex": "4bb55ab4d5a8a2bb16af8bd6e966b60ac68dd4e482b8d9085d4dc83f3a237027", "agentNonceHex": "d3a5a4f9f1621065d377bfc50571af708b54b666e77a923242485bb476b8b91d", - "phoneProofHex": "4b5178f9945bcfec0126c81ff6d20680a875ad0629849011f51bb7cd59e1c70b", - "agentProofHex": "d60a80c27fa89919513ac9d7f9c3fcf617887a20761b36df9d96512860a22e9c" + "keyHex": "9ebc85c88d54ff2801735859161806506e7508c8552c396ebc7734027dc9ba9f", + "phoneProofHex": "b038faae3791acfc7111b033e344b9d9929024f133fab243851d890baf61fae0", + "agentProofHex": "9425a561e3c0521b6ed240e9931f6813b706111d53d5bc1c9694a3dc5b28f048" }, { "name": "no pinned certificate (behind a proxy)", @@ -25,8 +27,9 @@ "fingerprintHex": "", "phoneNonceHex": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", "agentNonceHex": "5f5e5d5c5b5a595857565554535251505f5e5d5c5b5a59585756555453525150", - "phoneProofHex": "cb1e6223e27a87a68bab5c8f93777aabc5a03f451c72dd3fba342cbdbf7ea3ed", - "agentProofHex": "830537614741d294c08417a6ef8a1b0a02b2e2749d84da74a7ab67f18757ef4f" + "keyHex": "409df586139082b24a6af3cc821d61da0da42e95b43857929ab219a0a88434ab", + "phoneProofHex": "c29667751132714735af6bb0b326c274b6e921bbbbf5577102ae9615ec92507f", + "agentProofHex": "5ab0852dabcc6eb722142682c594bff5f6f9f12d4a1149a65a4d1c9d587d632f" } ], "normalization": [ @@ -65,6 +68,71 @@ { "input": "", "code": null + }, + { + "input": "K7QM-2XPA-9TR\u0131", + "code": null + }, + { + "input": "K7QM-2XPA-9TR\u017f", + "code": null + }, + { + "input": "K7QM-2XPA-9TR\u00df", + "code": null + }, + { + "input": "K7QM\t2XPA\t9TRC", + "code": null + }, + { + "input": "K7QM-2XPA-9TRC\n", + "code": null + }, + { + "input": "K7QM\u00a02XPA\u00a09TRC", + "code": null + }, + { + "input": "K7QM\u20132XPA\u20139TRC", + "code": null + }, + { + "input": "K7QM-2XPA-\uff19TRC", + "code": null + }, + { + "input": "k7qm-2xpa-9tru", + "code": null + } + ], + "links": [ + { + "host": "192.168.1.20", + "port": "8443", + "fingerprint": "A6IxeSNJQk3GXxtfnKg77_KClmoC-1d0G7icg8JlERk", + "scheme": "", + "code": "0123456789AB", + "name": "nas", + "link": "dockermobile://pair?c=0123456789AB&f=A6IxeSNJQk3GXxtfnKg77_KClmoC-1d0G7icg8JlERk&h=192.168.1.20&n=nas&p=8443&v=1" + }, + { + "host": "docker.example.com", + "port": "443", + "fingerprint": "", + "scheme": "https", + "code": "ZZZZZZZZZZZZ", + "name": "build server", + "link": "dockermobile://pair?c=ZZZZZZZZZZZZ&h=docker.example.com&n=build+server&p=443&s=https&v=1" + }, + { + "host": "my-server.lan", + "port": "8443", + "fingerprint": "OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI", + "scheme": "", + "code": "K7QM2XPA9TRC", + "name": "R&D = lab #1 + 50% caf\u00e9", + "link": "dockermobile://pair?c=K7QM2XPA9TRC&f=OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI&h=my-server.lan&n=R%26D+%3D+lab+%231+%2B+50%25+caf%C3%A9&p=8443&v=1" } ] } From 0e05cd9ca84a7d727fefb976fd694d4277ad7aaa Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 04:49:37 +0530 Subject: [PATCH 09/32] test(agent): pin single use of a pairing under concurrent calls --- agent/internal/pairing/manager.go | 13 +- agent/internal/pairing/manager_test.go | 363 ++++++++++++++++++++++++- 2 files changed, 361 insertions(+), 15 deletions(-) diff --git a/agent/internal/pairing/manager.go b/agent/internal/pairing/manager.go index 4a02638..7731d2d 100644 --- a/agent/internal/pairing/manager.go +++ b/agent/internal/pairing/manager.go @@ -83,13 +83,22 @@ type pending struct { } // NewManager returns a manager that reads time and randomness from the -// given sources. +// given sources. Both must be safe for use by several goroutines at once, as +// time.Now and crypto/rand.Reader are: the manager's methods may be called +// concurrently, and Start uses both outside the manager's lock. func NewManager(now func() time.Time, rand io.Reader) *Manager { return &Manager{now: now, rand: rand} } // Start begins a pairing, replacing any pending one. The channel delivers -// exactly one Result. +// exactly one Result, at the moment the pairing ends. +// +// Running out of time does not end a pairing by itself: the manager has no +// timer of its own. A pairing past ExpiresAt can no longer be redeemed, but +// it stays pending, and its channel silent, until Redeem or Expire is next +// called and ends it as expired, or until Cancel or another Start ends it. +// Whoever waits on the channel therefore arranges for Expire to be called +// at ExpiresAt. func (m *Manager) Start(role state.Role, name string) (Pairing, <-chan Result, error) { if !role.Valid() { return Pairing{}, nil, fmt.Errorf("unknown role %q", role) diff --git a/agent/internal/pairing/manager_test.go b/agent/internal/pairing/manager_test.go index cf4e5f2..7ecf2ed 100644 --- a/agent/internal/pairing/manager_test.go +++ b/agent/internal/pairing/manager_test.go @@ -4,25 +4,45 @@ import ( "bytes" "crypto/rand" "errors" + "fmt" + "runtime" + "sync" + "sync/atomic" "testing" "time" "github.com/retransmit/docker-mobile/agent/internal/state" ) -type clock struct{ t time.Time } +// clock is a time source the tests set by hand. Goroutines may share it. +type clock struct { + mu sync.Mutex + t time.Time +} + +func (c *clock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} -func (c *clock) now() time.Time { return c.t } -func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) } +func (c *clock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} func newClock() *clock { return &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} } var ( agentFP = bytes.Repeat([]byte{7}, 32) nonce = bytes.Repeat([]byte{4}, NonceLen) + // wrongProof has the length of a proof and proves nothing. + wrongProof = bytes.Repeat([]byte{0}, 32) ) -// creator records what Redeem asked to store. +// creator records what Redeem asked to store. With err set it fails, and +// still returns a device and a token; neither may get past Redeem. type creator struct { calls []string err error @@ -30,10 +50,67 @@ type creator struct { func (c *creator) create(name string, role state.Role) (state.Device, string, error) { c.calls = append(c.calls, name+"/"+string(role)) - if c.err != nil { - return state.Device{}, "", c.err + return state.Device{ID: "abcd1234", Name: name, Role: role}, "dm1.abcd1234.secret", c.err +} + +// sharedCreator is a creator that many goroutines may call at once. It +// counts its calls, and every call returns a device and a token of its own. +type sharedCreator struct{ calls atomic.Int32 } + +func (c *sharedCreator) create(name string, role state.Role) (state.Device, string, error) { + n := c.calls.Add(1) + // Give the other goroutines a turn while this call is in flight: a + // manager that held them back only up to here would now let them in. + for i := 0; i < 8; i++ { + runtime.Gosched() + } + id := fmt.Sprintf("%08x", n) + return state.Device{ID: id, Name: name, Role: role}, "dm1." + id + ".secret", nil +} + +var errNoRandomness = errors.New("no randomness") + +// budgetRand is a random source that fails once it has handed out its budget +// of bytes. A negative budget never runs out. +type budgetRand struct{ left int } + +func (r *budgetRand) Read(p []byte) (int, error) { + if r.left >= 0 { + if len(p) > r.left { + return 0, errNoRandomness + } + r.left -= len(p) + } + return rand.Read(p) +} + +// handedOutNothing reports whether a redeem returned the zero value: no +// device, no token, no nonce and no proof. +func handedOutNothing(r Redeemed) bool { + return r.Device == (state.Device{}) && r.Token == "" && r.AgentNonce == nil && r.AgentProof == nil +} + +// collect reads what a pairing's channel delivers until stop is closed, then +// hands all of it over on out. It reads while the manager is at work, so a +// second result for one pairing is counted instead of blocking the manager. +func collect(ch <-chan Result, stop <-chan struct{}, out chan<- []Result) { + var got []Result + for { + select { + case r := <-ch: + got = append(got, r) + case <-stop: + for { + select { + case r := <-ch: + got = append(got, r) + default: + out <- got + return + } + } + } } - return state.Device{ID: "abcd1234", Name: name, Role: role}, "dm1.abcd1234.secret", nil } func result(t *testing.T, ch <-chan Result) Result { @@ -117,6 +194,15 @@ func TestSomeoneInTheMiddleCannotPair(t *testing.T) { t.Fatal("a device was created for a relayed proof") } pendingStill(t, done) + // Directly, over the certificate the agent really has, the code still + // works. + got, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "Pixel 8", c.create) + if err != nil || got.Token == "" { + t.Fatalf("the code after the relayed proof: redeemed = %+v, err = %v", got, err) + } + if r := result(t, done); r.Outcome != Paired { + t.Fatalf("result = %+v", r) + } } func TestFiveWrongProofsVoidThePairing(t *testing.T) { @@ -141,11 +227,19 @@ func TestFiveWrongProofsVoidThePairing(t *testing.T) { } func TestAWrongNonceLengthIsAWrongProof(t *testing.T) { - m := NewManager(newClock().now, rand.Reader) - p, _, _ := m.Start(state.RoleFull, "") - short := []byte{1, 2, 3} - if _, err := m.Redeem(agentFP, short, PhoneProof(p.Code, agentFP, short), "x", (&creator{}).create); !errors.Is(err, ErrWrongProof) { - t.Fatalf("err = %v, want ErrWrongProof", err) + for _, n := range []int{0, 31, 33, 64} { + m := NewManager(newClock().now, rand.Reader) + p, _, _ := m.Start(state.RoleFull, "") + c := &creator{} + odd := bytes.Repeat([]byte{4}, n) + // The proof is the right one for that nonce, so the length of the + // nonce is all there is to refuse. + if _, err := m.Redeem(agentFP, odd, PhoneProof(p.Code, agentFP, odd), "x", c.create); !errors.Is(err, ErrWrongProof) { + t.Fatalf("a nonce of %d bytes: err = %v, want ErrWrongProof", n, err) + } + if len(c.calls) != 0 { + t.Fatalf("a nonce of %d bytes: a device was created", n) + } } } @@ -157,6 +251,11 @@ func TestACodeExpiresAfterFiveMinutes(t *testing.T) { t.Fatalf("expiry = %v", p.ExpiresAt) } c.advance(Lifetime - time.Second) + // One second before the end the code is still alive: a wrong proof is + // answered as wrong, not as if there were nothing to redeem. + if _, err := m.Redeem(agentFP, nonce, wrongProof, "x", (&creator{}).create); !errors.Is(err, ErrWrongProof) { + t.Fatalf("one second before the end: err = %v, want ErrWrongProof", err) + } pendingStill(t, done) c.advance(time.Second) if _, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "x", (&creator{}).create); !errors.Is(err, ErrNone) { @@ -210,12 +309,76 @@ func TestAFailedStoreEndsThePairingAsFailed(t *testing.T) { m := NewManager(newClock().now, rand.Reader) p, done, _ := m.Start(state.RoleFull, "") c := &creator{err: errors.New("disk full")} - if _, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "x", c.create); err == nil { + right := PhoneProof(p.Code, agentFP, nonce) + got, err := m.Redeem(agentFP, nonce, right, "x", c.create) + if err == nil { t.Fatal("a failed store was reported as success") } + if !handedOutNothing(got) { + t.Fatalf("a failed store handed out %+v", got) + } if r := result(t, done); r.Outcome != Failed || r.Err != "disk full" { t.Fatalf("result = %+v", r) } + if _, err := m.Redeem(agentFP, nonce, right, "x", c.create); !errors.Is(err, ErrNone) { + t.Fatalf("second redeem err = %v, want ErrNone", err) + } +} + +func TestAFailedRandomSourceInStartLeavesThePendingPairingAlone(t *testing.T) { + // Start draws the code first and the id after it. + for _, tc := range []struct { + what string + budget int + }{ + {"the code", 0}, + {"the id", CodeLen}, + } { + src := &budgetRand{left: -1} + m := NewManager(newClock().now, src) + p, done, err := m.Start(state.RoleFull, "") + if err != nil { + t.Fatal(err) + } + src.left = tc.budget + if _, _, err := m.Start(state.RoleFull, ""); !errors.Is(err, errNoRandomness) { + t.Fatalf("no randomness for %s: err = %v", tc.what, err) + } + pendingStill(t, done) + // The pairing that was pending is still the one that redeems. + src.left = -1 + c := &creator{} + if _, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "x", c.create); err != nil { + t.Fatalf("no randomness for %s: the pending pairing: %v", tc.what, err) + } + if r := result(t, done); r.Outcome != Paired { + t.Fatalf("no randomness for %s: result = %+v", tc.what, r) + } + } +} + +func TestAFailedRandomSourceInRedeemEndsThePairingAsFailed(t *testing.T) { + src := &budgetRand{left: -1} + m := NewManager(newClock().now, src) + p, done, err := m.Start(state.RoleFull, "") + if err != nil { + t.Fatal(err) + } + src.left = 0 + c := &creator{} + got, err := m.Redeem(agentFP, nonce, PhoneProof(p.Code, agentFP, nonce), "x", c.create) + if !errors.Is(err, errNoRandomness) { + t.Fatalf("err = %v, want the failure of the random source", err) + } + if !handedOutNothing(got) { + t.Fatalf("a redeem without randomness handed out %+v", got) + } + if len(c.calls) != 0 { + t.Fatalf("create was called: %v", c.calls) + } + if r := result(t, done); r.Outcome != Failed || r.Err != errNoRandomness.Error() { + t.Fatalf("result = %+v", r) + } } func TestPairingWithoutACertificateUsesAnEmptyFingerprint(t *testing.T) { @@ -236,3 +399,177 @@ func TestStartRejectsAnUnknownRole(t *testing.T) { t.Fatal("unknown role accepted") } } + +func TestConcurrentRedeemsYieldOneDevice(t *testing.T) { + const callers = 16 + m := NewManager(newClock().now, rand.Reader) + p, done, err := m.Start(state.RoleFull, "") + if err != nil { + t.Fatal(err) + } + right := PhoneProof(p.Code, agentFP, nonce) + c := &sharedCreator{} + + stop := make(chan struct{}) + delivered := make(chan []Result, 1) + go collect(done, stop, delivered) + + type answer struct { + got Redeemed + err error + } + answers := make(chan answer, callers) + release := make(chan struct{}) + var wg sync.WaitGroup + for i := 0; i < callers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-release + got, err := m.Redeem(agentFP, nonce, right, "Pixel 8", c.create) + answers <- answer{got, err} + }() + } + close(release) + wg.Wait() + close(answers) + close(stop) + results := <-delivered + + var winner Redeemed + paired, none := 0, 0 + for a := range answers { + switch { + case a.err == nil: + paired++ + winner = a.got + case errors.Is(a.err, ErrNone): + none++ + if !handedOutNothing(a.got) { + t.Errorf("a redeem that found nothing handed out %+v", a.got) + } + default: + t.Errorf("Redeem: %v", a.err) + } + } + if paired != 1 || none != callers-1 { + t.Fatalf("%d redeems succeeded and %d found nothing, want 1 and %d", paired, none, callers-1) + } + if winner.Token == "" { + t.Fatalf("the redeem that succeeded has no token: %+v", winner) + } + if n := c.calls.Load(); n != 1 { + t.Fatalf("create ran %d times, want once", n) + } + if len(results) != 1 || results[0].Outcome != Paired || results[0].Device.ID != winner.Device.ID { + t.Fatalf("results = %+v, want one that says paired with device %s", results, winner.Device.ID) + } +} + +func TestConcurrentWrongProofsCancelAndStartEndEachPairingOnce(t *testing.T) { + // Enough wrong proofs to void a pairing, should they all reach the same. + const wrongTries = MaxTries + for round := 0; round < 4; round++ { + m := NewManager(newClock().now, rand.Reader) + first, firstDone, err := m.Start(state.RoleFull, "") + if err != nil { + t.Fatal(err) + } + right := PhoneProof(first.Code, agentFP, nonce) + c := &sharedCreator{} + + stop := make(chan struct{}) + firstDelivered := make(chan []Result, 1) + secondDelivered := make(chan []Result, 1) + go collect(firstDone, stop, firstDelivered) + + release := make(chan struct{}) + var wg sync.WaitGroup + var accepted atomic.Int32 + run := func(call func()) { + wg.Add(1) + go func() { + defer wg.Done() + <-release + call() + }() + } + wrong := func() { + got, err := m.Redeem(agentFP, nonce, wrongProof, "x", c.create) + if !errors.Is(err, ErrWrongProof) && !errors.Is(err, ErrNone) { + t.Errorf("round %d: a wrong proof: err = %v", round, err) + } + if !handedOutNothing(got) { + t.Errorf("round %d: a wrong proof was handed %+v", round, got) + } + } + cancel := func() { m.Cancel(first.ID) } + start := func() { + _, ch, err := m.Start(state.RoleFull, "") + if err != nil { + t.Errorf("round %d: the second Start: %v", round, err) + secondDelivered <- nil + return + } + go collect(ch, stop, secondDelivered) + } + redeem := func() { + // Right for the first pairing, and wrong for the second if that + // one is pending by now. + got, err := m.Redeem(agentFP, nonce, right, "Pixel 8", c.create) + switch { + case err == nil: + accepted.Add(1) + if got.Token == "" { + t.Errorf("round %d: the right proof was accepted without a token: %+v", round, got) + } + case errors.Is(err, ErrNone), errors.Is(err, ErrWrongProof): + if !handedOutNothing(got) { + t.Errorf("round %d: a refused redeem handed out %+v", round, got) + } + default: + t.Errorf("round %d: the right proof: err = %v", round, err) + } + } + ops := []func(){cancel, start, redeem} + for i := 0; i < wrongTries; i++ { + ops = append(ops, wrong) + } + // Every round launches the calls in another order, so that it is not + // always the same one that reaches the manager first. + for i := range ops { + run(ops[(i+round*3)%len(ops)]) + } + close(release) + wg.Wait() + close(stop) + firstResults, secondResults := <-firstDelivered, <-secondDelivered + + // The first pairing has ended for sure, the second Start saw to that. + if len(firstResults) != 1 { + t.Fatalf("round %d: the first pairing delivered %d results: %+v", round, len(firstResults), firstResults) + } + if len(secondResults) > 1 { + t.Fatalf("round %d: the second pairing delivered %d results: %+v", round, len(secondResults), secondResults) + } + calls := int(c.calls.Load()) + if calls > 1 { + t.Fatalf("round %d: create ran %d times", round, calls) + } + // Only the first code was ever proved, so only the first pairing can + // end as paired, and it does exactly when a device was created. + paired := 0 + if firstResults[0].Outcome == Paired { + paired = 1 + } + if paired != calls || int(accepted.Load()) != calls { + t.Fatalf("round %d: create ran %d times, the right proof was accepted %d times, the first pairing ended as %s", + round, calls, accepted.Load(), firstResults[0].Outcome) + } + for _, r := range secondResults { + if r.Outcome == Paired { + t.Fatalf("round %d: the second pairing ended as paired: %+v", round, r) + } + } + } +} From 5a04cf0733117fae7fb248d51d2647e975697ca8 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 04:57:10 +0530 Subject: [PATCH 10/32] fix(agent): salt the pairing key with the phone nonce --- agent/internal/pairing/code.go | 41 +++++++++---- agent/internal/pairing/code_test.go | 32 ++++++++++- agent/internal/pairing/testdata/vectors.json | 60 ++++++++++++++++---- 3 files changed, 110 insertions(+), 23 deletions(-) diff --git a/agent/internal/pairing/code.go b/agent/internal/pairing/code.go index 93ad307..ba521e9 100644 --- a/agent/internal/pairing/code.go +++ b/agent/internal/pairing/code.go @@ -76,14 +76,15 @@ func Format(code string) string { return code[0:4] + "-" + code[4:8] + "-" + code[8:12] } -// proofContext names the exchange and its version. It is the salt of the -// key and the first part of what both proofs authenticate. +// proofContext names the exchange and its version. It is the first part of +// the salt of the key and the first part of what both proofs authenticate. const proofContext = "docker-mobile pair v1" // stretchRounds is how many rounds of PBKDF2 turn a code into the key of the // proofs. A code holds only 60 bits, so whoever has seen one proof can try // every code against it; the rounds make each of those tries cost this many -// times more. +// times more, and the salt (see proofKey) keeps them from being prepared +// before the proof is seen. const stretchRounds = 100000 // NonceLen is the length of the random value each side contributes. @@ -91,6 +92,9 @@ const NonceLen = 32 // PhoneProof is what the phone sends: an HMAC keyed with the stretched code // over the fingerprint the phone sees on its connection and its own nonce. +// The nonce also salts the stretch (see proofKey), so the key is good for +// this one attempt and no other. That is why the phone must draw a fresh, +// random nonce for every attempt. // // code is a canonical code of CodeLen characters. fingerprint is 32 bytes, // or empty when the agent has no certificate of its own (it runs behind a @@ -102,9 +106,10 @@ func PhoneProof(code string, fingerprint, phoneNonce []byte) []byte { return proof(code, "phone", fingerprint, phoneNonce) } -// AgentProof is the answer: the same construction, keyed with the stretched -// code as well, with the other label and both nonces, so the phone knows the -// agent holds the code too. +// AgentProof is the answer: the same construction with the other label and +// both nonces, so the phone knows the agent holds the code too. Its key is +// the key of the phone's proof: the stretch is salted with the phone's +// nonce, and both proofs of one attempt carry that nonce. // // It expects what PhoneProof expects, and agentNonce is NonceLen bytes too. // The two nonces are written one after the other with nothing between them, @@ -114,19 +119,31 @@ func AgentProof(code string, fingerprint, phoneNonce, agentNonce []byte) []byte return proof(code, "agent", fingerprint, phoneNonce, agentNonce) } -// proofKey stretches a code into the 32-byte key of both proofs. -func proofKey(code string) []byte { - key, err := pbkdf2.Key(sha256.New, code, []byte(proofContext), stretchRounds, sha256.Size) +// proofKey stretches a code into the 32-byte key of both proofs of one +// attempt. The salt is proofContext, a zero byte and the phone's nonce. +// +// The nonce is in the salt so that a key computed for one attempt is useless +// for any other: nothing can be stretched ahead of time and kept for a +// pairing that is still to come. This holds only while the phone's nonce is +// fresh and random for every attempt, so that nobody knows it beforehand. +func proofKey(code string, phoneNonce []byte) []byte { + salt := make([]byte, 0, len(proofContext)+1+len(phoneNonce)) + salt = append(salt, proofContext...) + salt = append(salt, 0) + salt = append(salt, phoneNonce...) + key, err := pbkdf2.Key(sha256.New, code, salt, stretchRounds, sha256.Size) if err != nil { - // Only parameters the library refuses lead here, and every one of - // them is a constant. + // Only parameters the library refuses lead here, and nothing a + // caller passes is one of them: the hash, the rounds and the length + // are constants, and the salt is never shorter than proofContext. panic("pairing: stretching the code: " + err.Error()) } return key } func proof(code, who string, fingerprint []byte, nonces ...[]byte) []byte { - mac := hmac.New(sha256.New, proofKey(code)) + // The first nonce is the phone's; both callers pass it. + mac := hmac.New(sha256.New, proofKey(code, nonces[0])) mac.Write([]byte(proofContext)) mac.Write([]byte{0}) mac.Write([]byte(who)) diff --git a/agent/internal/pairing/code_test.go b/agent/internal/pairing/code_test.go index faf2643..ef646a9 100644 --- a/agent/internal/pairing/code_test.go +++ b/agent/internal/pairing/code_test.go @@ -15,6 +15,7 @@ type vectors struct { Proofs []struct { Name string `json:"name"` Code string `json:"code"` + Typed string `json:"typed"` FingerprintHex string `json:"fingerprintHex"` PhoneNonceHex string `json:"phoneNonceHex"` AgentNonceHex string `json:"agentNonceHex"` @@ -65,7 +66,10 @@ func unhex(t *testing.T, s string) []byte { func TestProofsMatchTheSharedVectors(t *testing.T) { for _, p := range loadVectors(t).Proofs { fp, np, na := unhex(t, p.FingerprintHex), unhex(t, p.PhoneNonceHex), unhex(t, p.AgentNonceHex) - if got := hex.EncodeToString(proofKey(p.Code)); got != p.KeyHex { + if got, ok := Normalize(p.Typed); !ok || got != p.Code { + t.Errorf("%s: Normalize(%q) = %q, %v, want %q", p.Name, p.Typed, got, ok, p.Code) + } + if got := hex.EncodeToString(proofKey(p.Code, np)); got != p.KeyHex { t.Errorf("%s: key = %s, want %s", p.Name, got, p.KeyHex) } if got := hex.EncodeToString(PhoneProof(p.Code, fp, np)); got != p.PhoneProofHex { @@ -111,6 +115,32 @@ func TestAProofDependsOnEveryInput(t *testing.T) { } } +func TestTheKeyDependsOnThePhoneNonceAndTheCode(t *testing.T) { + one := bytes.Repeat([]byte{2}, NonceLen) + other := bytes.Repeat([]byte{9}, NonceLen) + if bytes.Equal(proofKey("K7QM2XPA9TRC", one), proofKey("K7QM2XPA9TRC", other)) { + t.Error("one code gives the same key for two phone nonces") + } + // Among the vectors, two entries share a phone nonce and differ in code. + proofs := loadVectors(t).Proofs + pairs := 0 + for i, a := range proofs { + for _, b := range proofs[i+1:] { + if a.PhoneNonceHex != b.PhoneNonceHex || a.Code == b.Code { + continue + } + pairs++ + np := unhex(t, a.PhoneNonceHex) + if bytes.Equal(proofKey(a.Code, np), proofKey(b.Code, np)) { + t.Errorf("%s and %s: two codes give the same key for one phone nonce", a.Name, b.Name) + } + } + } + if pairs == 0 { + t.Fatal("no two vectors share a phone nonce and differ in code") + } +} + func TestNewCodeIsCanonicalAndVaries(t *testing.T) { seen := map[string]bool{} for i := 0; i < 200; i++ { diff --git a/agent/internal/pairing/testdata/vectors.json b/agent/internal/pairing/testdata/vectors.json index 6f934dc..e3ec02d 100644 --- a/agent/internal/pairing/testdata/vectors.json +++ b/agent/internal/pairing/testdata/vectors.json @@ -1,35 +1,38 @@ { - "note": "Shared with the app. key: PBKDF2-HMAC-SHA256(password = the 12 ASCII bytes of the code, salt = 'docker-mobile pair v1', rounds = 100000, length = 32 bytes). proofs: HMAC-SHA256 keyed with that key over 'docker-mobile pair v1' 00 'phone'|'agent' 00 len(fingerprint) fingerprint phoneNonce [agentNonce]. normalization: what a typed code becomes (null = rejected). links: the link the agent shows for the six fields; an empty host, port, fingerprint, scheme or name is left out, and values are form-encoded (a space is '+', a reserved or non-ASCII character is %XX for each UTF-8 byte).", + "note": "Shared with the app. key: PBKDF2-HMAC-SHA256(password = the 12 ASCII bytes of the code, salt = 'docker-mobile pair v1' 00 phoneNonce, rounds = 100000, length = 32 bytes); the salt is the context string, one zero byte, then the phone nonce, 54 bytes in all, so both proofs of one attempt have the same key and no other attempt has it. proofs: HMAC-SHA256 keyed with that key over 'docker-mobile pair v1' 00 'phone'|'agent' 00 len(fingerprint) as one byte, fingerprint, phoneNonce, [agentNonce]. typed (in proofs): one way a person might enter that code; it is normalized first, and what is stretched is the result, code. normalization: what a typed code becomes (null = rejected). links: the link the agent shows for the six fields; an empty host, port, fingerprint, scheme or name is left out, and values are form-encoded (a space is '+', a reserved or non-ASCII character is %XX for each UTF-8 byte).", "proofs": [ { "name": "pinned certificate", "code": "K7QM2XPA9TRC", + "typed": "k7qm-2xpa-9trc", "fingerprintHex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "phoneNonceHex": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", "agentNonceHex": "5f5e5d5c5b5a595857565554535251505f5e5d5c5b5a59585756555453525150", - "keyHex": "39231b583a4813def69a652cdfb5cd8c093b7292dcb8d841ceea386eb1c64b04", - "phoneProofHex": "d15073614bee6324b21b429397810e3c305a7c46e8f6f68f6657491e92600a73", - "agentProofHex": "0548c503207f4e5a5262822802b5a740d9b631dc202b6682af065a96dbf9d27d" + "keyHex": "ab82b066aadbd2d286357033e67c6a5a40d0bbdb72e3bc71f28186715f5863c9", + "phoneProofHex": "8513841281ab543d50acbc51d19905198ebfcfc8e32bd9b4171d0dad69168417", + "agentProofHex": "b11a58f3ed9c02c8d6a74324517b68a461f34096a538d752c99ad10bb1697b4f" }, { "name": "second pinned certificate", "code": "0123456789AB", + "typed": "o123 4567 89ab", "fingerprintHex": "03a231792349424dc65f1b5f9ca83beff282966a02fb57741bb89c83c2651119", "phoneNonceHex": "4bb55ab4d5a8a2bb16af8bd6e966b60ac68dd4e482b8d9085d4dc83f3a237027", "agentNonceHex": "d3a5a4f9f1621065d377bfc50571af708b54b666e77a923242485bb476b8b91d", - "keyHex": "9ebc85c88d54ff2801735859161806506e7508c8552c396ebc7734027dc9ba9f", - "phoneProofHex": "b038faae3791acfc7111b033e344b9d9929024f133fab243851d890baf61fae0", - "agentProofHex": "9425a561e3c0521b6ed240e9931f6813b706111d53d5bc1c9694a3dc5b28f048" + "keyHex": "3883572731ef45d28535c4753c295fe18186f546158ae58e03372c5d9be333f8", + "phoneProofHex": "fce292dac41f1d195692f7476ba54fadc2e195078307f149cc09de5730cce2bf", + "agentProofHex": "58e520f14a9ee46198c9dda4354e611124b35e35f4973699fadf8e8cddf0f46d" }, { "name": "no pinned certificate (behind a proxy)", "code": "ZZZZZZZZZZZZ", + "typed": "zzzz-zzzz-zzzz", "fingerprintHex": "", "phoneNonceHex": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", "agentNonceHex": "5f5e5d5c5b5a595857565554535251505f5e5d5c5b5a59585756555453525150", - "keyHex": "409df586139082b24a6af3cc821d61da0da42e95b43857929ab219a0a88434ab", - "phoneProofHex": "c29667751132714735af6bb0b326c274b6e921bbbbf5577102ae9615ec92507f", - "agentProofHex": "5ab0852dabcc6eb722142682c594bff5f6f9f12d4a1149a65a4d1c9d587d632f" + "keyHex": "9a4abb7e2aa7f841a59634e84b3478468623f9ebd776b103bae3f3b27ab9d860", + "phoneProofHex": "124d82bf616bef9819262c33dc825d438adbcb455bd8589ed393faa9c5c9ef62", + "agentProofHex": "0ca8fbccc07625fdb29b39ac4237f384c727e5a6c19b9ac8d31440b821b1df8b" } ], "normalization": [ @@ -104,6 +107,34 @@ { "input": "k7qm-2xpa-9tru", "code": null + }, + { + "input": "\u212a7QM-2XPA-9TRC", + "code": null + }, + { + "input": "K7QM-2XPA-9TR\u0130", + "code": null + }, + { + "input": "0123456789ab", + "code": "0123456789AB" + }, + { + "input": "cdefghjkmnpq", + "code": "CDEFGHJKMNPQ" + }, + { + "input": "rstvwxyz0000", + "code": "RSTVWXYZ0000" + }, + { + "input": "K7-QM2XPA9TRC", + "code": "K7QM2XPA9TRC" + }, + { + "input": "K7QM--2XPA--9TRC", + "code": "K7QM2XPA9TRC" } ], "links": [ @@ -133,6 +164,15 @@ "code": "K7QM2XPA9TRC", "name": "R&D = lab #1 + 50% caf\u00e9", "link": "dockermobile://pair?c=K7QM2XPA9TRC&f=OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI&h=my-server.lan&n=R%26D+%3D+lab+%231+%2B+50%25+caf%C3%A9&p=8443&v=1" + }, + { + "host": "10.0.0.7", + "port": "8443", + "fingerprint": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8", + "scheme": "", + "code": "K7QM2XPA9TRC", + "name": "", + "link": "dockermobile://pair?c=K7QM2XPA9TRC&f=AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8&h=10.0.0.7&p=8443&v=1" } ] } From fe9f987a79b99886b0fc00c8178d5514b214d7d1 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 05:05:18 +0530 Subject: [PATCH 11/32] test(agent): pin every rule of the read-only allow list --- agent/internal/policy/policy_test.go | 109 +++++++++++++++++++++------ 1 file changed, 84 insertions(+), 25 deletions(-) diff --git a/agent/internal/policy/policy_test.go b/agent/internal/policy/policy_test.go index 50855a4..8f0772a 100644 --- a/agent/internal/policy/policy_test.go +++ b/agent/internal/policy/policy_test.go @@ -4,32 +4,35 @@ import "testing" const id = "3f2a9c1b7d4e5f60718293a4b5c6d7e8f9a0b1c2d3e4f5061728394a5b6c7d8e" +// reads holds at least one path for every rule of the allow list, without an +// API version in front. +var reads = []string{ + "/_ping", + "/version", + "/info", + "/system/df", + "/events", + "/containers/json", + "/containers/" + id + "/json", + "/containers/" + id + "/logs", + "/containers/" + id + "/stats", + "/containers/my_web-1.2/json", + "/images/json", + "/images/sha256:" + id + "/json", + "/images/sha256:" + id + "/history", + "/images/nginx:1.27/json", + "/images/ghcr.io/owner/app:latest/json", + "/images/registry.example.com:5000/team/app@sha256:" + id + "/history", + "/networks", + "/networks/" + id, + "/networks/bridge", + "/volumes", + "/volumes/pg_data", + "/agent/v1/whoami", +} + func TestEveryReadTheAppMakesIsAllowed(t *testing.T) { - paths := []string{ - "/_ping", - "/version", - "/info", - "/system/df", - "/events", - "/containers/json", - "/containers/" + id + "/json", - "/containers/" + id + "/logs", - "/containers/" + id + "/stats", - "/containers/my_web-1.2/json", - "/images/json", - "/images/sha256:" + id + "/json", - "/images/sha256:" + id + "/history", - "/images/nginx:1.27/json", - "/images/ghcr.io/owner/app:latest/json", - "/images/registry.example.com:5000/team/app@sha256:" + id + "/history", - "/networks", - "/networks/" + id, - "/networks/bridge", - "/volumes", - "/volumes/pg_data", - "/agent/v1/whoami", - } - for _, p := range paths { + for _, p := range reads { for _, prefix := range []string{"", "/v1.45", "/v1.41"} { for _, method := range []string{"GET", "HEAD"} { if !AllowedReadOnly(method, prefix+p) { @@ -180,3 +183,59 @@ func TestImageNamesMayContainSlashesButNotReachOtherRoutes(t *testing.T) { } } } + +func TestNothingMayBeAddedToEitherEndOfARead(t *testing.T) { + // Adding "/x" to these two gives a read of its own, because the rule + // named beside each takes "x" as the name to inspect. + inspectsX := map[string]bool{ + "/networks": true, // `^/networks/` + idSeg + `$` + "/volumes": true, // `^/volumes/` + idSeg + `$` + } + for _, p := range reads { + for _, q := range []string{"/x" + p, p + "/"} { + if AllowedReadOnly("GET", q) { + t.Errorf("GET %s was allowed", q) + } + } + if got, want := AllowedReadOnly("GET", p+"/x"), inspectsX[p]; got != want { + t.Errorf("GET %s/x: allowed is %v, want %v", p, got, want) + } + } +} + +func TestNearMissesOfARuleAreRefused(t *testing.T) { + paths := []string{ + // An empty or "." segment inside an image name. + "/images/a//json", + "/images/a/./json", + // Only an image name may hold "/". + "/containers/a/b/json", + "/volumes/a/b", + // An image name starts with a letter or digit. + "/images/-x/json", + // The image list is the whole path, not the start of a longer one. + "/images/json/get", + "/images/json-server/get", + // The network and volume rules start at the root. + "/containers/networks/archive", + "/containers/volumes/export", + // An API version is "/v", digits, a dot, digits, at the very start. + "/v1x45/info", + "/x/v1.45/info", + } + for _, p := range paths { + if AllowedReadOnly("GET", p) { + t.Errorf("GET %s was allowed", p) + } + } +} + +func TestTheMethodIsMatchedExactly(t *testing.T) { + for _, method := range []string{"get", "Get", "head", ""} { + for _, p := range reads { + if AllowedReadOnly(method, p) { + t.Errorf("%q %s was allowed", method, p) + } + } + } +} From f6027b4aae08f7ad50735aa01916720dce7a6a1c Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 05:12:43 +0530 Subject: [PATCH 12/32] feat(agent): throttle for failed attempts per address --- agent/internal/throttle/throttle.go | 125 ++++++++++++++++++++ agent/internal/throttle/throttle_test.go | 138 +++++++++++++++++++++++ 2 files changed, 263 insertions(+) create mode 100644 agent/internal/throttle/throttle.go create mode 100644 agent/internal/throttle/throttle_test.go diff --git a/agent/internal/throttle/throttle.go b/agent/internal/throttle/throttle.go new file mode 100644 index 0000000..0be7e10 --- /dev/null +++ b/agent/internal/throttle/throttle.go @@ -0,0 +1,125 @@ +// Package throttle slows down guessing: it counts failed attempts per source +// address and blocks an address for a growing time once it fails too often. +package throttle + +import ( + "net" + "sync" + "time" +) + +const ( + // Window is how far back failures count. + Window = 10 * time.Minute + // Threshold is the number of failures in the window at which an address + // is first blocked. + Threshold = 10 + // BasePenalty is the first block; it doubles with every further failure. + BasePenalty = time.Minute + // MaxPenalty caps the block. + MaxPenalty = 15 * time.Minute + // maxAddresses bounds memory: beyond it, addresses with nothing left to + // remember are dropped, and failing that the oldest ones. + maxAddresses = 10000 +) + +type entry struct { + failures []time.Time + blockedUntil time.Time +} + +// Limiter is safe for concurrent use. +type Limiter struct { + now func() time.Time + + mu sync.Mutex + addrs map[string]*entry +} + +// New returns a limiter that reads time from now. +func New(now func() time.Time) *Limiter { + return &Limiter{now: now, addrs: map[string]*entry{}} +} + +// Key turns a remote address ("host:port") into the key failures are counted +// under: the host alone. +func Key(remoteAddr string) string { + host, _, err := net.SplitHostPort(remoteAddr) + if err != nil { + return remoteAddr + } + return host +} + +// Blocked reports whether key is blocked right now, and for how much longer. +func (l *Limiter) Blocked(key string) (time.Duration, bool) { + l.mu.Lock() + defer l.mu.Unlock() + e := l.addrs[key] + if e == nil { + return 0, false + } + if left := e.blockedUntil.Sub(l.now()); left > 0 { + return left, true + } + return 0, false +} + +// Fail records one failed attempt from key. +func (l *Limiter) Fail(key string) { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + e := l.addrs[key] + if e == nil { + if len(l.addrs) >= maxAddresses { + l.evictLocked(now) + } + e = &entry{} + l.addrs[key] = e + } + e.failures = append(recent(e.failures, now), now) + if n := len(e.failures); n >= Threshold { + penalty := BasePenalty + for i := Threshold; i < n && penalty < MaxPenalty; i++ { + penalty *= 2 + } + if penalty > MaxPenalty { + penalty = MaxPenalty + } + e.blockedUntil = now.Add(penalty) + } +} + +// recent drops failures that have left the window. +func recent(failures []time.Time, now time.Time) []time.Time { + cut := 0 + for cut < len(failures) && now.Sub(failures[cut]) >= Window { + cut++ + } + return failures[cut:] +} + +// evictLocked makes room: first every address with nothing left to remember, +// then, if none could go, the address whose last failure is oldest. +func (l *Limiter) evictLocked(now time.Time) { + var oldestKey string + var oldest time.Time + for key, e := range l.addrs { + e.failures = recent(e.failures, now) + if len(e.failures) == 0 && !e.blockedUntil.After(now) { + delete(l.addrs, key) + continue + } + last := e.blockedUntil + if n := len(e.failures); n > 0 && e.failures[n-1].After(last) { + last = e.failures[n-1] + } + if oldestKey == "" || last.Before(oldest) { + oldestKey, oldest = key, last + } + } + if len(l.addrs) >= maxAddresses && oldestKey != "" { + delete(l.addrs, oldestKey) + } +} diff --git a/agent/internal/throttle/throttle_test.go b/agent/internal/throttle/throttle_test.go new file mode 100644 index 0000000..f790d0e --- /dev/null +++ b/agent/internal/throttle/throttle_test.go @@ -0,0 +1,138 @@ +package throttle + +import ( + "fmt" + "testing" + "time" +) + +type clock struct{ t time.Time } + +func (c *clock) now() time.Time { return c.t } +func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) } + +func newClock() *clock { return &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} } + +func fail(l *Limiter, key string, n int) { + for i := 0; i < n; i++ { + l.Fail(key) + } +} + +func TestNineFailuresDoNotBlock(t *testing.T) { + l := New(newClock().now) + fail(l, "10.0.0.1", Threshold-1) + if _, blocked := l.Blocked("10.0.0.1"); blocked { + t.Fatal("blocked below the threshold") + } +} + +func TestTheTenthFailureBlocksForAMinute(t *testing.T) { + c := newClock() + l := New(c.now) + fail(l, "10.0.0.1", Threshold) + left, blocked := l.Blocked("10.0.0.1") + if !blocked || left != time.Minute { + t.Fatalf("blocked = %v for %v, want a minute", blocked, left) + } + c.advance(59 * time.Second) + if left, blocked := l.Blocked("10.0.0.1"); !blocked || left != time.Second { + t.Fatalf("after 59 s: blocked = %v for %v", blocked, left) + } + c.advance(time.Second) + if _, blocked := l.Blocked("10.0.0.1"); blocked { + t.Fatal("still blocked after the minute") + } +} + +func TestThePenaltyDoublesAndIsCapped(t *testing.T) { + c := newClock() + l := New(c.now) + fail(l, "a", Threshold) + want := []time.Duration{2 * time.Minute, 4 * time.Minute, 8 * time.Minute, 15 * time.Minute, 15 * time.Minute} + for i, w := range want { + l.Fail("a") + if left, _ := l.Blocked("a"); left != w { + t.Fatalf("failure %d: penalty = %v, want %v", Threshold+1+i, left, w) + } + } +} + +func TestAddressesAreCountedSeparately(t *testing.T) { + l := New(newClock().now) + fail(l, "a", Threshold) + if _, blocked := l.Blocked("b"); blocked { + t.Fatal("another address is blocked") + } + if _, blocked := l.Blocked("never-seen"); blocked { + t.Fatal("an unknown address is blocked") + } +} + +func TestFailuresLeaveTheWindow(t *testing.T) { + c := newClock() + l := New(c.now) + fail(l, "a", Threshold-1) + c.advance(Window) + l.Fail("a") + if _, blocked := l.Blocked("a"); blocked { + t.Fatal("failures older than the window still count") + } + fail(l, "a", Threshold-1) + if _, blocked := l.Blocked("a"); !blocked { + t.Fatal("ten failures inside the window did not block") + } +} + +func TestKeyDropsThePort(t *testing.T) { + cases := map[string]string{ + "192.168.1.5:51234": "192.168.1.5", + "[::1]:8443": "::1", + "[fe80::1%eth0]:1": "fe80::1%eth0", + "no-port": "no-port", + "": "", + } + for in, want := range cases { + if got := Key(in); got != want { + t.Errorf("Key(%q) = %q, want %q", in, got, want) + } + } +} + +func TestMemoryIsBounded(t *testing.T) { + c := newClock() + l := New(c.now) + for i := 0; i < maxAddresses; i++ { + l.Fail(fmt.Sprintf("addr-%d", i)) + if i%1000 == 0 { + c.advance(time.Second) + } + } + // Everything so far is still inside the window: the oldest one goes. + l.Fail("one-more") + if n := len(l.addrs); n > maxAddresses { + t.Fatalf("%d addresses remembered, cap is %d", n, maxAddresses) + } + if _, ok := l.addrs["addr-0"]; ok { + t.Fatal("the oldest address was not dropped") + } + // Once the window has passed, everything forgettable goes at once. + c.advance(Window) + l.Fail("after-the-window") + if n := len(l.addrs); n != 1 { + t.Fatalf("%d addresses remembered after the window, want 1", n) + } +} + +func TestABlockedAddressIsNotForgottenWhileBlocked(t *testing.T) { + c := newClock() + l := New(c.now) + fail(l, "attacker", Threshold+4) // 15 minutes + c.advance(Window) // failures left the window, the block has not ended + for i := 0; i < maxAddresses; i++ { + l.Fail(fmt.Sprintf("addr-%d", i)) + } + if _, blocked := l.Blocked("attacker"); !blocked { + t.Fatal("a blocked address was forgotten") + } +} From 4e742c243b4e318389311d2a03c231d24a2d4cbb Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 05:18:07 +0530 Subject: [PATCH 13/32] feat(agent): per-device authentication and connection tracking --- agent/internal/auth/authenticator.go | 112 ++++++++++++ agent/internal/auth/authenticator_test.go | 202 ++++++++++++++++++++++ agent/internal/conns/conns.go | 85 +++++++++ agent/internal/conns/conns_test.go | 105 +++++++++++ 4 files changed, 504 insertions(+) create mode 100644 agent/internal/auth/authenticator.go create mode 100644 agent/internal/auth/authenticator_test.go create mode 100644 agent/internal/conns/conns.go create mode 100644 agent/internal/conns/conns_test.go diff --git a/agent/internal/auth/authenticator.go b/agent/internal/auth/authenticator.go new file mode 100644 index 0000000..e555b77 --- /dev/null +++ b/agent/internal/auth/authenticator.go @@ -0,0 +1,112 @@ +// Package auth decides who sent a request: a paired device, the shared +// token from the environment, or nobody. +package auth + +import ( + "context" + "crypto/subtle" + "encoding/json" + "math" + "net/http" + "strconv" + "strings" + + "github.com/retransmit/docker-mobile/agent/internal/conns" + "github.com/retransmit/docker-mobile/agent/internal/state" + "github.com/retransmit/docker-mobile/agent/internal/throttle" +) + +// LegacyDeviceID is the id requests carry when they authenticate with the +// shared token from the environment. +const LegacyDeviceID = "env" + +type callerKey struct{} + +// WithCaller returns a context that knows which device sent the request. +func WithCaller(ctx context.Context, dev state.Device) context.Context { + return context.WithValue(ctx, callerKey{}, dev) +} + +// Caller returns the device that sent the request, if it was authenticated. +func Caller(ctx context.Context) (state.Device, bool) { + dev, ok := ctx.Value(callerKey{}).(state.Device) + return dev, ok +} + +// Authenticator guards handlers. Devices is required; the rest is optional. +type Authenticator struct { + Devices *state.Devices + // Legacy is the shared token from the environment; empty disables it. + Legacy string + Limiter *throttle.Limiter + Conns *conns.Registry + // OnFailure is told the source address of every failed attempt. + OnFailure func(remoteAddr string) + // OnCaller is told who a request belongs to, once that is known. + OnCaller func(r *http.Request, dev state.Device) +} + +// Require lets a request through only with valid credentials. A paired +// device always passes. Anything else from an address that has failed too +// often is refused without a look at its token, so the shared token cannot +// be guessed at speed. +func (a *Authenticator) Require(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + bearer, hasBearer := bearerToken(r) + if hasBearer && state.IsDeviceToken(bearer) { + if dev, ok := a.Devices.Authenticate(bearer); ok { + a.serve(w, r, dev, next) + return + } + } + key := throttle.Key(r.RemoteAddr) + if a.Limiter != nil { + if left, blocked := a.Limiter.Blocked(key); blocked { + w.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(left.Seconds())))) + WriteError(w, http.StatusTooManyRequests, "Too many failed attempts from this address") + return + } + } + if hasBearer && a.Legacy != "" && !state.IsDeviceToken(bearer) && + subtle.ConstantTimeCompare([]byte(bearer), []byte(a.Legacy)) == 1 { + a.serve(w, r, state.Device{ID: LegacyDeviceID, Name: "env-token", Role: state.RoleFull}, next) + return + } + if a.Limiter != nil { + a.Limiter.Fail(key) + } + if a.OnFailure != nil { + a.OnFailure(r.RemoteAddr) + } + WriteError(w, http.StatusUnauthorized, "unauthorized") + }) +} + +func (a *Authenticator) serve(w http.ResponseWriter, r *http.Request, dev state.Device, next http.Handler) { + if a.OnCaller != nil { + a.OnCaller(r, dev) + } + ctx := r.Context() + if a.Conns != nil { + tracked, release := a.Conns.Track(ctx, dev.ID) + defer release() + ctx = tracked + } + next.ServeHTTP(w, r.WithContext(WithCaller(ctx, dev))) +} + +func bearerToken(r *http.Request) (string, bool) { + token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if !ok || token == "" { + return "", false + } + return token, true +} + +// WriteError answers with a JSON body shaped like the Docker API's errors, so +// clients read agent errors and daemon errors the same way. +func WriteError(w http.ResponseWriter, status int, message string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + json.NewEncoder(w).Encode(map[string]string{"message": message}) +} diff --git a/agent/internal/auth/authenticator_test.go b/agent/internal/auth/authenticator_test.go new file mode 100644 index 0000000..628a50a --- /dev/null +++ b/agent/internal/auth/authenticator_test.go @@ -0,0 +1,202 @@ +package auth + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/conns" + "github.com/retransmit/docker-mobile/agent/internal/state" + "github.com/retransmit/docker-mobile/agent/internal/throttle" +) + +type clock struct{ t time.Time } + +func (c *clock) now() time.Time { return c.t } + +type fixture struct { + auth *Authenticator + devices *state.Devices + clock *clock + seen []state.Device // callers the inner handler saw + failed []string +} + +func newFixture(t *testing.T, legacy string) *fixture { + t.Helper() + dir, err := state.Open(filepath.Join(t.TempDir(), "data")) + if err != nil { + t.Fatal(err) + } + c := &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} + devices, err := state.LoadDevices(dir, c.now) + if err != nil { + t.Fatal(err) + } + f := &fixture{devices: devices, clock: c} + f.auth = &Authenticator{ + Devices: devices, + Legacy: legacy, + Limiter: throttle.New(c.now), + Conns: conns.New(), + OnFailure: func(remote string) { f.failed = append(f.failed, remote) }, + } + return f +} + +func (f *fixture) do(bearer, remote string) *httptest.ResponseRecorder { + h := f.auth.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + dev, _ := Caller(r.Context()) + f.seen = append(f.seen, dev) + w.WriteHeader(http.StatusOK) + })) + req := httptest.NewRequest(http.MethodGet, "/containers/json", nil) + if bearer != "" { + req.Header.Set("Authorization", bearer) + } + if remote != "" { + req.RemoteAddr = remote + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +const legacy = "a-shared-token-of-enough-length" + +func TestADeviceTokenIdentifiesItsDevice(t *testing.T) { + f := newFixture(t, "") + dev, token, _ := f.devices.Add("Pixel 8", state.RoleReadOnly) + if rec := f.do("Bearer "+token, ""); rec.Code != http.StatusOK { + t.Fatalf("code = %d, want 200", rec.Code) + } + if len(f.seen) != 1 || f.seen[0].ID != dev.ID || f.seen[0].Role != state.RoleReadOnly { + t.Fatalf("caller = %+v", f.seen) + } +} + +func TestTheSharedTokenIsAFullDeviceCalledEnvToken(t *testing.T) { + f := newFixture(t, legacy) + if rec := f.do("Bearer "+legacy, ""); rec.Code != http.StatusOK { + t.Fatalf("code = %d, want 200", rec.Code) + } + got := f.seen[0] + if got.ID != LegacyDeviceID || got.Name != "env-token" || got.Role != state.RoleFull { + t.Fatalf("caller = %+v", got) + } +} + +func TestBadCredentialsAreRefusedWithAJSONMessage(t *testing.T) { + f := newFixture(t, legacy) + _, token, _ := f.devices.Add("phone", state.RoleFull) + for name, bearer := range map[string]string{ + "nothing": "", + "empty bearer": "Bearer ", + "wrong shared token": "Bearer nope", + "wrong scheme": "Basic " + legacy, + "no scheme": legacy, + "damaged device": "Bearer " + token + "x", + "unknown device": "Bearer dm1.ffffffff.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "lower case scheme": "bearer " + legacy, + } { + rec := f.do(bearer, "") + if rec.Code != http.StatusUnauthorized { + t.Errorf("%s: code = %d, want 401", name, rec.Code) + } + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body["message"] != "unauthorized" { + t.Errorf("%s: body = %q", name, rec.Body.String()) + } + } + if len(f.seen) != 0 { + t.Fatalf("the handler ran for %d refused requests", len(f.seen)) + } +} + +func TestWithoutASharedTokenNothingButDevicesGetsIn(t *testing.T) { + f := newFixture(t, "") + for _, bearer := range []string{"Bearer ", "Bearer anything", ""} { + if rec := f.do(bearer, ""); rec.Code != http.StatusUnauthorized { + t.Fatalf("%q: code = %d, want 401", bearer, rec.Code) + } + } +} + +func TestTenFailuresBlockTheAddressButNotItsPairedDevices(t *testing.T) { + f := newFixture(t, legacy) + _, token, _ := f.devices.Add("phone", state.RoleFull) + const nat = "203.0.113.7:40000" + for i := 0; i < throttle.Threshold; i++ { + if rec := f.do("Bearer wrong", nat); rec.Code != http.StatusUnauthorized { + t.Fatalf("failure %d: code = %d", i+1, rec.Code) + } + } + // The right shared token is now refused unseen. + rec := f.do("Bearer "+legacy, "203.0.113.7:40001") + if rec.Code != http.StatusTooManyRequests { + t.Fatalf("code = %d, want 429", rec.Code) + } + if got := rec.Header().Get("Retry-After"); got != "60" { + t.Fatalf("Retry-After = %q, want 60", got) + } + // A paired device behind the same address still gets in. + if rec := f.do("Bearer "+token, nat); rec.Code != http.StatusOK { + t.Fatalf("paired device: code = %d, want 200", rec.Code) + } + // Another address is not affected. + if rec := f.do("Bearer "+legacy, "198.51.100.9:1"); rec.Code != http.StatusOK { + t.Fatalf("other address: code = %d, want 200", rec.Code) + } + // Blocked requests are not counted as further failures. + if len(f.failed) != throttle.Threshold { + t.Fatalf("%d failures reported, want %d", len(f.failed), throttle.Threshold) + } + // When the block ends the shared token works again. + f.clock.t = f.clock.t.Add(time.Minute) + if rec := f.do("Bearer "+legacy, nat); rec.Code != http.StatusOK { + t.Fatalf("after the block: code = %d, want 200", rec.Code) + } +} + +func TestClosingADeviceEndsItsOpenRequest(t *testing.T) { + f := newFixture(t, "") + dev, token, _ := f.devices.Add("phone", state.RoleFull) + started := make(chan struct{}) + ended := make(chan error, 1) + h := f.auth.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + ended <- r.Context().Err() + })) + req := httptest.NewRequest(http.MethodGet, "/events", nil) + req.Header.Set("Authorization", "Bearer "+token) + go h.ServeHTTP(httptest.NewRecorder(), req) + <-started + if f.auth.Conns.Open(dev.ID) != 1 { + t.Fatalf("open = %d, want 1", f.auth.Conns.Open(dev.ID)) + } + f.auth.Conns.CloseDevice(dev.ID) + select { + case err := <-ended: + if err != context.Canceled { + t.Fatalf("err = %v", err) + } + case <-time.After(3 * time.Second): + t.Fatal("the request did not end") + } +} + +func TestOnCallerLearnsWhoARequestBelongsTo(t *testing.T) { + f := newFixture(t, "") + dev, token, _ := f.devices.Add("phone", state.RoleFull) + var told string + f.auth.OnCaller = func(_ *http.Request, d state.Device) { told = d.ID } + f.do("Bearer "+token, "") + if told != dev.ID { + t.Fatalf("OnCaller got %q, want %q", told, dev.ID) + } +} diff --git a/agent/internal/conns/conns.go b/agent/internal/conns/conns.go new file mode 100644 index 0000000..3735027 --- /dev/null +++ b/agent/internal/conns/conns.go @@ -0,0 +1,85 @@ +// Package conns tracks the requests each device has open, so that removing a +// device, or stopping the agent, can end them. +package conns + +import ( + "context" + "sync" +) + +// Registry is safe for concurrent use. +type Registry struct { + mu sync.Mutex + next uint64 + open map[string]map[uint64]context.CancelFunc + closed bool +} + +// New returns an empty registry. +func New() *Registry { + return &Registry{open: map[string]map[uint64]context.CancelFunc{}} +} + +// Track returns a context for one request of deviceID. The context ends when +// parent ends, when the device is closed, or when everything is closed. The +// caller must call release when the request is over. +func (r *Registry) Track(parent context.Context, deviceID string) (ctx context.Context, release func()) { + ctx, cancel := context.WithCancel(parent) + r.mu.Lock() + if r.closed { + r.mu.Unlock() + cancel() + return ctx, func() {} + } + r.next++ + n := r.next + if r.open[deviceID] == nil { + r.open[deviceID] = map[uint64]context.CancelFunc{} + } + r.open[deviceID][n] = cancel + r.mu.Unlock() + return ctx, func() { + r.mu.Lock() + if set := r.open[deviceID]; set != nil { + delete(set, n) + if len(set) == 0 { + delete(r.open, deviceID) + } + } + r.mu.Unlock() + cancel() + } +} + +// CloseDevice ends every open request of one device and reports how many. +func (r *Registry) CloseDevice(deviceID string) int { + r.mu.Lock() + set := r.open[deviceID] + delete(r.open, deviceID) + r.mu.Unlock() + for _, cancel := range set { + cancel() + } + return len(set) +} + +// CloseAll ends every open request and refuses new ones from then on. +func (r *Registry) CloseAll() { + r.mu.Lock() + all := r.open + r.open = map[string]map[uint64]context.CancelFunc{} + r.closed = true + r.mu.Unlock() + for _, set := range all { + for _, cancel := range set { + cancel() + } + } +} + +// Open reports how many requests a device has open. +func (r *Registry) Open(deviceID string) int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.open[deviceID]) +} diff --git a/agent/internal/conns/conns_test.go b/agent/internal/conns/conns_test.go new file mode 100644 index 0000000..ed87f80 --- /dev/null +++ b/agent/internal/conns/conns_test.go @@ -0,0 +1,105 @@ +package conns + +import ( + "context" + "sync" + "testing" +) + +func ended(ctx context.Context) bool { + select { + case <-ctx.Done(): + return true + default: + return false + } +} + +func TestCloseDeviceEndsOnlyThatDevice(t *testing.T) { + r := New() + a1, relA1 := r.Track(context.Background(), "a") + a2, relA2 := r.Track(context.Background(), "a") + b, relB := r.Track(context.Background(), "b") + defer relA1() + defer relA2() + defer relB() + + if n := r.CloseDevice("a"); n != 2 { + t.Fatalf("closed %d, want 2", n) + } + if !ended(a1) || !ended(a2) { + t.Fatal("a request of the closed device is still open") + } + if ended(b) { + t.Fatal("another device was closed too") + } + if n := r.CloseDevice("a"); n != 0 { + t.Fatalf("second close reported %d", n) + } + if n := r.CloseDevice("unknown"); n != 0 { + t.Fatalf("unknown device reported %d", n) + } +} + +func TestReleaseForgetsTheRequest(t *testing.T) { + r := New() + ctx, release := r.Track(context.Background(), "a") + if r.Open("a") != 1 { + t.Fatalf("open = %d", r.Open("a")) + } + release() + if r.Open("a") != 0 { + t.Fatalf("open after release = %d", r.Open("a")) + } + if !ended(ctx) { + t.Fatal("release left the context open") + } + release() // twice is harmless +} + +func TestTheParentEndingEndsTheRequest(t *testing.T) { + r := New() + parent, cancel := context.WithCancel(context.Background()) + ctx, release := r.Track(parent, "a") + defer release() + cancel() + if !ended(ctx) { + t.Fatal("the request outlived its parent") + } +} + +func TestCloseAllEndsEverythingAndRefusesNewRequests(t *testing.T) { + r := New() + a, relA := r.Track(context.Background(), "a") + b, relB := r.Track(context.Background(), "b") + defer relA() + defer relB() + r.CloseAll() + if !ended(a) || !ended(b) { + t.Fatal("a request survived CloseAll") + } + late, relLate := r.Track(context.Background(), "a") + defer relLate() + if !ended(late) { + t.Fatal("a request started after CloseAll is open") + } +} + +func TestConcurrentUse(t *testing.T) { + r := New() + var wg sync.WaitGroup + for i := 0; i < 50; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, release := r.Track(context.Background(), "a") + r.Open("a") + r.CloseDevice("a") + release() + }() + } + wg.Wait() + if r.Open("a") != 0 { + t.Fatalf("open = %d after everything was released", r.Open("a")) + } +} From 188d02c5c26770bbbe56735ff1d677d48da91310 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 05:27:32 +0530 Subject: [PATCH 14/32] feat(agent): handler with roles, pairing endpoint and access log --- agent/internal/exec/bridge.go | 13 +- agent/internal/exec/bridge_test.go | 62 ++++ agent/internal/proxy/proxy.go | 20 ++ agent/internal/proxy/proxy_test.go | 46 +++ agent/internal/server/handler.go | 90 ++++++ agent/internal/server/handler_test.go | 437 ++++++++++++++++++++++++++ agent/internal/server/middleware.go | 208 ++++++++++++ agent/internal/server/pair.go | 117 +++++++ 8 files changed, 990 insertions(+), 3 deletions(-) create mode 100644 agent/internal/server/handler.go create mode 100644 agent/internal/server/handler_test.go create mode 100644 agent/internal/server/middleware.go create mode 100644 agent/internal/server/pair.go diff --git a/agent/internal/exec/bridge.go b/agent/internal/exec/bridge.go index 834ac34..9ae426c 100644 --- a/agent/internal/exec/bridge.go +++ b/agent/internal/exec/bridge.go @@ -87,9 +87,9 @@ func NewHandler(dockerHost string) (http.Handler, error) { return nil, err } // Default CheckOrigin enforces same-origin when an Origin header is present - // and allows it when absent (the native-app client sends none). The exec - // session is also gated by bearer-token auth (RequireToken), so this is - // defense-in-depth against a browser client, not the primary control. + // and allows it when absent (the app sends none). The server refuses any + // request with an Origin header before it gets here, and the route is + // behind authentication, so this is a third line of defence. upgrader := websocket.Upgrader{} return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { execID := r.PathValue("id") @@ -108,6 +108,13 @@ func NewHandler(dockerHost string) (http.Handler, error) { return } defer conn.Close() + // The request's context ends when the device is removed or the agent + // stops. Closing both ends then unblocks the copy loops below. + stop := context.AfterFunc(r.Context(), func() { + ws.Close() + conn.Close() + }) + defer stop() bridge(ws, conn) }), nil } diff --git a/agent/internal/exec/bridge_test.go b/agent/internal/exec/bridge_test.go index 2faa811..2393f35 100644 --- a/agent/internal/exec/bridge_test.go +++ b/agent/internal/exec/bridge_test.go @@ -140,3 +140,65 @@ func TestExecBridgeEchoesBothDirections(t *testing.T) { t.Fatalf("echo = %q, want hello", data) } } + +func TestEndingTheRequestContextClosesTheTerminal(t *testing.T) { + // Fake daemon: accept the exec start, reply 101, then stay silent. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + started := make(chan struct{}) + daemonSawEnd := make(chan struct{}) + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + defer conn.Close() + br := bufio.NewReader(conn) + req, err := http.ReadRequest(br) + if err != nil { + return + } + io.ReadAll(req.Body) + io.WriteString(conn, "HTTP/1.1 101 UPGRADED\r\n\r\n") + close(started) + io.Copy(io.Discard, br) // returns when the agent closes its side + close(daemonSawEnd) + }() + + h, err := NewHandler("tcp://" + ln.Addr().String()) + if err != nil { + t.Fatalf("NewHandler: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.SetPathValue("id", "abc") + h.ServeHTTP(w, r.WithContext(ctx)) + })) + defer srv.Close() + + c, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http")+"/exec/abc/ws", nil) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer c.Close() + + select { + case <-started: + case <-time.After(3 * time.Second): + t.Fatal("the exec never started") + } + cancel() // the device was removed, or the agent is stopping + c.SetReadDeadline(time.Now().Add(3 * time.Second)) + if _, _, err := c.ReadMessage(); err == nil { + t.Fatal("the terminal stayed open") + } + select { + case <-daemonSawEnd: + case <-time.After(3 * time.Second): + t.Fatal("the connection to the daemon stayed open") + } +} diff --git a/agent/internal/proxy/proxy.go b/agent/internal/proxy/proxy.go index ff0ed2a..c8459ae 100644 --- a/agent/internal/proxy/proxy.go +++ b/agent/internal/proxy/proxy.go @@ -3,6 +3,10 @@ package proxy import ( + "encoding/json" + "errors" + "io" + "log" "net/http" "net/http/httputil" "net/url" @@ -31,6 +35,22 @@ func New(dockerHost string) (http.Handler, error) { rp.Director = func(r *http.Request) { origDirector(r) r.Host = target.Host + // The bearer token is for the agent. The daemon has no use for it and + // must not see it (registry credentials travel in X-Registry-Auth). + r.Header.Del("Authorization") + } + // Transport errors become JSON answers the app can show, not a bare 502, + // and stay out of the process log (the access log has the status). + rp.ErrorLog = log.New(io.Discard, "", 0) + rp.ErrorHandler = func(w http.ResponseWriter, _ *http.Request, err error) { + status, message := http.StatusBadGateway, "The agent cannot reach the Docker daemon" + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + status, message = http.StatusRequestEntityTooLarge, "The request body is too large" + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + json.NewEncoder(w).Encode(map[string]string{"message": message}) } return rp, nil } diff --git a/agent/internal/proxy/proxy_test.go b/agent/internal/proxy/proxy_test.go index 1d31c8c..f36497b 100644 --- a/agent/internal/proxy/proxy_test.go +++ b/agent/internal/proxy/proxy_test.go @@ -3,6 +3,7 @@ package proxy import ( "encoding/json" "io" + "net" "net/http" "net/http/httptest" "testing" @@ -104,3 +105,48 @@ func TestProxyStreamsIncrementally(t *testing.T) { t.Fatalf("rest = %q, want %q", rest, "second\n") } } + +func TestTheBearerTokenIsNotForwarded(t *testing.T) { + var got http.Header + daemon := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got = r.Header.Clone() + w.Write([]byte("{}")) + })) + defer daemon.Close() + h, err := New("tcp://" + daemon.Listener.Addr().String()) + if err != nil { + t.Fatalf("New: %v", err) + } + req := httptest.NewRequest(http.MethodPost, "/images/create?fromImage=nginx", nil) + req.Header.Set("Authorization", "Bearer dm1.abcd1234.secret") + req.Header.Set("X-Registry-Auth", "registry-credentials") + h.ServeHTTP(httptest.NewRecorder(), req) + if got.Get("Authorization") != "" { + t.Fatalf("the daemon saw Authorization: %q", got.Get("Authorization")) + } + if got.Get("X-Registry-Auth") != "registry-credentials" { + t.Fatal("X-Registry-Auth was not forwarded") + } +} + +func TestAnUnreachableDaemonIsAJSON502(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + ln.Close() // nothing listens there any more + h, err := New("tcp://" + addr) + if err != nil { + t.Fatalf("New: %v", err) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/containers/json", nil)) + if rec.Code != http.StatusBadGateway { + t.Fatalf("code = %d, want 502", rec.Code) + } + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body["message"] != "The agent cannot reach the Docker daemon" { + t.Fatalf("body = %q", rec.Body.String()) + } +} diff --git a/agent/internal/server/handler.go b/agent/internal/server/handler.go new file mode 100644 index 0000000..e035055 --- /dev/null +++ b/agent/internal/server/handler.go @@ -0,0 +1,90 @@ +// Package server composes the agent's HTTP handler: an open health check +// and pairing endpoint, and behind authentication the agent's own API, the +// terminal bridge and the transparent Docker proxy. +package server + +import ( + "io" + "log/slog" + "net/http" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/auth" + "github.com/retransmit/docker-mobile/agent/internal/conns" + "github.com/retransmit/docker-mobile/agent/internal/exec" + "github.com/retransmit/docker-mobile/agent/internal/pairing" + "github.com/retransmit/docker-mobile/agent/internal/proxy" + "github.com/retransmit/docker-mobile/agent/internal/state" + "github.com/retransmit/docker-mobile/agent/internal/throttle" +) + +// APILevel is the version of the agent's own API, reported by whoami. +const APILevel = 1 + +// Options is everything the handler needs. Devices, Pairing, Limiter and +// Conns are required. +type Options struct { + DockerHost string + Devices *state.Devices + // LegacyToken is the shared token from the environment; empty disables it. + LegacyToken string + Pairing *pairing.Manager + // Fingerprint is the agent's certificate fingerprint (32 bytes), or empty + // when it serves plain HTTP behind a proxy. + Fingerprint []byte + Limiter *throttle.Limiter + Conns *conns.Registry + Version string + // Log receives the access log; nil discards it. + Log *slog.Logger + // Now is the clock; nil means time.Now. + Now func() time.Time +} + +// New builds the agent's HTTP handler. +func New(o Options) (http.Handler, error) { + if o.Log == nil { + o.Log = slog.New(slog.NewTextHandler(io.Discard, nil)) + } + if o.Now == nil { + o.Now = time.Now + } + dockerProxy, err := proxy.New(o.DockerHost) + if err != nil { + return nil, err + } + execHandler, err := exec.NewHandler(o.DockerHost) + if err != nil { + return nil, err + } + s := &server{o: o, failures: newFailureLog(o.Log, o.Now)} + authn := &auth.Authenticator{ + Devices: o.Devices, + Legacy: o.LegacyToken, + Limiter: o.Limiter, + Conns: o.Conns, + OnFailure: s.failures.note, + OnCaller: noteCaller, + } + + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("ok")) + }) + mux.HandleFunc("POST /agent/v1/pair", s.handlePair) + mux.Handle("GET /agent/v1/whoami", authn.Require(http.HandlerFunc(s.handleWhoami))) + // Nothing else under /agent/ exists; it must not fall through to Docker. + mux.HandleFunc("/agent/", func(w http.ResponseWriter, _ *http.Request) { + auth.WriteError(w, http.StatusNotFound, "not found") + }) + mux.Handle("GET /exec/{id}/ws", authn.Require(fullOnly(execHandler))) + mux.Handle("/", authn.Require(roleGate(limitBody(dockerProxy)))) + + return accessLog(o.Log, o.Now, rejectBrowsers(mux)), nil +} + +type server struct { + o Options + failures *failureLog +} diff --git a/agent/internal/server/handler_test.go b/agent/internal/server/handler_test.go new file mode 100644 index 0000000..9d2f933 --- /dev/null +++ b/agent/internal/server/handler_test.go @@ -0,0 +1,437 @@ +package server + +import ( + "bytes" + "crypto/rand" + "encoding/base64" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/conns" + "github.com/retransmit/docker-mobile/agent/internal/pairing" + "github.com/retransmit/docker-mobile/agent/internal/state" + "github.com/retransmit/docker-mobile/agent/internal/throttle" +) + +const legacy = "a-shared-token-of-enough-length" + +type clock struct { + mu sync.Mutex + t time.Time +} + +func (c *clock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *clock) advance(d time.Duration) { + c.mu.Lock() + c.t = c.t.Add(d) + c.mu.Unlock() +} + +// daemon is a fake Docker daemon that records what reaches it. +type daemon struct { + *httptest.Server + mu sync.Mutex + seen []string +} + +func newDaemon(t *testing.T) *daemon { + t.Helper() + d := &daemon{} + d.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + d.mu.Lock() + d.seen = append(d.seen, r.Method+" "+r.URL.EscapedPath()+" "+r.Header.Get("Authorization")+" "+string(body)) + d.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`[{"Id":"x"}]`)) + })) + t.Cleanup(d.Close) + return d +} + +func (d *daemon) requests() []string { + d.mu.Lock() + defer d.mu.Unlock() + return append([]string(nil), d.seen...) +} + +type fixture struct { + handler http.Handler + devices *state.Devices + pairing *pairing.Manager + conns *conns.Registry + clock *clock + daemon *daemon + log *bytes.Buffer + fp []byte +} + +func newFixture(t *testing.T, legacyToken string, fingerprint []byte) *fixture { + t.Helper() + dir, err := state.Open(filepath.Join(t.TempDir(), "data")) + if err != nil { + t.Fatal(err) + } + c := &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} + devices, err := state.LoadDevices(dir, c.now) + if err != nil { + t.Fatal(err) + } + f := &fixture{ + devices: devices, + pairing: pairing.NewManager(c.now, rand.Reader), + conns: conns.New(), + clock: c, + daemon: newDaemon(t), + log: &bytes.Buffer{}, + fp: fingerprint, + } + f.handler, err = New(Options{ + DockerHost: "tcp://" + f.daemon.Listener.Addr().String(), + Devices: devices, + LegacyToken: legacyToken, + Pairing: f.pairing, + Fingerprint: fingerprint, + Limiter: throttle.New(c.now), + Conns: f.conns, + Version: "1.2.3", + Log: slog.New(slog.NewTextHandler(f.log, nil)), + Now: c.now, + }) + if err != nil { + t.Fatalf("New: %v", err) + } + return f +} + +func (f *fixture) do(method, path, token string, body io.Reader, headers ...string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, body) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + for i := 0; i+1 < len(headers); i += 2 { + req.Header.Set(headers[i], headers[i+1]) + } + rec := httptest.NewRecorder() + f.handler.ServeHTTP(rec, req) + return rec +} + +func message(t *testing.T, rec *httptest.ResponseRecorder) string { + t.Helper() + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("body is not a JSON message: %q", rec.Body.String()) + } + return body["message"] +} + +var agentFP = bytes.Repeat([]byte{7}, 32) + +func TestHealthzIsOpenAndSaysOnlyOk(t *testing.T) { + f := newFixture(t, "", agentFP) + rec := f.do("GET", "/healthz", "", nil) + if rec.Code != http.StatusOK || rec.Body.String() != "ok" { + t.Fatalf("healthz = %d %q", rec.Code, rec.Body.String()) + } + if f.log.Len() != 0 { + t.Fatalf("the health check was logged: %s", f.log.String()) + } +} + +func TestTheProxyNeedsCredentials(t *testing.T) { + f := newFixture(t, legacy, agentFP) + if rec := f.do("GET", "/containers/json", "", nil); rec.Code != http.StatusUnauthorized { + t.Fatalf("code = %d, want 401", rec.Code) + } + if rec := f.do("GET", "/containers/json", legacy, nil); rec.Code != http.StatusOK { + t.Fatalf("shared token: code = %d, want 200", rec.Code) + } + _, token, _ := f.devices.Add("phone", state.RoleFull) + if rec := f.do("POST", "/v1.45/containers/abc/start", token, nil); rec.Code != http.StatusOK { + t.Fatalf("device token: code = %d, want 200", rec.Code) + } + if n := len(f.daemon.requests()); n != 2 { + t.Fatalf("%d requests reached the daemon, want 2", n) + } +} + +func TestAReadOnlyDeviceReadsButCannotChangeAnything(t *testing.T) { + f := newFixture(t, "", agentFP) + _, token, _ := f.devices.Add("viewer", state.RoleReadOnly) + for _, path := range []string{"/containers/json", "/v1.45/containers/abc/logs", "/events", "/agent/v1/whoami"} { + if rec := f.do("GET", path, token, nil); rec.Code != http.StatusOK { + t.Errorf("GET %s: code = %d, want 200", path, rec.Code) + } + } + before := len(f.daemon.requests()) + refused := []struct{ method, path string }{ + {"POST", "/containers/abc/start"}, + {"DELETE", "/v1.45/containers/abc"}, + {"POST", "/containers/abc/exec"}, + {"GET", "/containers/abc/archive"}, + {"GET", "/exec/abc/ws"}, + {"GET", "/containers/abc%2Fjson"}, + } + for _, r := range refused { + rec := f.do(r.method, r.path, token, nil) + if rec.Code != http.StatusForbidden || message(t, rec) != ReadOnlyMessage { + t.Errorf("%s %s: %d %q, want 403 with the read-only message", r.method, r.path, rec.Code, rec.Body.String()) + } + } + // A path with dot segments is redirected by the router before any + // handler sees it; it must not come back as a success either. + if rec := f.do("GET", "/containers/../containers/abc/start", token, nil); rec.Code == http.StatusOK { + t.Fatalf("a path with dot segments was served: %d", rec.Code) + } + if after := len(f.daemon.requests()); after != before { + t.Fatalf("%d refused requests reached the daemon", after-before) + } +} + +func TestWhoami(t *testing.T) { + f := newFixture(t, legacy, agentFP) + dev, token, _ := f.devices.Add("Pixel 8", state.RoleReadOnly) + rec := f.do("GET", "/agent/v1/whoami", token, nil) + var got whoamiResponse + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("body = %q", rec.Body.String()) + } + if got.Device.ID != dev.ID || got.Device.Name != "Pixel 8" || got.Device.Role != "readonly" || got.Agent.Version != "1.2.3" || got.Agent.API != 1 { + t.Fatalf("whoami = %+v", got) + } + rec = f.do("GET", "/agent/v1/whoami", legacy, nil) + json.Unmarshal(rec.Body.Bytes(), &got) + if got.Device.ID != "env" || got.Device.Role != "full" { + t.Fatalf("whoami with the shared token = %+v", got) + } + if rec := f.do("GET", "/agent/v1/whoami", "", nil); rec.Code != http.StatusUnauthorized { + t.Fatalf("whoami without credentials: %d", rec.Code) + } +} + +func TestUnknownAgentPathsNeverReachDocker(t *testing.T) { + f := newFixture(t, legacy, agentFP) + for _, path := range []string{"/agent/v1/devices", "/agent/v2/whoami", "/agent/", "/agent/v1/pair"} { + if rec := f.do("GET", path, legacy, nil); rec.Code != http.StatusNotFound { + t.Errorf("GET %s: code = %d, want 404", path, rec.Code) + } + } + if n := len(f.daemon.requests()); n != 0 { + t.Fatalf("%d requests reached the daemon", n) + } +} + +func TestARequestFromAWebPageIsRefused(t *testing.T) { + f := newFixture(t, legacy, agentFP) + for _, path := range []string{"/containers/json", "/healthz", "/agent/v1/pair"} { + rec := f.do("GET", path, legacy, nil, "Origin", "https://evil.example") + if rec.Code != http.StatusForbidden { + t.Errorf("%s with an Origin header: code = %d, want 403", path, rec.Code) + } + } + if n := len(f.daemon.requests()); n != 0 { + t.Fatalf("%d requests reached the daemon", n) + } +} + +func TestBodiesAreCappedExceptOnUploadRoutes(t *testing.T) { + f := newFixture(t, legacy, agentFP) + big := strings.NewReader(strings.Repeat("x", maxBody+1)) + rec := f.do("POST", "/containers/create", legacy, big) + if rec.Code != http.StatusRequestEntityTooLarge || message(t, rec) != "The request body is too large" { + t.Fatalf("an oversized body: %d %q, want 413", rec.Code, rec.Body.String()) + } + big = strings.NewReader(strings.Repeat("x", maxBody+1)) + if rec := f.do("POST", "/v1.45/images/load", legacy, big); rec.Code != http.StatusOK { + t.Fatalf("an upload was refused: %d", rec.Code) + } + small := strings.NewReader(`{"Image":"nginx"}`) + if rec := f.do("POST", "/containers/create", legacy, small); rec.Code != http.StatusOK { + t.Fatalf("a normal body was refused: %d", rec.Code) + } +} + +func TestTheTokenNeverReachesTheDaemon(t *testing.T) { + f := newFixture(t, legacy, agentFP) + _, token, _ := f.devices.Add("phone", state.RoleFull) + f.do("GET", "/containers/json", legacy, nil) + f.do("GET", "/containers/json", token, nil) + seen := f.daemon.requests() + if len(seen) != 2 { + t.Fatalf("%d requests reached the daemon, want 2", len(seen)) + } + for _, line := range seen { + if strings.Contains(line, "Bearer") || strings.Contains(line, legacy) { + t.Fatalf("the daemon saw credentials: %s", line) + } + } +} + +func TestTheAccessLogNamesTheDeviceAndHidesSecrets(t *testing.T) { + f := newFixture(t, legacy, agentFP) + dev, token, _ := f.devices.Add("Pixel 8", state.RoleFull) + f.do("GET", "/containers/json?filters=secret-looking-value", token, nil) + line := f.log.String() + for _, want := range []string{"device=" + dev.ID, `name="Pixel 8"`, "method=GET", "path=/containers/json", "status=200"} { + if !strings.Contains(line, want) { + t.Errorf("log line lacks %s: %s", want, line) + } + } + secret := token[strings.LastIndex(token, ".")+1:] + for _, never := range []string{secret, "secret-looking-value", "Bearer"} { + if strings.Contains(line, never) { + t.Errorf("log line contains %q: %s", never, line) + } + } +} + +func TestFailedAuthenticationsAreLoggedOncePerSecondPerAddress(t *testing.T) { + f := newFixture(t, legacy, agentFP) + for i := 0; i < 3; i++ { + f.do("GET", "/containers/json", "wrong", nil) + } + if n := strings.Count(f.log.String(), "authentication failed"); n != 1 { + t.Fatalf("%d failure lines within a second, want 1", n) + } + f.clock.advance(time.Second) + f.do("GET", "/containers/json", "wrong", nil) + if n := strings.Count(f.log.String(), "authentication failed"); n != 2 { + t.Fatalf("%d failure lines, want 2", n) + } + if !strings.Contains(f.log.String(), "from=192.0.2.1") { + t.Fatalf("the source address is missing: %s", f.log.String()) + } +} + +// pair runs the phone's side of a pairing against the handler. +func (f *fixture) pair(t *testing.T, code string, seenFP []byte, name string) (*httptest.ResponseRecorder, []byte) { + t.Helper() + nonce := make([]byte, pairing.NonceLen) + rand.Read(nonce) + body, _ := json.Marshal(pairRequest{ + V: 1, + Nonce: base64.RawURLEncoding.EncodeToString(nonce), + Proof: base64.RawURLEncoding.EncodeToString(pairing.PhoneProof(code, seenFP, nonce)), + Name: name, + }) + return f.do("POST", "/agent/v1/pair", "", bytes.NewReader(body)), nonce +} + +func TestPairingIssuesATokenAndProvesTheAgentHoldsTheCode(t *testing.T) { + f := newFixture(t, "", agentFP) + p, done, _ := f.pairing.Start(state.RoleReadOnly, "") + rec, nonce := f.pair(t, p.Code, agentFP, "Pixel 8") + if rec.Code != http.StatusOK { + t.Fatalf("code = %d %s", rec.Code, rec.Body.String()) + } + var got pairResponse + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + agentNonce, _ := base64.RawURLEncoding.DecodeString(got.Nonce) + proof, _ := base64.RawURLEncoding.DecodeString(got.Proof) + if !bytes.Equal(proof, pairing.AgentProof(p.Code, agentFP, nonce, agentNonce)) { + t.Fatal("the agent's proof does not verify") + } + if got.Device.Name != "Pixel 8" || got.Device.Role != "readonly" || got.Agent.Version != "1.2.3" { + t.Fatalf("response = %+v", got) + } + if rec := f.do("GET", "/containers/json", got.Token, nil); rec.Code != http.StatusOK { + t.Fatalf("the issued token does not authenticate: %d", rec.Code) + } + if rec := f.do("POST", "/containers/x/start", got.Token, nil); rec.Code != http.StatusForbidden { + t.Fatalf("the issued token is not read-only: %d", rec.Code) + } + if r := <-done; r.Outcome != pairing.Paired { + t.Fatalf("result = %+v", r) + } + if rec.Header().Get("Cache-Control") != "no-store" { + t.Fatal("the response with the token may be cached") + } + if strings.Contains(f.log.String(), got.Token) || strings.Contains(f.log.String(), p.Code) { + t.Fatal("the token or the code is in the log") + } +} + +func TestPairingAnswersNothingUsefulWithoutAPendingPairing(t *testing.T) { + f := newFixture(t, "", agentFP) + rec, _ := f.pair(t, "K7QM2XPA9TRC", agentFP, "x") + if rec.Code != http.StatusNotFound { + t.Fatalf("code = %d, want 404", rec.Code) + } +} + +func TestAProofBoundToAnotherCertificateIsRefused(t *testing.T) { + f := newFixture(t, "", agentFP) + p, _, _ := f.pairing.Start(state.RoleFull, "") + rec, _ := f.pair(t, p.Code, bytes.Repeat([]byte{8}, 32), "x") + if rec.Code != http.StatusForbidden { + t.Fatalf("code = %d, want 403", rec.Code) + } + if len(f.devices.List()) != 0 { + t.Fatal("a device was created") + } +} + +func TestMalformedPairingRequestsAreRefused(t *testing.T) { + f := newFixture(t, "", agentFP) + f.pairing.Start(state.RoleFull, "") + ok := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)) + for name, body := range map[string]string{ + "not json": "{", + "wrong version": `{"v":2,"nonce":"` + ok + `","proof":"` + ok + `"}`, + "no version": `{"nonce":"` + ok + `","proof":"` + ok + `"}`, + "short nonce": `{"v":1,"nonce":"AAAA","proof":"` + ok + `"}`, + "bad base64": `{"v":1,"nonce":"***","proof":"` + ok + `"}`, + "padded base64": `{"v":1,"nonce":"` + ok + `=","proof":"` + ok + `"}`, + "no proof": `{"v":1,"nonce":"` + ok + `","proof":""}`, + "huge": `{"v":1,"name":"` + strings.Repeat("x", maxPairBody) + `"}`, + } { + rec := f.do("POST", "/agent/v1/pair", "", strings.NewReader(body)) + if rec.Code != http.StatusBadRequest { + t.Errorf("%s: code = %d, want 400", name, rec.Code) + } + } +} + +func TestWrongPairingProofsCountAgainstTheAddress(t *testing.T) { + f := newFixture(t, "", agentFP) + for i := 0; i < throttle.Threshold; i++ { + f.pairing.Start(state.RoleFull, "") // a fresh pairing, so the try limit is not what stops it + rec, _ := f.pair(t, "000000000000", agentFP, "x") + if rec.Code != http.StatusForbidden { + t.Fatalf("try %d: code = %d, want 403", i+1, rec.Code) + } + } + p, _, _ := f.pairing.Start(state.RoleFull, "") + rec, _ := f.pair(t, p.Code, agentFP, "x") + if rec.Code != http.StatusTooManyRequests || rec.Header().Get("Retry-After") != "60" { + t.Fatalf("the right code from a blocked address: %d, Retry-After %q", rec.Code, rec.Header().Get("Retry-After")) + } + f.clock.advance(time.Minute) + if rec, _ := f.pair(t, p.Code, agentFP, "x"); rec.Code != http.StatusOK { + t.Fatalf("after the block: code = %d, want 200", rec.Code) + } +} + +func TestPairingWithoutACertificateBindsToAnEmptyFingerprint(t *testing.T) { + f := newFixture(t, "", nil) + p, _, _ := f.pairing.Start(state.RoleFull, "") + if rec, _ := f.pair(t, p.Code, nil, "x"); rec.Code != http.StatusOK { + t.Fatalf("code = %d, want 200", rec.Code) + } +} diff --git a/agent/internal/server/middleware.go b/agent/internal/server/middleware.go new file mode 100644 index 0000000..6f7a8d5 --- /dev/null +++ b/agent/internal/server/middleware.go @@ -0,0 +1,208 @@ +package server + +import ( + "bufio" + "context" + "errors" + "log/slog" + "net" + "net/http" + "regexp" + "sync" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/auth" + "github.com/retransmit/docker-mobile/agent/internal/policy" + "github.com/retransmit/docker-mobile/agent/internal/state" + "github.com/retransmit/docker-mobile/agent/internal/throttle" +) + +// ReadOnlyMessage is what a read-only device gets for a refused request. The +// app shows it as is. +const ReadOnlyMessage = "This device has read-only access" + +// maxBody caps request bodies, except on the few routes that upload. +const maxBody = 16 << 20 + +// uploads are the routes whose bodies may be large: image builds, image +// loads and file uploads into a container. +var uploads = regexp.MustCompile(`^(/v[0-9]+\.[0-9]+)?(/build|/images/load|/containers/[^/]+/archive)$`) + +// rejectBrowsers refuses anything a web page sent. The app never sends an +// Origin header; a browser always does on a cross-site request. +func rejectBrowsers(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Origin") != "" { + auth.WriteError(w, http.StatusForbidden, "requests from web pages are not accepted") + return + } + next.ServeHTTP(w, r) + }) +} + +// roleGate lets a read-only device through only for the reads on the list. +func roleGate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + dev, _ := auth.Caller(r.Context()) + if dev.Role != state.RoleFull && !policy.AllowedReadOnly(r.Method, r.URL.EscapedPath()) { + auth.WriteError(w, http.StatusForbidden, ReadOnlyMessage) + return + } + next.ServeHTTP(w, r) + }) +} + +// fullOnly refuses read-only devices outright. +func fullOnly(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if dev, _ := auth.Caller(r.Context()); dev.Role != state.RoleFull { + auth.WriteError(w, http.StatusForbidden, ReadOnlyMessage) + return + } + next.ServeHTTP(w, r) + }) +} + +// limitBody caps the request body unless the route is an upload. +func limitBody(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Body != nil && !uploads.MatchString(r.URL.Path) { + r.Body = http.MaxBytesReader(w, r.Body, maxBody) + } + next.ServeHTTP(w, r) + }) +} + +// requestInfo travels with a request so that the access log, which wraps +// everything, can name the device that authentication found further in. +type requestInfo struct { + mu sync.Mutex + device state.Device +} + +type infoKey struct{} + +func noteCaller(r *http.Request, dev state.Device) { + if info, ok := r.Context().Value(infoKey{}).(*requestInfo); ok { + info.mu.Lock() + info.device = dev + info.mu.Unlock() + } +} + +// accessLog writes one line per finished request. It never logs a query +// string, a header or a body. The health check is not logged. +func accessLog(log *slog.Logger, now func() time.Time, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/healthz" { + next.ServeHTTP(w, r) + return + } + start := now() + info := &requestInfo{} + sw := &statusWriter{ResponseWriter: w} + next.ServeHTTP(sw, r.WithContext(context.WithValue(r.Context(), infoKey{}, info))) + info.mu.Lock() + dev := info.device + info.mu.Unlock() + log.Info("request", + "device", dev.ID, + "name", dev.Name, + "method", r.Method, + "path", r.URL.Path, + "status", sw.code(), + "bytes", sw.bytes, + "ms", now().Sub(start).Milliseconds(), + ) + }) +} + +// statusWriter records the status and size of a response. It keeps +// streaming (Flush) and connection takeover (Hijack) working, which the +// proxy and the terminal bridge depend on. +type statusWriter struct { + http.ResponseWriter + status int + bytes int64 + hijacked bool +} + +func (w *statusWriter) WriteHeader(status int) { + if w.status == 0 { + w.status = status + } + w.ResponseWriter.WriteHeader(status) +} + +func (w *statusWriter) Write(p []byte) (int, error) { + if w.status == 0 { + w.status = http.StatusOK + } + n, err := w.ResponseWriter.Write(p) + w.bytes += int64(n) + return n, err +} + +func (w *statusWriter) Flush() { + if f, ok := w.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} + +func (w *statusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + h, ok := w.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, errors.New("the connection cannot be taken over") + } + conn, rw, err := h.Hijack() + if err == nil { + w.hijacked = true + } + return conn, rw, err +} + +// Unwrap lets http.ResponseController reach the real writer. +func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func (w *statusWriter) code() int { + switch { + case w.hijacked: + return http.StatusSwitchingProtocols + case w.status == 0: + return http.StatusOK + } + return w.status +} + +// failureLog reports failed authentications, at most one line a second per +// source address. +type failureLog struct { + log *slog.Logger + now func() time.Time + + mu sync.Mutex + last map[string]time.Time +} + +// maxFailureAddrs bounds what failureLog remembers. +const maxFailureAddrs = 1000 + +func newFailureLog(log *slog.Logger, now func() time.Time) *failureLog { + return &failureLog{log: log, now: now, last: map[string]time.Time{}} +} + +func (f *failureLog) note(remoteAddr string) { + key := throttle.Key(remoteAddr) + now := f.now() + f.mu.Lock() + if last, seen := f.last[key]; seen && now.Sub(last) < time.Second { + f.mu.Unlock() + return + } + if len(f.last) >= maxFailureAddrs { + f.last = map[string]time.Time{} + } + f.last[key] = now + f.mu.Unlock() + f.log.Warn("authentication failed", "from", key) +} diff --git a/agent/internal/server/pair.go b/agent/internal/server/pair.go new file mode 100644 index 0000000..fa69f64 --- /dev/null +++ b/agent/internal/server/pair.go @@ -0,0 +1,117 @@ +package server + +import ( + "encoding/base64" + "encoding/json" + "errors" + "io" + "math" + "net/http" + "strconv" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/auth" + "github.com/retransmit/docker-mobile/agent/internal/pairing" + "github.com/retransmit/docker-mobile/agent/internal/throttle" +) + +const ( + // maxPairBody is far more than a pairing request needs. + maxPairBody = 4 << 10 + // pairBodyTimeout is how long a pairing request may take to arrive. + pairBodyTimeout = 10 * time.Second +) + +type pairRequest struct { + V int `json:"v"` + Nonce string `json:"nonce"` + Proof string `json:"proof"` + Name string `json:"name"` +} + +type deviceInfo struct { + ID string `json:"id"` + Name string `json:"name"` + Role string `json:"role"` +} + +type agentInfo struct { + Version string `json:"version"` + API int `json:"api"` +} + +type pairResponse struct { + Nonce string `json:"nonce"` + Proof string `json:"proof"` + Token string `json:"token"` + Device deviceInfo `json:"device"` + Agent agentInfo `json:"agent"` +} + +type whoamiResponse struct { + Device deviceInfo `json:"device"` + Agent agentInfo `json:"agent"` +} + +// handlePair is the one endpoint a stranger may call. It answers nothing +// useful unless a pairing is pending and the caller proves it holds the code. +func (s *server) handlePair(w http.ResponseWriter, r *http.Request) { + key := throttle.Key(r.RemoteAddr) + if left, blocked := s.o.Limiter.Blocked(key); blocked { + w.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(left.Seconds())))) + auth.WriteError(w, http.StatusTooManyRequests, "Too many failed attempts from this address") + return + } + // A stranger may call this, so the body must arrive promptly: without a + // deadline a slow sender could hold the connection open for ever. + rc := http.NewResponseController(w) + rc.SetReadDeadline(time.Now().Add(pairBodyTimeout)) + var req pairRequest + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxPairBody)) + rc.SetReadDeadline(time.Time{}) + if err != nil || json.Unmarshal(body, &req) != nil || req.V != 1 { + auth.WriteError(w, http.StatusBadRequest, "malformed pairing request") + return + } + nonce, errN := base64.RawURLEncoding.DecodeString(req.Nonce) + proof, errP := base64.RawURLEncoding.DecodeString(req.Proof) + if errN != nil || errP != nil || len(nonce) != pairing.NonceLen || len(proof) == 0 { + auth.WriteError(w, http.StatusBadRequest, "malformed pairing request") + return + } + got, err := s.o.Pairing.Redeem(s.o.Fingerprint, nonce, proof, req.Name, s.o.Devices.Add) + switch { + case errors.Is(err, pairing.ErrNone): + auth.WriteError(w, http.StatusNotFound, "No pairing is in progress on this agent") + return + case errors.Is(err, pairing.ErrWrongProof): + s.o.Limiter.Fail(key) + s.failures.note(r.RemoteAddr) + auth.WriteError(w, http.StatusForbidden, "The pairing code is wrong") + return + case err != nil: + s.o.Log.Error("pairing failed", "error", err.Error()) + auth.WriteError(w, http.StatusInternalServerError, "The agent could not store the new device") + return + } + s.o.Log.Info("device paired", "device", got.Device.ID, "name", got.Device.Name, "role", string(got.Device.Role)) + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + json.NewEncoder(w).Encode(pairResponse{ + Nonce: base64.RawURLEncoding.EncodeToString(got.AgentNonce), + Proof: base64.RawURLEncoding.EncodeToString(got.AgentProof), + Token: got.Token, + Device: deviceInfo{ID: got.Device.ID, Name: got.Device.Name, Role: string(got.Device.Role)}, + Agent: agentInfo{Version: s.o.Version, API: APILevel}, + }) +} + +// handleWhoami tells a device what the agent knows it as. +func (s *server) handleWhoami(w http.ResponseWriter, r *http.Request) { + dev, _ := auth.Caller(r.Context()) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(whoamiResponse{ + Device: deviceInfo{ID: dev.ID, Name: dev.Name, Role: string(dev.Role)}, + Agent: agentInfo{Version: s.o.Version, API: APILevel}, + }) +} From 79fdc72f7ba657cffecb853ce5793a3b36c25783 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 05:42:45 +0530 Subject: [PATCH 15/32] fix(agent): a throttle block never shrinks and IPv6 counts per network --- agent/internal/throttle/throttle.go | 109 +++++++-- agent/internal/throttle/throttle_test.go | 269 ++++++++++++++++++++++- 2 files changed, 347 insertions(+), 31 deletions(-) diff --git a/agent/internal/throttle/throttle.go b/agent/internal/throttle/throttle.go index 0be7e10..48f4c05 100644 --- a/agent/internal/throttle/throttle.go +++ b/agent/internal/throttle/throttle.go @@ -1,9 +1,12 @@ // Package throttle slows down guessing: it counts failed attempts per source -// address and blocks an address for a growing time once it fails too often. +// address (per /64 network for IPv6) and blocks a source for a growing time +// once it fails too often. package throttle import ( "net" + "net/netip" + "slices" "sync" "time" ) @@ -18,9 +21,16 @@ const ( BasePenalty = time.Minute // MaxPenalty caps the block. MaxPenalty = 15 * time.Minute - // maxAddresses bounds memory: beyond it, addresses with nothing left to - // remember are dropped, and failing that the oldest ones. + // maxFailures is how many failure times one address keeps, the newest + // ones. The penalty reaches MaxPenalty at this count and stays there, so + // older times change nothing. + maxFailures = Threshold + 4 + // maxAddresses bounds memory: a full table makes room before it takes a + // new address, see evictLocked. maxAddresses = 10000 + // evictBatch is how many addresses a full table gives up in one pass when + // none of them can simply be forgotten. + evictBatch = maxAddresses / 10 ) type entry struct { @@ -36,22 +46,46 @@ type Limiter struct { addrs map[string]*entry } -// New returns a limiter that reads time from now. +// New returns a limiter that reads time from now. Outside tests, pass +// time.Now itself: its values carry the monotonic reading, so a step of the +// wall clock moves no block end. A clock without that reading lets such a +// step shorten or lengthen every block. func New(now func() time.Time) *Limiter { return &Limiter{now: now, addrs: map[string]*entry{}} } // Key turns a remote address ("host:port") into the key failures are counted -// under: the host alone. +// under. An IPv4 address is its own key, also when it is written as IPv6 +// ("::ffff:192.0.2.7"). An IPv6 address is counted under its /64 network +// ("2001:db8:1:2::/64"), because whoever has one address in such a network +// can usually take any other in it. A zone stays in the key +// ("fe80::/64%eth0"): a link-local network on another interface is another +// network. A host that is not an IP address is returned as it is, and so is +// a string that is not "host:port". func Key(remoteAddr string) string { host, _, err := net.SplitHostPort(remoteAddr) if err != nil { return remoteAddr } - return host + addr, err := netip.ParseAddr(host) + if err != nil { + return host + } + zone := addr.Zone() + addr = addr.WithZone("").Unmap() + if addr.Is4() { + return addr.String() + } + network := netip.PrefixFrom(addr, 64).Masked().String() + if zone != "" { + network += "%" + zone + } + return network } // Blocked reports whether key is blocked right now, and for how much longer. +// Ask it before a credential is checked: for a blocked address the caller +// neither runs the check nor calls Fail. func (l *Limiter) Blocked(key string) (time.Duration, bool) { l.mu.Lock() defer l.mu.Unlock() @@ -65,7 +99,10 @@ func (l *Limiter) Blocked(key string) (time.Duration, bool) { return 0, false } -// Fail records one failed attempt from key. +// Fail records one failed attempt from key. Call it once for every check +// that tested a guess and found it wrong, and never after a success. It is +// not meant for an address that Blocked reports as blocked; when it is called +// for one all the same, the failure counts and the block can only get longer. func (l *Limiter) Fail(key string) { l.mu.Lock() defer l.mu.Unlock() @@ -79,6 +116,9 @@ func (l *Limiter) Fail(key string) { l.addrs[key] = e } e.failures = append(recent(e.failures, now), now) + if over := len(e.failures) - maxFailures; over > 0 { + e.failures = e.failures[over:] + } if n := len(e.failures); n >= Threshold { penalty := BasePenalty for i := Threshold; i < n && penalty < MaxPenalty; i++ { @@ -87,7 +127,12 @@ func (l *Limiter) Fail(key string) { if penalty > MaxPenalty { penalty = MaxPenalty } - e.blockedUntil = now.Add(penalty) + // The end of a block only moves forward. A block can outlast the + // window, and failures counted after the older ones have left it are + // worth a smaller penalty; that must not cut a running block short. + if until := now.Add(penalty); until.After(e.blockedUntil) { + e.blockedUntil = until + } } } @@ -100,26 +145,48 @@ func recent(failures []time.Time, now time.Time) []time.Time { return failures[cut:] } -// evictLocked makes room: first every address with nothing left to remember, -// then, if none could go, the address whose last failure is oldest. +// evictLocked makes room in a full table. First every address with nothing +// left to remember goes: no failure inside the window and no running block. +// If the table is still full after that, evictBatch addresses go in one pass, +// so that the next new addresses need no pass at all. Addresses that are not +// blocked go before blocked ones; among those not blocked the one whose last +// failure is oldest goes first, among blocked ones the one whose block ends +// soonest. func (l *Limiter) evictLocked(now time.Time) { - var oldestKey string - var oldest time.Time for key, e := range l.addrs { e.failures = recent(e.failures, now) if len(e.failures) == 0 && !e.blockedUntil.After(now) { delete(l.addrs, key) - continue } - last := e.blockedUntil - if n := len(e.failures); n > 0 && e.failures[n-1].After(last) { - last = e.failures[n-1] - } - if oldestKey == "" || last.Before(oldest) { - oldestKey, oldest = key, last + } + if len(l.addrs) < maxAddresses { + return + } + type candidate struct { + key string + blocked bool + // at is the end of the block of a blocked address, and the last + // failure of one that is not blocked. + at time.Time + } + candidates := make([]candidate, 0, len(l.addrs)) + for key, e := range l.addrs { + c := candidate{key: key, blocked: e.blockedUntil.After(now), at: e.blockedUntil} + if !c.blocked { + c.at = e.failures[len(e.failures)-1] } + candidates = append(candidates, c) } - if len(l.addrs) >= maxAddresses && oldestKey != "" { - delete(l.addrs, oldestKey) + slices.SortFunc(candidates, func(a, b candidate) int { + if a.blocked != b.blocked { + if a.blocked { + return 1 + } + return -1 + } + return a.at.Compare(b.at) + }) + for _, c := range candidates[:evictBatch] { + delete(l.addrs, c.key) } } diff --git a/agent/internal/throttle/throttle_test.go b/agent/internal/throttle/throttle_test.go index f790d0e..7de1e1d 100644 --- a/agent/internal/throttle/throttle_test.go +++ b/agent/internal/throttle/throttle_test.go @@ -2,14 +2,27 @@ package throttle import ( "fmt" + "sync" "testing" "time" ) -type clock struct{ t time.Time } +type clock struct { + mu sync.Mutex + t time.Time +} + +func (c *clock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} -func (c *clock) now() time.Time { return c.t } -func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) } +func (c *clock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} func newClock() *clock { return &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} } @@ -19,6 +32,21 @@ func fail(l *Limiter, key string, n int) { } } +func TestThresholdWindowAndPenaltiesInNumbers(t *testing.T) { + if n := Threshold; n != 10 { + t.Errorf("Threshold = %d, want 10", n) + } + for name, d := range map[string][2]time.Duration{ + "Window": {Window, 10 * time.Minute}, + "BasePenalty": {BasePenalty, time.Minute}, + "MaxPenalty": {MaxPenalty, 15 * time.Minute}, + } { + if d[0] != d[1] { + t.Errorf("%s = %v, want %v", name, d[0], d[1]) + } + } +} + func TestNineFailuresDoNotBlock(t *testing.T) { l := New(newClock().now) fail(l, "10.0.0.1", Threshold-1) @@ -58,6 +86,21 @@ func TestThePenaltyDoublesAndIsCapped(t *testing.T) { } } +func TestABlockNeverGetsShorter(t *testing.T) { + c := newClock() + l := New(c.now) + fail(l, "a", Threshold+4) // 15 minutes + c.advance(Window) // the failures left the window, the block has 5 minutes to go + before, _ := l.Blocked("a") + if before != 5*time.Minute { + t.Fatalf("%v of the block left after the window, want 5 minutes", before) + } + fail(l, "a", Threshold) // by themselves these ten are worth a minute + if after, _ := l.Blocked("a"); after < before { + t.Fatalf("ten more failures cut the block from %v to %v", before, after) + } +} + func TestAddressesAreCountedSeparately(t *testing.T) { l := New(newClock().now) fail(l, "a", Threshold) @@ -84,13 +127,75 @@ func TestFailuresLeaveTheWindow(t *testing.T) { } } +func TestTheWindowIsTenMinutesToTheNanosecond(t *testing.T) { + c := newClock() + l := New(c.now) + fail(l, "just-inside", 9) + c.advance(10*time.Minute - time.Nanosecond) + l.Fail("just-inside") + if _, blocked := l.Blocked("just-inside"); !blocked { + t.Error("nine failures a nanosecond inside the window and a tenth did not block") + } + + fail(l, "just-outside", 9) + c.advance(10 * time.Minute) + l.Fail("just-outside") + if _, blocked := l.Blocked("just-outside"); blocked { + t.Error("nine failures exactly ten minutes old and a tenth blocked") + } +} + +func TestFailuresAtDifferentTimesAddUp(t *testing.T) { + c := newClock() + l := New(c.now) + for i := 1; i <= 10; i++ { + l.Fail("a") + left, blocked := l.Blocked("a") + if blocked != (i == 10) { + t.Fatalf("one failure a minute, after failure %d: blocked = %v", i, blocked) + } + if blocked && left != time.Minute { + t.Fatalf("the tenth failure blocks for %v, want a minute", left) + } + c.advance(time.Minute) + } +} + +func TestOneAddressKeepsOnlyItsNewestFailures(t *testing.T) { + c := newClock() + l := New(c.now) + for i := 0; i < 5000; i++ { + c.advance(time.Millisecond) + l.Fail("a") + } + kept := l.addrs["a"].failures + if n := len(kept); n != Threshold+4 { + t.Fatalf("%d failure times kept for one address, want %d", n, Threshold+4) + } + if newest, oldest := kept[len(kept)-1], kept[0]; !newest.Equal(c.now()) || c.now().Sub(oldest) != 13*time.Millisecond { + t.Fatalf("kept the times from %v to %v, want the newest ones up to %v", oldest, newest, c.now()) + } + if left, blocked := l.Blocked("a"); !blocked || left != MaxPenalty { + t.Fatalf("blocked = %v for %v, want %v", blocked, left, MaxPenalty) + } +} + func TestKeyDropsThePort(t *testing.T) { cases := map[string]string{ - "192.168.1.5:51234": "192.168.1.5", - "[::1]:8443": "::1", - "[fe80::1%eth0]:1": "fe80::1%eth0", - "no-port": "no-port", - "": "", + "192.168.1.5:51234": "192.168.1.5", + "192.0.2.7:51234": "192.0.2.7", + "[::ffff:192.0.2.7]:1": "192.0.2.7", + "[2001:db8:1:2:aaaa:bbbb:cccc:dddd]:443": "2001:db8:1:2::/64", + "[2001:db8:1:2::1]:443": "2001:db8:1:2::/64", + "[2001:db8:1:3::1]:443": "2001:db8:1:3::/64", + "[::1]:8443": "::/64", + "[fe80::1%eth0]:1": "fe80::/64%eth0", + "[fe80::2%eth0]:1": "fe80::/64%eth0", + "[fe80::1%wlan0]:1": "fe80::/64%wlan0", + "example.com:80": "example.com", + "not-an-address": "not-an-address", + "no-port": "no-port", + "": "", } for in, want := range cases { if got := Key(in); got != want { @@ -108,7 +213,7 @@ func TestMemoryIsBounded(t *testing.T) { c.advance(time.Second) } } - // Everything so far is still inside the window: the oldest one goes. + // Everything so far is still inside the window: the oldest ones go. l.Fail("one-more") if n := len(l.addrs); n > maxAddresses { t.Fatalf("%d addresses remembered, cap is %d", n, maxAddresses) @@ -116,7 +221,11 @@ func TestMemoryIsBounded(t *testing.T) { if _, ok := l.addrs["addr-0"]; ok { t.Fatal("the oldest address was not dropped") } - // Once the window has passed, everything forgettable goes at once. + // Once the window has passed, a full table drops everything forgettable + // at once. + for i := 0; len(l.addrs) < maxAddresses; i++ { + l.Fail(fmt.Sprintf("more-%d", i)) + } c.advance(Window) l.Fail("after-the-window") if n := len(l.addrs); n != 1 { @@ -124,6 +233,49 @@ func TestMemoryIsBounded(t *testing.T) { } } +func TestTheTableStaysWithinItsCapAlsoWithAnEmptyKey(t *testing.T) { + c := newClock() + l := New(c.now) + l.Fail("") // the oldest entry of all + c.advance(time.Second) + for i := 0; i < 2*maxAddresses; i++ { + l.Fail(fmt.Sprintf("addr-%d", i)) + if n := len(l.addrs); n > maxAddresses { + t.Fatalf("%d addresses remembered after %d more, cap is %d", n, i+1, maxAddresses) + } + } + if _, ok := l.addrs[""]; ok { + t.Fatal("the oldest address was kept because its key is empty") + } +} + +func TestMakingRoomFreesATenthOfTheTableAtOnce(t *testing.T) { + c := newClock() + l := New(c.now) + for i := 0; i < maxAddresses; i++ { + l.Fail(fmt.Sprintf("addr-%d", i)) + } + // The table is full and nothing in it can be forgotten. A pass frees a + // tenth of it; until that room is used up the table grows by exactly one + // per new address, which shows that no pass ran in between. + batch := maxAddresses / 10 + passes := 0 + for i := 0; i < 3*batch; i++ { + before := len(l.addrs) + l.Fail(fmt.Sprintf("new-%d", i)) + switch after := len(l.addrs); { + case after == before+1: + case before == maxAddresses && after == maxAddresses-batch+1: + passes++ + default: + t.Fatalf("new address %d: the table went from %d to %d", i+1, before, after) + } + } + if passes != 3 { + t.Fatalf("%d passes for %d new addresses, want 3", passes, 3*batch) + } +} + func TestABlockedAddressIsNotForgottenWhileBlocked(t *testing.T) { c := newClock() l := New(c.now) @@ -136,3 +288,100 @@ func TestABlockedAddressIsNotForgottenWhileBlocked(t *testing.T) { t.Fatal("a blocked address was forgotten") } } + +func TestAddressesThatAreNotBlockedGoBeforeBlockedOnes(t *testing.T) { + c := newClock() + l := New(c.now) + const blockedOnes = 5 + for i := 0; i < blockedOnes; i++ { + fail(l, fmt.Sprintf("blocked-%d", i), Threshold+4) // 15 minutes + } + c.advance(time.Minute) // every other address failed later than the blocked ones + for i := 0; len(l.addrs) < maxAddresses; i++ { + l.Fail(fmt.Sprintf("addr-%d", i)) + } + l.Fail("one-more") + if n, want := len(l.addrs), maxAddresses-maxAddresses/10+1; n != want { + t.Fatalf("%d addresses remembered after making room, want %d", n, want) + } + for i := 0; i < blockedOnes; i++ { + if _, blocked := l.Blocked(fmt.Sprintf("blocked-%d", i)); !blocked { + t.Fatalf("blocked address %d was forgotten while others could go", i) + } + } +} + +func TestWhenEveryAddressIsBlockedTheBlocksThatEndSoonestGoFirst(t *testing.T) { + c := newClock() + l := New(c.now) + // The first addresses failed longest ago but are blocked for 15 minutes. + // The others are blocked for a minute, each a millisecond later than the + // one before it. + const long = 500 + for i := 0; i < maxAddresses; i++ { + n := Threshold + if i < long { + n = Threshold + 4 + } + fail(l, fmt.Sprintf("addr-%d", i), n) + c.advance(time.Millisecond) + } + l.Fail("one-more") + batch := maxAddresses / 10 + for i := 0; i < maxAddresses; i++ { + _, kept := l.addrs[fmt.Sprintf("addr-%d", i)] + if want := i < long || i >= long+batch; kept != want { + t.Fatalf("address %d: kept = %v, want %v", i, kept, want) + } + } +} + +func TestTheLimiterHoldsUnderConcurrentCalls(t *testing.T) { + c := newClock() + l := New(c.now) + const goroutines = 8 + const each = maxAddresses / 4 // twice the cap of distinct keys in all + var wg sync.WaitGroup + for g := 0; g < goroutines; g++ { + wg.Add(1) + go func(g int) { + defer wg.Done() + wrong := 0 + for i := 0; i < each; i++ { + l.Fail("shared") + // This goroutine alone has now failed i+1 times on the shared key. + if _, blocked := l.Blocked("shared"); !blocked && i+1 >= Threshold { + wrong++ + } + own := fmt.Sprintf("g%d-%d", g, i) + l.Fail(own) + if _, blocked := l.Blocked(own); blocked { + wrong++ + } + } + if wrong > 0 { + t.Errorf("goroutine %d got %d wrong answers", g, wrong) + } + }(g) + } + wg.Wait() + + l.mu.Lock() + defer l.mu.Unlock() + shared := l.addrs["shared"] + if shared == nil { + t.Fatal("the shared key was forgotten") + } + if n := len(shared.failures); n != Threshold+4 { + t.Errorf("%d failure times kept for the shared key, want %d", n, Threshold+4) + } + if want := c.now().Add(MaxPenalty); !shared.blockedUntil.Equal(want) { + t.Errorf("the shared key is blocked until %v, want %v", shared.blockedUntil, want) + } + // Every key but the shared one was seen once and the clock stood still, + // so the table filled, gave up a tenth each time it was full, and ends + // one address after its last pass. + if n, want := len(l.addrs), maxAddresses-maxAddresses/10+1; n != want { + t.Errorf("%d addresses remembered, want %d (cap %d)", n, want, maxAddresses) + } +} From 7c942b7caee52b986873517013416823b23c308c Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 05:57:44 +0530 Subject: [PATCH 16/32] fix(agent): a device removed mid-request keeps nothing open --- agent/internal/auth/authenticator.go | 84 +++++-- agent/internal/auth/authenticator_test.go | 267 +++++++++++++++++++++- agent/internal/conns/conns.go | 6 +- 3 files changed, 330 insertions(+), 27 deletions(-) diff --git a/agent/internal/auth/authenticator.go b/agent/internal/auth/authenticator.go index e555b77..4f5b836 100644 --- a/agent/internal/auth/authenticator.go +++ b/agent/internal/auth/authenticator.go @@ -4,6 +4,7 @@ package auth import ( "context" + "crypto/sha256" "crypto/subtle" "encoding/json" "math" @@ -42,21 +43,27 @@ type Authenticator struct { Conns *conns.Registry // OnFailure is told the source address of every failed attempt. OnFailure func(remoteAddr string) - // OnCaller is told who a request belongs to, once that is known. + // OnCaller is told who a request belongs to, once that is known. The + // device comes without the hash of its token, as does the one in the + // request's context. OnCaller func(r *http.Request, dev state.Device) } -// Require lets a request through only with valid credentials. A paired -// device always passes. Anything else from an address that has failed too -// often is refused without a look at its token, so the shared token cannot -// be guessed at speed. +// Require lets a request through only with valid credentials. A token with +// the shape of a device token is always looked up, and a paired device passes +// whatever its address has done before: the failures of others behind the +// same address must not lock it out. Any other request from an address that +// has failed too often is answered with 429; the shared token is not compared +// then, so it cannot be guessed at speed. A request that fails is counted +// against its address, except while that address is blocked. func (a *Authenticator) Require(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { bearer, hasBearer := bearerToken(r) if hasBearer && state.IsDeviceToken(bearer) { if dev, ok := a.Devices.Authenticate(bearer); ok { - a.serve(w, r, dev, next) - return + if a.serve(w, r, dev, bearer, next) { + return + } } } key := throttle.Key(r.RemoteAddr) @@ -67,9 +74,8 @@ func (a *Authenticator) Require(next http.Handler) http.Handler { return } } - if hasBearer && a.Legacy != "" && !state.IsDeviceToken(bearer) && - subtle.ConstantTimeCompare([]byte(bearer), []byte(a.Legacy)) == 1 { - a.serve(w, r, state.Device{ID: LegacyDeviceID, Name: "env-token", Role: state.RoleFull}, next) + if hasBearer && a.Legacy != "" && !state.IsDeviceToken(bearer) && sameToken(bearer, a.Legacy) { + a.serve(w, r, state.Device{ID: LegacyDeviceID, Name: "env-token", Role: state.RoleFull}, "", next) return } if a.Limiter != nil { @@ -82,17 +88,54 @@ func (a *Authenticator) Require(next http.Handler) http.Handler { }) } -func (a *Authenticator) serve(w http.ResponseWriter, r *http.Request, dev state.Device, next http.Handler) { - if a.OnCaller != nil { - a.OnCaller(r, dev) - } - ctx := r.Context() +// serve hands a request with valid credentials to next. deviceToken is the +// token of the paired device it came from, or empty when it came with the +// shared token. It reports false, having answered nothing, when the device is +// no longer paired. +func (a *Authenticator) serve(w http.ResponseWriter, r *http.Request, dev state.Device, deviceToken string, next http.Handler) bool { + parent := r.Context() + ctx := parent + endedByRegistry := false if a.Conns != nil { - tracked, release := a.Conns.Track(ctx, dev.ID) + tracked, release := a.Conns.Track(parent, dev.ID) defer release() ctx = tracked + // Over before it began although the client is still there: the + // registry ended the request. A client that went away ends parent as + // well, and that is not the registry's doing. Asking parent after + // tracked is what makes this sure: a parent that is alive now was + // alive when tracked was found ended. + endedByRegistry = tracked.Err() != nil && parent.Err() == nil + } + // The token was accepted before the request was tracked. A device removed + // in between had its requests closed while this one was not tracked yet, + // so nothing would end it. Hence the second lookup, now that the request + // is tracked: if the device is still paired, any removal comes later and + // its close ends this request too; if it is not, the request is refused. + if deviceToken != "" { + paired, ok := a.Devices.Authenticate(deviceToken) + if !ok { + return false + } + dev = paired + } + // Nothing further in needs the hash of the token, and whatever prints or + // encodes the caller must not find it there. + dev.TokenHash = "" + if a.OnCaller != nil { + a.OnCaller(r, dev) + } + // The registry had ended the request before its device was looked up + // again and found. A removal would have unpaired the device by then, so + // this is the registry refusing everything. That is why the look at the + // context comes before the lookup: taken after it, a device removed just + // after the lookup would be told that the agent stops. + if endedByRegistry { + WriteError(w, http.StatusServiceUnavailable, "The agent is shutting down") + return true } next.ServeHTTP(w, r.WithContext(WithCaller(ctx, dev))) + return true } func bearerToken(r *http.Request) (string, bool) { @@ -103,6 +146,15 @@ func bearerToken(r *http.Request) (string, bool) { return token, true } +// sameToken compares two tokens in constant time. It compares their SHA-256 +// digests, which always have the same length: comparing the tokens themselves +// would answer sooner for a guess of another length, and so give the length +// of the shared token away. +func sameToken(got, want string) bool { + gotSum, wantSum := sha256.Sum256([]byte(got)), sha256.Sum256([]byte(want)) + return subtle.ConstantTimeCompare(gotSum[:], wantSum[:]) == 1 +} + // WriteError answers with a JSON body shaped like the Docker API's errors, so // clients read agent errors and daemon errors the same way. func WriteError(w http.ResponseWriter, status int, message string) { diff --git a/agent/internal/auth/authenticator_test.go b/agent/internal/auth/authenticator_test.go index 628a50a..93b7705 100644 --- a/agent/internal/auth/authenticator_test.go +++ b/agent/internal/auth/authenticator_test.go @@ -3,9 +3,12 @@ package auth import ( "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "path/filepath" + "strings" + "sync" "testing" "time" @@ -14,9 +17,23 @@ import ( "github.com/retransmit/docker-mobile/agent/internal/throttle" ) -type clock struct{ t time.Time } +// clock is a time source the tests set by hand. Goroutines may share it. +type clock struct { + mu sync.Mutex + t time.Time +} + +func (c *clock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} -func (c *clock) now() time.Time { return c.t } +func (c *clock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} type fixture struct { auth *Authenticator @@ -66,8 +83,27 @@ func (f *fixture) do(bearer, remote string) *httptest.ResponseRecorder { return rec } +// counted reports how many failures the limiter holds for the address of +// remote. It finds out by adding failures until the address is blocked, so it +// is the last thing a test does with that address. +func (f *fixture) counted(remote string) int { + key := throttle.Key(remote) + added := 0 + for added <= throttle.Threshold { + if _, blocked := f.auth.Limiter.Blocked(key); blocked { + break + } + f.auth.Limiter.Fail(key) + added++ + } + return throttle.Threshold - added +} + const legacy = "a-shared-token-of-enough-length" +// noDevice has the shape of a device token and belongs to nobody. +var noDevice = "dm1.ffffffff." + strings.Repeat("A", 43) + func TestADeviceTokenIdentifiesItsDevice(t *testing.T) { f := newFixture(t, "") dev, token, _ := f.devices.Add("Pixel 8", state.RoleReadOnly) @@ -77,6 +113,9 @@ func TestADeviceTokenIdentifiesItsDevice(t *testing.T) { if len(f.seen) != 1 || f.seen[0].ID != dev.ID || f.seen[0].Role != state.RoleReadOnly { t.Fatalf("caller = %+v", f.seen) } + if f.seen[0].TokenHash != "" { + t.Fatal("the hash of the token travelled with the request") + } } func TestTheSharedTokenIsAFullDeviceCalledEnvToken(t *testing.T) { @@ -93,6 +132,7 @@ func TestTheSharedTokenIsAFullDeviceCalledEnvToken(t *testing.T) { func TestBadCredentialsAreRefusedWithAJSONMessage(t *testing.T) { f := newFixture(t, legacy) _, token, _ := f.devices.Add("phone", state.RoleFull) + n := 0 for name, bearer := range map[string]string{ "nothing": "", "empty bearer": "Bearer ", @@ -100,10 +140,13 @@ func TestBadCredentialsAreRefusedWithAJSONMessage(t *testing.T) { "wrong scheme": "Basic " + legacy, "no scheme": legacy, "damaged device": "Bearer " + token + "x", - "unknown device": "Bearer dm1.ffffffff.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "unknown device": "Bearer " + noDevice, "lower case scheme": "bearer " + legacy, } { - rec := f.do(bearer, "") + // Each case has its own address, so however many cases there are, none + // of them is answered by the throttle. + n++ + rec := f.do(bearer, fmt.Sprintf("198.51.100.%d:1000", n)) if rec.Code != http.StatusUnauthorized { t.Errorf("%s: code = %d, want 401", name, rec.Code) } @@ -143,6 +186,10 @@ func TestTenFailuresBlockTheAddressButNotItsPairedDevices(t *testing.T) { if got := rec.Header().Get("Retry-After"); got != "60" { t.Fatalf("Retry-After = %q, want 60", got) } + // So is a token with the shape of a device token that belongs to nobody. + if rec := f.do("Bearer "+noDevice, nat); rec.Code != http.StatusTooManyRequests { + t.Fatalf("unknown device: code = %d, want 429", rec.Code) + } // A paired device behind the same address still gets in. if rec := f.do("Bearer "+token, nat); rec.Code != http.StatusOK { t.Fatalf("paired device: code = %d, want 200", rec.Code) @@ -156,12 +203,64 @@ func TestTenFailuresBlockTheAddressButNotItsPairedDevices(t *testing.T) { t.Fatalf("%d failures reported, want %d", len(f.failed), throttle.Threshold) } // When the block ends the shared token works again. - f.clock.t = f.clock.t.Add(time.Minute) + f.clock.advance(time.Minute) if rec := f.do("Bearer "+legacy, nat); rec.Code != http.StatusOK { t.Fatalf("after the block: code = %d, want 200", rec.Code) } } +func TestEveryKindOfFailureIsCountedOnce(t *testing.T) { + f := newFixture(t, legacy) + known, _, _ := f.devices.Add("phone", state.RoleFull) + gone, goneToken, _ := f.devices.Add("old phone", state.RoleFull) + if _, ok, err := f.devices.Remove(gone.ID); !ok || err != nil { + t.Fatalf("remove: ok = %v, err = %v", ok, err) + } + cases := []struct{ name, bearer string }{ + {"no header", ""}, + {"a wrong scheme", "Basic " + legacy}, + {"a malformed device token", "Bearer dm1.no-second-dot"}, + {"an unknown device", "Bearer " + noDevice}, + {"a wrong secret for a known device", "Bearer dm1." + known.ID + "." + strings.Repeat("A", 43)}, + {"a removed device", "Bearer " + goneToken}, + } + for i, c := range cases { + remote := fmt.Sprintf("198.51.100.%d:1000", i+1) + before := len(f.failed) + if rec := f.do(c.bearer, remote); rec.Code != http.StatusUnauthorized { + t.Errorf("%s: code = %d, want 401", c.name, rec.Code) + } + if got := f.failed[before:]; len(got) != 1 || got[0] != remote { + t.Errorf("%s: failures reported = %q, want one from %s", c.name, got, remote) + } + if got := f.counted(remote); got != 1 { + t.Errorf("%s: %d failures counted, want 1", c.name, got) + } + } + if len(f.seen) != 0 { + t.Fatalf("the handler ran for %d refused requests", len(f.seen)) + } +} + +func TestASuccessIsNeverCounted(t *testing.T) { + f := newFixture(t, legacy) + _, token, _ := f.devices.Add("phone", state.RoleFull) + for i, bearer := range []string{"Bearer " + token, "Bearer " + legacy} { + remote := fmt.Sprintf("198.51.100.%d:1000", i+1) + for n := 0; n < 3; n++ { + if rec := f.do(bearer, remote); rec.Code != http.StatusOK { + t.Fatalf("%s: code = %d, want 200", remote, rec.Code) + } + } + if got := f.counted(remote); got != 0 { + t.Errorf("%s: %d failures counted, want 0", remote, got) + } + } + if len(f.failed) != 0 { + t.Fatalf("%d failures reported, want 0", len(f.failed)) + } +} + func TestClosingADeviceEndsItsOpenRequest(t *testing.T) { f := newFixture(t, "") dev, token, _ := f.devices.Add("phone", state.RoleFull) @@ -175,7 +274,11 @@ func TestClosingADeviceEndsItsOpenRequest(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/events", nil) req.Header.Set("Authorization", "Bearer "+token) go h.ServeHTTP(httptest.NewRecorder(), req) - <-started + select { + case <-started: + case <-time.After(3 * time.Second): + t.Fatal("the request did not start") + } if f.auth.Conns.Open(dev.ID) != 1 { t.Fatalf("open = %d, want 1", f.auth.Conns.Open(dev.ID)) } @@ -193,10 +296,154 @@ func TestClosingADeviceEndsItsOpenRequest(t *testing.T) { func TestOnCallerLearnsWhoARequestBelongsTo(t *testing.T) { f := newFixture(t, "") dev, token, _ := f.devices.Add("phone", state.RoleFull) - var told string - f.auth.OnCaller = func(_ *http.Request, d state.Device) { told = d.ID } + var told state.Device + f.auth.OnCaller = func(_ *http.Request, d state.Device) { told = d } f.do("Bearer "+token, "") - if told != dev.ID { - t.Fatalf("OnCaller got %q, want %q", told, dev.ID) + if told.ID != dev.ID { + t.Fatalf("OnCaller got %q, want %q", told.ID, dev.ID) + } + if told.TokenHash != "" { + t.Fatal("OnCaller got the hash of the token") + } +} + +// removingContext is a request context that runs remove the first time it is +// asked for Done. The registry asks while it tracks a request, which is after +// the token was accepted and before the request is registered. +type removingContext struct { + context.Context + once sync.Once + remove func() +} + +func (c *removingContext) Done() <-chan struct{} { + c.once.Do(c.remove) + return c.Context.Done() +} + +func TestADeviceRemovedBeforeItsRequestIsTrackedIsRefused(t *testing.T) { + f := newFixture(t, "") + dev, token, _ := f.devices.Add("phone", state.RoleFull) + told := 0 + f.auth.OnCaller = func(*http.Request, state.Device) { told++ } + removed := false + ctx := &removingContext{Context: context.Background(), remove: func() { + if _, ok, err := f.devices.Remove(dev.ID); !ok || err != nil { + t.Errorf("remove: ok = %v, err = %v", ok, err) + } + f.auth.Conns.CloseDevice(dev.ID) + removed = true + }} + const remote = "203.0.113.7:40000" + ran := false + h := f.auth.Require(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { ran = true })) + req := httptest.NewRequest(http.MethodGet, "/events", nil).WithContext(ctx) + req.Header.Set("Authorization", "Bearer "+token) + req.RemoteAddr = remote + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + if !removed { + t.Fatal("the device was not removed while its request was tracked") + } + if rec.Code != http.StatusUnauthorized { + t.Errorf("code = %d, want 401", rec.Code) + } + if ran { + t.Error("the handler ran for a removed device") + } + if told != 0 { + t.Error("OnCaller was told of a removed device") + } + if n := f.auth.Conns.Open(dev.ID); n != 0 { + t.Errorf("open = %d, want 0", n) + } + // It is a failed credential like any other. + if len(f.failed) != 1 || f.failed[0] != remote { + t.Errorf("failures reported = %q, want one from %s", f.failed, remote) + } + if got := f.counted(remote); got != 1 { + t.Errorf("%d failures counted, want 1", got) + } +} + +func TestADeviceRemovedAfterItsRequestIsTrackedHasItEnded(t *testing.T) { + f := newFixture(t, "") + _, token, _ := f.devices.Add("phone", state.RoleFull) + // OnCaller runs when the device was found again after tracking, so this + // removal lands behind that lookup and its close finds the request. + f.auth.OnCaller = func(_ *http.Request, d state.Device) { + if _, ok, err := f.devices.Remove(d.ID); !ok || err != nil { + t.Errorf("remove: ok = %v, err = %v", ok, err) + } + if n := f.auth.Conns.CloseDevice(d.ID); n != 1 { + t.Errorf("the close ended %d requests, want 1", n) + } + } + ran := false + var seen error + h := f.auth.Require(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + ran, seen = true, r.Context().Err() + })) + req := httptest.NewRequest(http.MethodGet, "/events", nil) + req.Header.Set("Authorization", "Bearer "+token) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code == http.StatusServiceUnavailable { + t.Error("code = 503 although the agent is not shutting down") + } + if !ran || seen != context.Canceled { + t.Errorf("handler ran = %v with context error %v, want it run with an ended context", ran, seen) + } +} + +func TestAfterCloseAllARequestIsRefusedAsShuttingDown(t *testing.T) { + f := newFixture(t, legacy) + _, token, _ := f.devices.Add("phone", state.RoleFull) + f.auth.Conns.CloseAll() + for name, bearer := range map[string]string{ + "device": "Bearer " + token, + "shared token": "Bearer " + legacy, + } { + rec := f.do(bearer, "") + if rec.Code != http.StatusServiceUnavailable { + t.Errorf("%s: code = %d, want 503", name, rec.Code) + } + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body["message"] != "The agent is shutting down" { + t.Errorf("%s: body = %q", name, rec.Body.String()) + } + } + if len(f.seen) != 0 { + t.Errorf("the handler ran for %d requests after CloseAll", len(f.seen)) + } + if len(f.failed) != 0 { + t.Errorf("%d failures reported, want 0", len(f.failed)) + } +} + +func TestAClientThatWentAwayIsNotAnsweredAsShuttingDown(t *testing.T) { + f := newFixture(t, legacy) + _, token, _ := f.devices.Add("phone", state.RoleFull) + for name, bearer := range map[string]string{ + "device": "Bearer " + token, + "shared token": "Bearer " + legacy, + } { + gone, cancel := context.WithCancel(context.Background()) + cancel() + ran := false + h := f.auth.Require(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + ran = r.Context().Err() == context.Canceled + })) + req := httptest.NewRequest(http.MethodGet, "/events", nil).WithContext(gone) + req.Header.Set("Authorization", bearer) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code == http.StatusServiceUnavailable { + t.Errorf("%s: code = 503 although the agent is not shutting down", name) + } + if !ran { + t.Errorf("%s: the handler did not run with the ended context", name) + } } } diff --git a/agent/internal/conns/conns.go b/agent/internal/conns/conns.go index 3735027..d7e7b05 100644 --- a/agent/internal/conns/conns.go +++ b/agent/internal/conns/conns.go @@ -51,7 +51,11 @@ func (r *Registry) Track(parent context.Context, deviceID string) (ctx context.C } } -// CloseDevice ends every open request of one device and reports how many. +// CloseDevice ends every open request of one device and reports how many. It +// ends only what is tracked at that moment, so the order matters: unpair the +// device first and call CloseDevice after that, and let every request check, +// once it is tracked, that its device is still paired. A request is then +// either ended here or fails that check. func (r *Registry) CloseDevice(deviceID string) int { r.mu.Lock() set := r.open[deviceID] From 105a5f764afbfc54014316c99338f0bca0bec370 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 06:09:24 +0530 Subject: [PATCH 17/32] fix(agent): close gaps in the pairing endpoint, access log and terminal start --- agent/internal/exec/bridge.go | 40 ++++- agent/internal/exec/bridge_test.go | 169 +++++++++++++++++++++ agent/internal/proxy/proxy_test.go | 14 +- agent/internal/server/handler.go | 27 +++- agent/internal/server/handler_test.go | 207 ++++++++++++++++++++++++++ agent/internal/server/middleware.go | 54 ++++--- agent/internal/server/pair.go | 12 +- 7 files changed, 496 insertions(+), 27 deletions(-) diff --git a/agent/internal/exec/bridge.go b/agent/internal/exec/bridge.go index 9ae426c..f1baf68 100644 --- a/agent/internal/exec/bridge.go +++ b/agent/internal/exec/bridge.go @@ -4,6 +4,7 @@ package exec import ( "bufio" "context" + "encoding/json" "fmt" "io" "net" @@ -17,12 +18,19 @@ import ( ) // startExecHijack dials the Docker daemon and starts the given exec with a TTY, -// hijacking the connection into a raw bidirectional stream. +// hijacking the connection into a raw bidirectional stream. It gives up, with +// an error, when ctx ends before the daemon has answered. func startExecHijack(ctx context.Context, dial dockerhost.DialFunc, execID string) (net.Conn, error) { conn, err := dial(ctx, "tcp", "docker") if err != nil { return nil, fmt.Errorf("dial docker: %w", err) } + // A daemon that accepts the connection and then says nothing would keep + // the write and the reads below waiting for ever. Closing the connection + // when the context ends is what makes them return. Once this function has + // returned the connection is the caller's to watch. + stop := context.AfterFunc(ctx, func() { conn.Close() }) + defer stop() const body = `{"Detach":false,"Tty":true}` req := "POST /exec/" + execID + "/start HTTP/1.1\r\n" + "Host: docker\r\n" + @@ -79,8 +87,27 @@ type bufferedConn struct { func (c *bufferedConn) Read(p []byte) (int, error) { return c.r.Read(p) } +// maxExecIDLen is the length of the ids the daemon gives out. +const maxExecIDLen = 64 + +// validExecID reports whether id can be an exec id: 1 to 64 hexadecimal +// characters, and so nothing that would end the request line it is put into. +func validExecID(id string) bool { + if len(id) == 0 || len(id) > maxExecIDLen { + return false + } + for i := 0; i < len(id); i++ { + c := id[i] + if !('0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F') { + return false + } + } + return true +} + // NewHandler returns a handler that upgrades the request to a WebSocket and -// bridges it to a hijacked exec stream on the daemon at dockerHost. +// bridges it to a hijacked exec stream on the daemon at dockerHost. The exec +// is named by the path value "id"; one that cannot be an exec id gets a 400. func NewHandler(dockerHost string) (http.Handler, error) { dial, _, err := dockerhost.DialContextFor(dockerHost) if err != nil { @@ -93,6 +120,15 @@ func NewHandler(dockerHost string) (http.Handler, error) { upgrader := websocket.Upgrader{} return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { execID := r.PathValue("id") + // The id becomes part of the request line written to the daemon, and + // it arrives here with its percent-escapes decoded. Anything that is + // not an id is refused before the connection is taken over. + if !validExecID(execID) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"message": "The terminal id is not valid"}) + return + } ws, err := upgrader.Upgrade(w, r, nil) if err != nil { return // Upgrade already wrote an error response diff --git a/agent/internal/exec/bridge_test.go b/agent/internal/exec/bridge_test.go index 2393f35..8b03d49 100644 --- a/agent/internal/exec/bridge_test.go +++ b/agent/internal/exec/bridge_test.go @@ -3,6 +3,7 @@ package exec import ( "bufio" "context" + "encoding/json" "io" "net" "net/http" @@ -202,3 +203,171 @@ func TestEndingTheRequestContextClosesTheTerminal(t *testing.T) { t.Fatal("the connection to the daemon stayed open") } } + +func TestStartingATerminalEndsWithItsContext(t *testing.T) { + // Fake daemon: accept the connection, read the request, then say nothing. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + asked := make(chan struct{}) + over := make(chan struct{}) + defer close(over) // lets the daemon go, which also frees a start that still waits + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + defer conn.Close() + req, err := http.ReadRequest(bufio.NewReader(conn)) + if err != nil { + return + } + io.ReadAll(req.Body) + close(asked) + <-over + }() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + result := make(chan error, 1) + go func() { + conn, err := startExecHijack(ctx, dialTo(ln.Addr().String()), "abc") + if err == nil { + conn.Close() + } + result <- err + }() + + select { + case <-asked: + case <-time.After(3 * time.Second): + t.Fatal("the daemon never got the request") + } + select { + case err := <-result: + t.Fatalf("the start returned before the daemon answered: %v", err) + default: + } + cancel() // the device was removed, or the agent is stopping + select { + case err := <-result: + if err == nil { + t.Fatal("the start succeeded although the daemon never answered") + } + case <-time.After(3 * time.Second): + t.Fatal("the start still waits for the daemon after its context ended") + } +} + +func TestATerminalIDThatIsNoIDIsRefusedBeforeAnythingIsDialled(t *testing.T) { + // The daemon's side: nobody accepts here, so a connection that was dialled + // stays queued and is found at the end. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + h, err := NewHandler("tcp://" + ln.Addr().String()) + if err != nil { + t.Fatalf("NewHandler: %v", err) + } + mux := http.NewServeMux() + mux.Handle("GET /exec/{id}/ws", h) + srv := httptest.NewServer(mux) + defer srv.Close() + + for name, id := range map[string]string{ + "an encoded CR LF": "abc%0d%0aX-Injected:%20yes", + "an encoded space": "abc%20def", + "a letter past f": "abcg", + "65 characters": strings.Repeat("a", 65), + } { + c, resp, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http")+"/exec/"+id+"/ws", nil) + if err == nil { + c.Close() + t.Errorf("%s: the terminal was opened", name) + continue + } + if resp == nil { + t.Errorf("%s: no answer: %v", name, err) + continue + } + if resp.StatusCode != http.StatusBadRequest { + t.Errorf("%s: code = %d, want 400", name, resp.StatusCode) + continue + } + var body map[string]string + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil || body["message"] == "" { + t.Errorf("%s: the body is not a JSON message: %v", name, err) + } + } + + ln.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond)) + if conn, err := ln.Accept(); err == nil { + conn.Close() + t.Fatal("the daemon was dialled for an id that was refused") + } +} + +func TestATerminalIDOf64HexCharactersWorks(t *testing.T) { + // Fake daemon: report the path it was asked for, reply 101, then echo. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + asked := make(chan string, 1) + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + defer conn.Close() + br := bufio.NewReader(conn) + req, err := http.ReadRequest(br) + if err != nil { + return + } + io.ReadAll(req.Body) + asked <- req.URL.Path + io.WriteString(conn, "HTTP/1.1 101 UPGRADED\r\n\r\n") + io.Copy(conn, br) // echo stdin back as stdout + }() + + h, err := NewHandler("tcp://" + ln.Addr().String()) + if err != nil { + t.Fatalf("NewHandler: %v", err) + } + mux := http.NewServeMux() + mux.Handle("GET /exec/{id}/ws", h) + srv := httptest.NewServer(mux) + defer srv.Close() + + id := strings.Repeat("0123456789abcdef", 4) + c, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http")+"/exec/"+id+"/ws", nil) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer c.Close() + if err := c.WriteMessage(websocket.BinaryMessage, []byte("hello")); err != nil { + t.Fatalf("write: %v", err) + } + c.SetReadDeadline(time.Now().Add(3 * time.Second)) + _, data, err := c.ReadMessage() + if err != nil { + t.Fatalf("read: %v", err) + } + if string(data) != "hello" { + t.Fatalf("echo = %q, want hello", data) + } + select { + case path := <-asked: + if path != "/exec/"+id+"/start" { + t.Fatalf("the daemon was asked for %q, want /exec/%s/start", path, id) + } + default: + t.Fatal("the daemon was never asked") + } +} diff --git a/agent/internal/proxy/proxy_test.go b/agent/internal/proxy/proxy_test.go index f36497b..6268ce9 100644 --- a/agent/internal/proxy/proxy_test.go +++ b/agent/internal/proxy/proxy_test.go @@ -107,9 +107,13 @@ func TestProxyStreamsIncrementally(t *testing.T) { } func TestTheBearerTokenIsNotForwarded(t *testing.T) { - var got http.Header + // The daemon's goroutine hands what it saw to the test over a channel. + seen := make(chan http.Header, 1) daemon := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - got = r.Header.Clone() + select { + case seen <- r.Header.Clone(): + default: + } w.Write([]byte("{}")) })) defer daemon.Close() @@ -121,6 +125,12 @@ func TestTheBearerTokenIsNotForwarded(t *testing.T) { req.Header.Set("Authorization", "Bearer dm1.abcd1234.secret") req.Header.Set("X-Registry-Auth", "registry-credentials") h.ServeHTTP(httptest.NewRecorder(), req) + var got http.Header + select { + case got = <-seen: + default: + t.Fatal("the request never reached the daemon") + } if got.Get("Authorization") != "" { t.Fatalf("the daemon saw Authorization: %q", got.Get("Authorization")) } diff --git a/agent/internal/server/handler.go b/agent/internal/server/handler.go index e035055..186b30d 100644 --- a/agent/internal/server/handler.go +++ b/agent/internal/server/handler.go @@ -4,6 +4,7 @@ package server import ( + "errors" "io" "log/slog" "net/http" @@ -21,9 +22,11 @@ import ( // APILevel is the version of the agent's own API, reported by whoami. const APILevel = 1 -// Options is everything the handler needs. Devices, Pairing, Limiter and -// Conns are required. +// Options is everything the handler needs. Devices, Pairing and Limiter are +// required, and DockerHost must name the daemon: without them New returns an +// error. Everything else may be left out, with the effect noted at the field. type Options struct { + // DockerHost is where the Docker daemon listens (unix:// or tcp://). DockerHost string Devices *state.Devices // LegacyToken is the shared token from the environment; empty disables it. @@ -33,16 +36,30 @@ type Options struct { // when it serves plain HTTP behind a proxy. Fingerprint []byte Limiter *throttle.Limiter - Conns *conns.Registry - Version string + // Conns tracks the requests that are open so that they can be ended. Nil + // means none is tracked: removing a device or stopping the agent then + // ends nothing that is open. + Conns *conns.Registry + // Version is what whoami and a pairing report; it may be empty. + Version string // Log receives the access log; nil discards it. Log *slog.Logger // Now is the clock; nil means time.Now. Now func() time.Time } -// New builds the agent's HTTP handler. +// New builds the agent's HTTP handler. It returns an error that names the +// first required option that is missing. func New(o Options) (http.Handler, error) { + // A request goes through each of these; without one it would panic. + switch { + case o.Devices == nil: + return nil, errors.New("server: the option Devices is required") + case o.Pairing == nil: + return nil, errors.New("server: the option Pairing is required") + case o.Limiter == nil: + return nil, errors.New("server: the option Limiter is required") + } if o.Log == nil { o.Log = slog.New(slog.NewTextHandler(io.Discard, nil)) } diff --git a/agent/internal/server/handler_test.go b/agent/internal/server/handler_test.go index 9d2f933..a85e530 100644 --- a/agent/internal/server/handler_test.go +++ b/agent/internal/server/handler_test.go @@ -399,6 +399,8 @@ func TestMalformedPairingRequestsAreRefused(t *testing.T) { "bad base64": `{"v":1,"nonce":"***","proof":"` + ok + `"}`, "padded base64": `{"v":1,"nonce":"` + ok + `=","proof":"` + ok + `"}`, "no proof": `{"v":1,"nonce":"` + ok + `","proof":""}`, + "short proof": `{"v":1,"nonce":"` + ok + `","proof":"` + base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 31)) + `"}`, + "long proof": `{"v":1,"nonce":"` + ok + `","proof":"` + base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 33)) + `"}`, "huge": `{"v":1,"name":"` + strings.Repeat("x", maxPairBody) + `"}`, } { rec := f.do("POST", "/agent/v1/pair", "", strings.NewReader(body)) @@ -435,3 +437,208 @@ func TestPairingWithoutACertificateBindsToAnEmptyFingerprint(t *testing.T) { t.Fatalf("code = %d, want 200", rec.Code) } } + +func TestAskingWhileNothingIsPendingCountsAgainstTheAddress(t *testing.T) { + f := newFixture(t, "", agentFP) + // A well-formed request with a proof that fits no code. + filler := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)) + poll := func() *httptest.ResponseRecorder { + return f.do("POST", "/agent/v1/pair", "", strings.NewReader(`{"v":1,"nonce":"`+filler+`","proof":"`+filler+`"}`)) + } + for i := 0; i < throttle.Threshold; i++ { + if rec := poll(); rec.Code != http.StatusNotFound { + t.Fatalf("poll %d: code = %d, want 404", i+1, rec.Code) + } + } + rec := poll() + if rec.Code != http.StatusTooManyRequests || rec.Header().Get("Retry-After") != "60" { + t.Fatalf("a poll past the threshold: %d, Retry-After %q, want 429 and 60", rec.Code, rec.Header().Get("Retry-After")) + } + if !strings.Contains(f.log.String(), "authentication failed") { + t.Fatalf("the polls were not noted: %s", f.log.String()) + } + // A pairing that starts now is out of the poller's reach: a blocked + // address is turned away before its proof is looked at, so no try is used. + p, _, _ := f.pairing.Start(state.RoleFull, "") + for i := 0; i < pairing.MaxTries; i++ { + if rec := poll(); rec.Code != http.StatusTooManyRequests { + t.Fatalf("blocked poll %d: code = %d, want 429", i+1, rec.Code) + } + } + f.clock.advance(time.Minute) + if rec, _ := f.pair(t, p.Code, agentFP, "x"); rec.Code != http.StatusOK { + t.Fatalf("the pairing did not outlast the polls: code = %d, want 200", rec.Code) + } +} + +func TestARequestThatIsCutOffStillGetsItsAccessLine(t *testing.T) { + var log bytes.Buffer + c := &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} + cutOff := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + noteCaller(r, state.Device{ID: "abcd1234", Name: "Pixel 8"}) + w.WriteHeader(http.StatusPartialContent) + w.Write([]byte("first\n")) + // What the proxy does when a stream ends before the daemon is done. + panic(http.ErrAbortHandler) + }) + h := accessLog(slog.New(slog.NewTextHandler(&log, nil)), c.now, cutOff) + var got any + func() { + defer func() { got = recover() }() + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/containers/abc/logs?follow=1", nil)) + }() + if got != http.ErrAbortHandler { + t.Fatalf("the panic arrived as %v, want http.ErrAbortHandler itself", got) + } + if n := strings.Count(log.String(), "msg=request"); n != 1 { + t.Fatalf("%d access lines for a request that was cut off, want 1: %s", n, log.String()) + } + for _, want := range []string{"device=abcd1234", `name="Pixel 8"`, "method=GET", "path=/containers/abc/logs", "status=206", "bytes=6"} { + if !strings.Contains(log.String(), want) { + t.Errorf("log line lacks %s: %s", want, log.String()) + } + } +} + +func TestOnlyTheHealthCheckItselfGoesUnlogged(t *testing.T) { + f := newFixture(t, "", agentFP) + dev, token, _ := f.devices.Add("phone", state.RoleFull) + for _, method := range []string{"GET", "HEAD"} { + if rec := f.do(method, "/healthz", "", nil); rec.Code != http.StatusOK { + t.Fatalf("%s /healthz: code = %d, want 200", method, rec.Code) + } + } + if f.log.Len() != 0 { + t.Fatalf("the health check was logged: %s", f.log.String()) + } + // Another method on that path is not the health check: with a credential + // it goes on to the daemon like any other request. + f.do("POST", "/healthz", token, nil) + line := f.log.String() + for _, want := range []string{"msg=request", "device=" + dev.ID, "method=POST", "path=/healthz"} { + if !strings.Contains(line, want) { + t.Errorf("log line lacks %s: %s", want, line) + } + } +} + +func TestAProofOfTheWrongLengthUsesUpNothing(t *testing.T) { + f := newFixture(t, "", agentFP) + p, _, _ := f.pairing.Start(state.RoleFull, "") + nonce := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, pairing.NonceLen)) + // More of them than a pairing has tries, and than an address may fail. + for i := 0; i < throttle.Threshold; i++ { + for _, n := range []int{31, 33} { + proof := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{2}, n)) + rec := f.do("POST", "/agent/v1/pair", "", strings.NewReader(`{"v":1,"nonce":"`+nonce+`","proof":"`+proof+`"}`)) + if rec.Code != http.StatusBadRequest { + t.Fatalf("a proof of %d bytes: code = %d, want 400", n, rec.Code) + } + } + } + if strings.Contains(f.log.String(), "authentication failed") { + t.Fatalf("a malformed request was noted as a failed attempt: %s", f.log.String()) + } + if rec, _ := f.pair(t, p.Code, agentFP, "x"); rec.Code != http.StatusOK { + t.Fatalf("the pairing did not outlast the malformed proofs: code = %d, want 200", rec.Code) + } +} + +// requiredOptions is the least New accepts: every option it may be left +// without is left out. +func requiredOptions(t *testing.T) Options { + t.Helper() + dir, err := state.Open(filepath.Join(t.TempDir(), "data")) + if err != nil { + t.Fatal(err) + } + devices, err := state.LoadDevices(dir, time.Now) + if err != nil { + t.Fatal(err) + } + return Options{ + DockerHost: "tcp://127.0.0.1:1", + Devices: devices, + Pairing: pairing.NewManager(time.Now, rand.Reader), + Limiter: throttle.New(time.Now), + } +} + +func TestNewNamesTheRequiredOptionThatIsMissing(t *testing.T) { + for name, without := range map[string]func(*Options){ + "Devices": func(o *Options) { o.Devices = nil }, + "Pairing": func(o *Options) { o.Pairing = nil }, + "Limiter": func(o *Options) { o.Limiter = nil }, + } { + o := requiredOptions(t) + without(&o) + h, err := New(o) + if err == nil || h != nil { + t.Errorf("New without %s built a handler", name) + continue + } + if !strings.Contains(err.Error(), name) { + t.Errorf("New without %s: the error does not name it: %v", name, err) + } + } + // With several missing, the first one is named. + if _, err := New(Options{DockerHost: "tcp://127.0.0.1:1"}); err == nil || !strings.Contains(err.Error(), "Devices") { + t.Errorf("New with nothing but a Docker host: error = %v, want one that names Devices", err) + } +} + +func TestAHandlerWorksWithTheRequiredOptionsAlone(t *testing.T) { + o := requiredOptions(t) + h, err := New(o) + if err != nil { + t.Fatalf("New with the required options alone: %v", err) + } + do := func(method, path, token, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec + } + dev, token, _ := o.Devices.Add("phone", state.RoleReadOnly) + if rec := do("GET", "/agent/v1/whoami", token, ""); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), dev.ID) { + t.Fatalf("whoami: %d %s", rec.Code, rec.Body.String()) + } + if rec := do("GET", "/agent/v1/whoami", "wrong", ""); rec.Code != http.StatusUnauthorized { + t.Fatalf("a wrong token: code = %d, want 401", rec.Code) + } + filler := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)) + if rec := do("POST", "/agent/v1/pair", "", `{"v":1,"nonce":"`+filler+`","proof":"`+filler+`"}`); rec.Code != http.StatusNotFound { + t.Fatalf("pairing with nothing pending: code = %d, want 404", rec.Code) + } +} + +func TestTheFailureWarningNamesTheAddressItself(t *testing.T) { + f := newFixture(t, legacy, agentFP) + fail := func(remoteAddr string) { + req := httptest.NewRequest("GET", "/containers/json", nil) + req.RemoteAddr = remoteAddr + req.Header.Set("Authorization", "Bearer wrong") + f.handler.ServeHTTP(httptest.NewRecorder(), req) + } + fail("[2001:db8:1:2::7]:50000") + if !strings.Contains(f.log.String(), "from=2001:db8:1:2::7\n") { + t.Fatalf("the warning does not name the address: %s", f.log.String()) + } + // Failures are counted per network, and so is the limit on the warning: + // a neighbour in the same network gets no line of its own within the second. + fail("[2001:db8:1:2::8]:50000") + if n := strings.Count(f.log.String(), "authentication failed"); n != 1 { + t.Fatalf("%d failure lines within a second for one network, want 1", n) + } + f.clock.advance(time.Second) + fail("[2001:db8:1:2::8]:50000") + if !strings.Contains(f.log.String(), "from=2001:db8:1:2::8\n") { + t.Fatalf("the second warning does not name its address: %s", f.log.String()) + } + if strings.Contains(f.log.String(), "/64") { + t.Fatalf("a warning names a network instead of an address: %s", f.log.String()) + } +} diff --git a/agent/internal/server/middleware.go b/agent/internal/server/middleware.go index 6f7a8d5..71fb8f2 100644 --- a/agent/internal/server/middleware.go +++ b/agent/internal/server/middleware.go @@ -90,30 +90,40 @@ func noteCaller(r *http.Request, dev state.Device) { } } -// accessLog writes one line per finished request. It never logs a query -// string, a header or a body. The health check is not logged. +// accessLog writes one line per request, when it is over. It never logs a +// query string, a header or a body. The health check is not logged: that is +// GET or HEAD on /healthz, and nothing else on that path. func accessLog(log *slog.Logger, now func() time.Time, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/healthz" { + if r.URL.Path == "/healthz" && (r.Method == http.MethodGet || r.Method == http.MethodHead) { next.ServeHTTP(w, r) return } start := now() info := &requestInfo{} sw := &statusWriter{ResponseWriter: w} + // The line is written however the handler ends. The proxy ends a stream + // that was cut off with a panic (http.ErrAbortHandler); that panic goes + // on after the line, with the value it came with. + defer func() { + panicked := recover() + info.mu.Lock() + dev := info.device + info.mu.Unlock() + log.Info("request", + "device", dev.ID, + "name", dev.Name, + "method", r.Method, + "path", r.URL.Path, + "status", sw.code(), + "bytes", sw.bytes, + "ms", now().Sub(start).Milliseconds(), + ) + if panicked != nil { + panic(panicked) + } + }() next.ServeHTTP(sw, r.WithContext(context.WithValue(r.Context(), infoKey{}, info))) - info.mu.Lock() - dev := info.device - info.mu.Unlock() - log.Info("request", - "device", dev.ID, - "name", dev.Name, - "method", r.Method, - "path", r.URL.Path, - "status", sw.code(), - "bytes", sw.bytes, - "ms", now().Sub(start).Milliseconds(), - ) }) } @@ -175,7 +185,8 @@ func (w *statusWriter) code() int { } // failureLog reports failed authentications, at most one line a second per -// source address. +// source as the throttle counts it: an address, or a network for IPv6. The +// line names the address itself. type failureLog struct { log *slog.Logger now func() time.Time @@ -204,5 +215,14 @@ func (f *failureLog) note(remoteAddr string) { } f.last[key] = now f.mu.Unlock() - f.log.Warn("authentication failed", "from", key) + f.log.Warn("authentication failed", "from", remoteHost(remoteAddr)) +} + +// remoteHost is the address a request came from, without its port. +func remoteHost(remoteAddr string) string { + host, _, err := net.SplitHostPort(remoteAddr) + if err != nil { + return remoteAddr + } + return host } diff --git a/agent/internal/server/pair.go b/agent/internal/server/pair.go index fa69f64..54cc6a0 100644 --- a/agent/internal/server/pair.go +++ b/agent/internal/server/pair.go @@ -1,6 +1,7 @@ package server import ( + "crypto/sha256" "encoding/base64" "encoding/json" "errors" @@ -20,6 +21,8 @@ const ( maxPairBody = 4 << 10 // pairBodyTimeout is how long a pairing request may take to arrive. pairBodyTimeout = 10 * time.Second + // proofLen is the length of a proof: one HMAC-SHA256 output. + proofLen = sha256.Size ) type pairRequest struct { @@ -75,13 +78,20 @@ func (s *server) handlePair(w http.ResponseWriter, r *http.Request) { } nonce, errN := base64.RawURLEncoding.DecodeString(req.Nonce) proof, errP := base64.RawURLEncoding.DecodeString(req.Proof) - if errN != nil || errP != nil || len(nonce) != pairing.NonceLen || len(proof) == 0 { + // A nonce or a proof of another length cannot be right. It is refused as + // malformed here, so it neither uses up a try nor counts as a failure. + if errN != nil || errP != nil || len(nonce) != pairing.NonceLen || len(proof) != proofLen { auth.WriteError(w, http.StatusBadRequest, "malformed pairing request") return } got, err := s.o.Pairing.Redeem(s.o.Fingerprint, nonce, proof, req.Name, s.o.Devices.Add) switch { case errors.Is(err, pairing.ErrNone): + // This answer costs the agent nothing, so it has to cost the asker: + // otherwise a stranger could ask without end, see the moment a pairing + // starts and use up its tries. + s.o.Limiter.Fail(key) + s.failures.note(r.RemoteAddr) auth.WriteError(w, http.StatusNotFound, "No pairing is in progress on this agent") return case errors.Is(err, pairing.ErrWrongProof): From 108dcb5febeae23b3d21da16d283630aab299bbf Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 06:18:14 +0530 Subject: [PATCH 18/32] feat(agent): admin socket, advertised address and terminal QR codes --- agent/go.mod | 2 + agent/go.sum | 2 + agent/internal/admin/admin.go | 283 +++++++++++++++++ agent/internal/admin/admin_test.go | 397 ++++++++++++++++++++++++ agent/internal/admin/client.go | 127 ++++++++ agent/internal/config/advertise.go | 83 +++++ agent/internal/config/advertise_test.go | 72 +++++ agent/internal/qr/qr.go | 58 ++++ agent/internal/qr/qr_test.go | 88 ++++++ 9 files changed, 1112 insertions(+) create mode 100644 agent/internal/admin/admin.go create mode 100644 agent/internal/admin/admin_test.go create mode 100644 agent/internal/admin/client.go create mode 100644 agent/internal/config/advertise.go create mode 100644 agent/internal/config/advertise_test.go create mode 100644 agent/internal/qr/qr.go create mode 100644 agent/internal/qr/qr_test.go diff --git a/agent/go.mod b/agent/go.mod index 027be07..9ff4e24 100644 --- a/agent/go.mod +++ b/agent/go.mod @@ -3,3 +3,5 @@ module github.com/retransmit/docker-mobile/agent go 1.24 require github.com/gorilla/websocket v1.5.3 + +require rsc.io/qr v0.2.0 diff --git a/agent/go.sum b/agent/go.sum index 25a9fc4..b65ef37 100644 --- a/agent/go.sum +++ b/agent/go.sum @@ -1,2 +1,4 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +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/agent/internal/admin/admin.go b/agent/internal/admin/admin.go new file mode 100644 index 0000000..8a4ab63 --- /dev/null +++ b/agent/internal/admin/admin.go @@ -0,0 +1,283 @@ +// Package admin is how the agent's own command line talks to the running +// agent: a small HTTP API on a unix socket inside the state folder. Whoever +// can open that socket can already run commands on the server; nothing here +// is reachable over the network. +package admin + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "os" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/conns" + "github.com/retransmit/docker-mobile/agent/internal/pairing" + "github.com/retransmit/docker-mobile/agent/internal/state" +) + +const socketName = "admin.sock" + +// PairRequest starts a pairing. +type PairRequest struct { + // Role is "full" or "readonly"; empty means full. + Role string `json:"role"` + // Name fixes the device name; empty lets the phone propose one. + Name string `json:"name"` + // Host overrides the advertised address for this pairing. + Host string `json:"host"` +} + +// Event names. A pairing stream is one "started" event followed by exactly +// one of the others. +const ( + EventStarted = "started" +) + +// Event is one line of a pairing stream. +type Event struct { + Event string `json:"event"` + // Set on "started". + Code string `json:"code,omitempty"` // XXXX-XXXX-XXXX + Link string `json:"link,omitempty"` // dockermobile://pair?... + Fingerprint string `json:"fingerprint,omitempty"` // SHA256:..., empty without a certificate + Address string `json:"address,omitempty"` // where the code says the agent is, empty if unknown + Role string `json:"role,omitempty"` + ExpiresIn int `json:"expiresInSeconds,omitempty"` + // Set on "paired". + Device *DeviceInfo `json:"device,omitempty"` + // Set on "failed". + Error string `json:"error,omitempty"` +} + +// DeviceInfo is a device as the command line shows it. It never carries the +// token hash. +type DeviceInfo struct { + ID string `json:"id"` + Name string `json:"name"` + Role string `json:"role"` + CreatedAt time.Time `json:"createdAt"` + LastSeenAt time.Time `json:"lastSeenAt"` +} + +func infoOf(d state.Device) DeviceInfo { + return DeviceInfo{ID: d.ID, Name: d.Name, Role: string(d.Role), CreatedAt: d.CreatedAt, LastSeenAt: d.LastSeenAt} +} + +type devicesResponse struct { + Devices []DeviceInfo `json:"devices"` +} + +type revokeResponse struct { + Device DeviceInfo `json:"device"` + Closed int `json:"closed"` +} + +type errorResponse struct { + Message string `json:"message"` +} + +// Server serves the admin API. Pairing, Devices and Conns are required. +type Server struct { + Pairing *pairing.Manager + Devices *state.Devices + Conns *conns.Registry + // Advertise is where phones reach the agent. + Advertise config.Advertise + // Fingerprint is the pinned form (base64url); empty without a certificate. + Fingerprint string + // FingerprintDisplay is the form shown to people. + FingerprintDisplay string + // AgentName is how the agent calls itself in pairing codes. + AgentName string + Log *slog.Logger + // Now and After are the clock; nil means time.Now and time.After. + Now func() time.Time + After func(time.Duration) <-chan time.Time +} + +// Listen opens the admin socket in dir, replacing a stale one. It refuses +// when another agent is already serving that folder. +func Listen(dir *state.Dir) (net.Listener, error) { + path := dir.Path(socketName) + if _, err := os.Stat(path); err == nil { + if c, err := net.DialTimeout("unix", path, time.Second); err == nil { + c.Close() + return nil, errors.New("another agent is already running on this state folder") + } + if err := os.Remove(path); err != nil { + return nil, fmt.Errorf("remove stale admin socket: %w", err) + } + } + ln, err := net.Listen("unix", path) + if err != nil { + return nil, fmt.Errorf("admin socket: %w", err) + } + if err := os.Chmod(path, 0o600); err != nil { + ln.Close() + return nil, fmt.Errorf("admin socket: %w", err) + } + return ln, nil +} + +// Handler returns the admin API. +func (s *Server) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST /pair", s.handlePair) + mux.HandleFunc("GET /devices", s.handleDevices) + mux.HandleFunc("DELETE /devices/{id}", s.handleRevoke) + return mux +} + +func (s *Server) now() time.Time { + if s.Now != nil { + return s.Now() + } + return time.Now() +} + +func (s *Server) after(d time.Duration) <-chan time.Time { + if s.After != nil { + return s.After(d) + } + return time.After(d) +} + +// logf writes one line to the log, if there is one. It is never given a +// pairing code or a token. +func (s *Server) logf(msg string, args ...any) { + if s.Log != nil { + s.Log.Info(msg, args...) + } +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + json.NewEncoder(w).Encode(v) +} + +func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) { + var req PairRequest + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4<<10)) + if err != nil || (len(body) > 0 && json.Unmarshal(body, &req) != nil) { + writeJSON(w, http.StatusBadRequest, errorResponse{"malformed request"}) + return + } + role := state.Role(req.Role) + if req.Role == "" { + role = state.RoleFull + } + if !role.Valid() { + writeJSON(w, http.StatusBadRequest, errorResponse{fmt.Sprintf("unknown role %q", req.Role)}) + return + } + adv, err := s.Advertise.WithHost(req.Host) + if err != nil { + writeJSON(w, http.StatusBadRequest, errorResponse{err.Error()}) + return + } + p, done, err := s.Pairing.Start(role, req.Name) + if err != nil { + writeJSON(w, http.StatusInternalServerError, errorResponse{err.Error()}) + return + } + link := pairing.Link(pairing.LinkParams{ + Host: adv.Host, + Port: portFor(adv), + Fingerprint: s.Fingerprint, + Scheme: adv.Scheme, + Code: p.Code, + Name: s.AgentName, + }) + w.Header().Set("Content-Type", "application/x-ndjson") + w.WriteHeader(http.StatusOK) + enc := json.NewEncoder(w) + send := func(e Event) { + enc.Encode(e) + if f, ok := w.(http.Flusher); ok { + f.Flush() + } + } + send(Event{ + Event: EventStarted, + Code: pairing.Format(p.Code), + Link: link, + Fingerprint: s.FingerprintDisplay, + Address: addressOf(adv), + Role: string(p.Role), + ExpiresIn: int(p.ExpiresAt.Sub(s.now()).Seconds()), + }) + + s.logf("pairing started", "role", string(p.Role)) + + var result pairing.Result + select { + case result = <-done: + case <-s.after(p.ExpiresAt.Sub(s.now())): + s.Pairing.Expire(p.ID) + result = <-done + case <-r.Context().Done(): + // The command line went away: the code must not stay usable. + s.Pairing.Cancel(p.ID) + s.logf("pairing ended", "outcome", string(pairing.Cancelled)) + return + } + s.logf("pairing ended", "outcome", string(result.Outcome)) + e := Event{Event: string(result.Outcome), Error: result.Err} + if result.Outcome == pairing.Paired { + info := infoOf(result.Device) + e.Device = &info + } + send(e) +} + +// portFor leaves the port out of a link when there is no host to go with it. +func portFor(a config.Advertise) string { + if a.Host == "" { + return "" + } + return a.Port +} + +// addressOf is the advertised address as a person reads it. +func addressOf(a config.Advertise) string { + if a.Host == "" { + return "" + } + hostPort := net.JoinHostPort(a.Host, a.Port) + if a.Scheme != "" { + return a.Scheme + "://" + hostPort + } + return hostPort +} + +func (s *Server) handleDevices(w http.ResponseWriter, _ *http.Request) { + list := s.Devices.List() + out := devicesResponse{Devices: make([]DeviceInfo, 0, len(list))} + for _, d := range list { + out.Devices = append(out.Devices, infoOf(d)) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) handleRevoke(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + dev, found, err := s.Devices.Remove(id) + if err != nil { + writeJSON(w, http.StatusInternalServerError, errorResponse{err.Error()}) + return + } + if !found { + writeJSON(w, http.StatusNotFound, errorResponse{fmt.Sprintf("no device with id %q", id)}) + return + } + closed := s.Conns.CloseDevice(id) + s.logf("device revoked", "device", dev.ID, "name", dev.Name, "closed", closed) + writeJSON(w, http.StatusOK, revokeResponse{Device: infoOf(dev), Closed: closed}) +} diff --git a/agent/internal/admin/admin_test.go b/agent/internal/admin/admin_test.go new file mode 100644 index 0000000..8e8fd9b --- /dev/null +++ b/agent/internal/admin/admin_test.go @@ -0,0 +1,397 @@ +package admin + +import ( + "bytes" + "context" + "crypto/rand" + "errors" + "log/slog" + "net/http" + "os" + "runtime" + "strings" + "sync" + "testing" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/conns" + "github.com/retransmit/docker-mobile/agent/internal/pairing" + "github.com/retransmit/docker-mobile/agent/internal/state" +) + +// shortDir returns a state folder with a short path: a unix socket path may +// not exceed about a hundred bytes, and t.TempDir can be longer than that. +func shortDir(t *testing.T) *state.Dir { + t.Helper() + path, err := os.MkdirTemp("", "dma") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(path) }) + dir, err := state.Open(path) + if err != nil { + t.Fatal(err) + } + return dir +} + +type fixture struct { + dir *state.Dir + server *Server + client *Client + devices *state.Devices + pairing *pairing.Manager + conns *conns.Registry + expire chan time.Time + log *lockedBuffer +} + +// lockedBuffer is a log sink the test can read while the server writes. +type lockedBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (l *lockedBuffer) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *lockedBuffer) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} + +var agentFP = bytes.Repeat([]byte{7}, 32) + +// start serves the admin API on a socket in a fresh folder. configure runs +// before the server starts: its fields must not change afterwards. +func start(t *testing.T, configure ...func(*Server)) *fixture { + t.Helper() + dir := shortDir(t) + devices, err := state.LoadDevices(dir, time.Now) + if err != nil { + t.Fatal(err) + } + f := &fixture{ + dir: dir, + devices: devices, + pairing: pairing.NewManager(time.Now, rand.Reader), + conns: conns.New(), + expire: make(chan time.Time), + log: &lockedBuffer{}, + } + f.server = &Server{ + Pairing: f.pairing, + Devices: devices, + Conns: f.conns, + Advertise: config.Advertise{Host: "my-server.lan", Port: "8443"}, + Fingerprint: "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", + FingerprintDisplay: "SHA256:BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", + AgentName: "home lab", + Log: slog.New(slog.NewTextHandler(f.log, nil)), + After: func(time.Duration) <-chan time.Time { return f.expire }, + } + for _, c := range configure { + c(f.server) + } + ln, err := Listen(dir) + if err != nil { + t.Fatalf("Listen: %v", err) + } + srv := &http.Server{Handler: f.server.Handler()} + go srv.Serve(ln) + t.Cleanup(func() { srv.Close() }) + f.client = NewClient(dir.Path("")) + return f +} + +// pairAsync runs Pair in the background and returns its events and its error. +func (f *fixture) pairAsync(ctx context.Context, req PairRequest) (<-chan Event, <-chan error) { + events := make(chan Event, 4) + done := make(chan error, 1) + go func() { + done <- f.client.Pair(ctx, req, func(e Event) { events <- e }) + }() + return events, done +} + +func next(t *testing.T, events <-chan Event) Event { + t.Helper() + select { + case e := <-events: + return e + case <-time.After(3 * time.Second): + t.Fatal("no event arrived") + return Event{} + } +} + +func finished(t *testing.T, done <-chan error) error { + t.Helper() + select { + case err := <-done: + return err + case <-time.After(3 * time.Second): + t.Fatal("Pair did not return") + return nil + } +} + +// redeem plays the phone: it turns the code from a started event into a +// correct proof. +func (f *fixture) redeem(t *testing.T, formatted, name string) error { + t.Helper() + code, ok := pairing.Normalize(formatted) + if !ok { + t.Fatalf("the started event carries no valid code: %q", formatted) + } + nonce := bytes.Repeat([]byte{4}, pairing.NonceLen) + _, err := f.pairing.Redeem(agentFP, nonce, pairing.PhoneProof(code, agentFP, nonce), name, f.devices.Add) + return err +} + +func TestPairStreamsTheCodeAndThenThePairedDevice(t *testing.T) { + f := start(t) + events, done := f.pairAsync(context.Background(), PairRequest{Role: "readonly"}) + started := next(t, events) + if started.Event != EventStarted || started.Role != "readonly" { + t.Fatalf("started = %+v", started) + } + if len(started.Code) != 14 || strings.Count(started.Code, "-") != 2 { + t.Fatalf("code = %q, want XXXX-XXXX-XXXX", started.Code) + } + code, _ := pairing.Normalize(started.Code) + wantLink := "dockermobile://pair?c=" + code + "&f=BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc&h=my-server.lan&n=home+lab&p=8443&v=1" + if started.Link != wantLink { + t.Fatalf("link =\n %s\nwant\n %s", started.Link, wantLink) + } + if started.Fingerprint != "SHA256:BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc" || started.Address != "my-server.lan:8443" { + t.Fatalf("started = %+v", started) + } + if started.ExpiresIn < 295 || started.ExpiresIn > 300 { + t.Fatalf("expiresIn = %d", started.ExpiresIn) + } + if err := f.redeem(t, started.Code, "Pixel 8"); err != nil { + t.Fatalf("redeem: %v", err) + } + paired := next(t, events) + if paired.Event != "paired" || paired.Device == nil || paired.Device.Name != "Pixel 8" || paired.Device.Role != "readonly" { + t.Fatalf("paired = %+v", paired) + } + if err := finished(t, done); err != nil { + t.Fatalf("Pair: %v", err) + } + log := f.log.String() + if !strings.Contains(log, "pairing started") || !strings.Contains(log, "outcome=paired") { + t.Fatalf("log = %s", log) + } + if strings.Contains(log, code) || strings.Contains(log, started.Code) { + t.Fatal("the pairing code is in the log") + } +} + +func TestPairEndsAsExpiredWhenTheCodeRunsOut(t *testing.T) { + f := start(t) + events, done := f.pairAsync(context.Background(), PairRequest{}) + started := next(t, events) + if started.Role != "full" { + t.Fatalf("the default role = %q, want full", started.Role) + } + f.expire <- time.Now() + if e := next(t, events); e.Event != "expired" { + t.Fatalf("event = %+v", e) + } + if err := finished(t, done); err != nil { + t.Fatalf("Pair: %v", err) + } + if err := f.redeem(t, started.Code, "x"); !errors.Is(err, pairing.ErrNone) { + t.Fatalf("an expired code still pairs: %v", err) + } +} + +func TestLeavingThePairCommandCancelsTheCode(t *testing.T) { + f := start(t) + ctx, cancel := context.WithCancel(context.Background()) + events, done := f.pairAsync(ctx, PairRequest{}) + started := next(t, events) + cancel() + if err := finished(t, done); !errors.Is(err, context.Canceled) { + t.Fatalf("Pair err = %v, want context.Canceled", err) + } + // The agent notices the closed connection a moment later. + deadline := time.Now().Add(3 * time.Second) + for !strings.Contains(f.log.String(), "outcome=cancelled") { + if time.Now().After(deadline) { + t.Fatal("the agent did not cancel the pairing") + } + time.Sleep(5 * time.Millisecond) + } + if err := f.redeem(t, started.Code, "x"); !errors.Is(err, pairing.ErrNone) { + t.Fatalf("the code is still usable after the command left: %v", err) + } + if len(f.devices.List()) != 0 { + t.Fatal("a device was created with a cancelled code") + } +} + +func TestASecondPairReplacesTheFirst(t *testing.T) { + f := start(t) + firstEvents, firstDone := f.pairAsync(context.Background(), PairRequest{}) + next(t, firstEvents) + secondEvents, _ := f.pairAsync(context.Background(), PairRequest{}) + next(t, secondEvents) + if e := next(t, firstEvents); e.Event != "replaced" { + t.Fatalf("event = %+v", e) + } + if err := finished(t, firstDone); err != nil { + t.Fatalf("Pair: %v", err) + } +} + +func TestPairRequestOptions(t *testing.T) { + f := start(t) + events, _ := f.pairAsync(context.Background(), PairRequest{Host: "10.0.0.5:9000", Name: "kitchen"}) + started := next(t, events) + if started.Address != "10.0.0.5:9000" || !strings.Contains(started.Link, "h=10.0.0.5&") || !strings.Contains(started.Link, "p=9000") { + t.Fatalf("started = %+v", started) + } + if err := f.redeem(t, started.Code, "what the phone calls itself"); err != nil { + t.Fatal(err) + } + if e := next(t, events); e.Device == nil || e.Device.Name != "kitchen" { + t.Fatalf("the name given on the command line did not win: %+v", e) + } + + for name, req := range map[string]PairRequest{ + "unknown role": {Role: "admin"}, + "bad host": {Host: "https://x"}, + } { + err := f.client.Pair(context.Background(), req, func(Event) { t.Errorf("%s: an event arrived", name) }) + if err == nil { + t.Errorf("%s was accepted", name) + } + } +} + +func TestPairWithoutAnAdvertisedAddressLeavesItOut(t *testing.T) { + f := start(t, func(s *Server) { s.Advertise = config.Advertise{Port: "8443"} }) + events, _ := f.pairAsync(context.Background(), PairRequest{}) + started := next(t, events) + if started.Address != "" || strings.Contains(started.Link, "h=") || strings.Contains(started.Link, "p=") { + t.Fatalf("started = %+v", started) + } +} + +func TestPairBehindAProxyCarriesASchemeInsteadOfAFingerprint(t *testing.T) { + f := start(t, func(s *Server) { + s.Advertise = config.Advertise{Scheme: "https", Host: "docker.example.com", Port: "443"} + s.Fingerprint, s.FingerprintDisplay = "", "" + }) + events, _ := f.pairAsync(context.Background(), PairRequest{}) + started := next(t, events) + if started.Fingerprint != "" || started.Address != "https://docker.example.com:443" { + t.Fatalf("started = %+v", started) + } + if !strings.Contains(started.Link, "s=https") || strings.Contains(started.Link, "f=") { + t.Fatalf("link = %s", started.Link) + } +} + +func TestDevicesListsWithoutTokenHashes(t *testing.T) { + f := start(t) + a, _, _ := f.devices.Add("a", state.RoleFull) + time.Sleep(2 * time.Millisecond) + b, _, _ := f.devices.Add("b", state.RoleReadOnly) + list, err := f.client.Devices(context.Background()) + if err != nil { + t.Fatalf("Devices: %v", err) + } + if len(list) != 2 || list[0].ID != a.ID || list[1].ID != b.ID || list[1].Role != "readonly" { + t.Fatalf("list = %+v", list) + } + resp, err := f.client.do(context.Background(), http.MethodGet, "/devices", nil) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var raw bytes.Buffer + raw.ReadFrom(resp.Body) + if strings.Contains(strings.ToLower(raw.String()), "hash") || strings.Contains(raw.String(), a.TokenHash) { + t.Fatalf("the answer carries a token hash: %s", raw.String()) + } +} + +func TestRevokeRemovesTheDeviceAndClosesItsRequests(t *testing.T) { + f := start(t) + dev, token, _ := f.devices.Add("phone", state.RoleFull) + ctx, release := f.conns.Track(context.Background(), dev.ID) + defer release() + + got, closed, err := f.client.Revoke(context.Background(), dev.ID) + if err != nil { + t.Fatalf("Revoke: %v", err) + } + if got.ID != dev.ID || closed != 1 { + t.Fatalf("revoked = %+v, closed = %d", got, closed) + } + select { + case <-ctx.Done(): + default: + t.Fatal("the open request of the revoked device was not closed") + } + if _, ok := f.devices.Authenticate(token); ok { + t.Fatal("the revoked token still authenticates") + } + if _, _, err := f.client.Revoke(context.Background(), dev.ID); err == nil || !strings.Contains(err.Error(), "no device") { + t.Fatalf("revoking twice: err = %v", err) + } + if _, _, err := f.client.Revoke(context.Background(), "../devices"); err == nil { + t.Fatal("an id with a path in it was accepted") + } +} + +func TestWithoutARunningAgentTheClientSaysSo(t *testing.T) { + c := NewClient(shortDir(t).Path("")) + if _, err := c.Devices(context.Background()); !errors.Is(err, ErrNotRunning) { + t.Fatalf("err = %v, want ErrNotRunning", err) + } + if err := c.Pair(context.Background(), PairRequest{}, func(Event) {}); !errors.Is(err, ErrNotRunning) { + t.Fatalf("Pair err = %v, want ErrNotRunning", err) + } +} + +func TestListenRefusesASecondAgentAndReplacesAStaleSocket(t *testing.T) { + dir := shortDir(t) + first, err := Listen(dir) + if err != nil { + t.Fatalf("Listen: %v", err) + } + go http.Serve(first, http.NotFoundHandler()) + if _, err := Listen(dir); err == nil || !strings.Contains(err.Error(), "already running") { + t.Fatalf("a second agent on the same folder: err = %v", err) + } + first.Close() + + // A socket file nobody listens on is stale and gets replaced. + if err := os.WriteFile(dir.Path(socketName), nil, 0o600); err != nil { + t.Fatal(err) + } + second, err := Listen(dir) + if err != nil { + t.Fatalf("Listen over a stale socket: %v", err) + } + defer second.Close() + if runtime.GOOS != "windows" { + info, err := os.Stat(dir.Path(socketName)) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("socket mode = %v, want 0600", info.Mode().Perm()) + } + } +} diff --git a/agent/internal/admin/client.go b/agent/internal/admin/client.go new file mode 100644 index 0000000..9b61b89 --- /dev/null +++ b/agent/internal/admin/client.go @@ -0,0 +1,127 @@ +package admin + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "path/filepath" +) + +// ErrNotRunning means nothing answers on the admin socket. +var ErrNotRunning = errors.New("the agent is not running on this state folder") + +// ErrStopped means the agent went away while a pairing was pending. +var ErrStopped = errors.New("the agent stopped before the pairing ended") + +// Client talks to a running agent through its admin socket. +type Client struct { + http *http.Client +} + +// NewClient returns a client for the agent whose state folder is dataDir. +// It does not create the folder. +func NewClient(dataDir string) *Client { + path := filepath.Join(dataDir, socketName) + return &Client{http: &http.Client{Transport: &http.Transport{ + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", path) + }, + }}} +} + +func (c *Client) do(ctx context.Context, method, path string, body any) (*http.Response, error) { + var reader io.Reader + if body != nil { + raw, err := json.Marshal(body) + if err != nil { + return nil, err + } + reader = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, "http://agent"+path, reader) + if err != nil { + return nil, err + } + resp, err := c.http.Do(req) + if err != nil { + var opErr *net.OpError + if errors.As(err, &opErr) && opErr.Op == "dial" { + return nil, ErrNotRunning + } + return nil, err + } + if resp.StatusCode >= 400 { + defer resp.Body.Close() + var e errorResponse + if json.NewDecoder(resp.Body).Decode(&e) == nil && e.Message != "" { + return nil, errors.New(e.Message) + } + return nil, fmt.Errorf("the agent answered %s", resp.Status) + } + return resp, nil +} + +// Pair starts a pairing and calls onEvent for the "started" event and then +// for the one that ends it. It returns when the pairing is over. Cancelling +// ctx cancels the pairing. +func (c *Client) Pair(ctx context.Context, req PairRequest, onEvent func(Event)) error { + resp, err := c.do(ctx, http.MethodPost, "/pair", req) + if err != nil { + return err + } + defer resp.Body.Close() + lines := bufio.NewScanner(resp.Body) + last := "" + for lines.Scan() { + var e Event + if err := json.Unmarshal(lines.Bytes(), &e); err != nil { + return fmt.Errorf("unreadable answer from the agent: %w", err) + } + last = e.Event + onEvent(e) + } + if ctx.Err() != nil { + return ctx.Err() + } + if last == "" || last == EventStarted { + // The stream broke off without an ending event. + return ErrStopped + } + return lines.Err() +} + +// Devices lists the paired devices, oldest first. +func (c *Client) Devices(ctx context.Context) ([]DeviceInfo, error) { + resp, err := c.do(ctx, http.MethodGet, "/devices", nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var out devicesResponse + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + return nil, fmt.Errorf("unreadable answer from the agent: %w", err) + } + return out.Devices, nil +} + +// Revoke removes a device and reports how many of its requests were closed. +func (c *Client) Revoke(ctx context.Context, id string) (DeviceInfo, int, error) { + resp, err := c.do(ctx, http.MethodDelete, "/devices/"+url.PathEscape(id), nil) + if err != nil { + return DeviceInfo{}, 0, err + } + defer resp.Body.Close() + var out revokeResponse + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + return DeviceInfo{}, 0, fmt.Errorf("unreadable answer from the agent: %w", err) + } + return out.Device, out.Closed, nil +} diff --git a/agent/internal/config/advertise.go b/agent/internal/config/advertise.go new file mode 100644 index 0000000..e60e7e6 --- /dev/null +++ b/agent/internal/config/advertise.go @@ -0,0 +1,83 @@ +package config + +import ( + "fmt" + "net" + "net/url" + "strings" +) + +// Advertise is the address pairing codes carry. Every field may be empty. +type Advertise struct { + // Scheme is "https" or "http" in plain-HTTP mode, and empty when the + // agent serves its own pinned certificate. + Scheme string + Host string + Port string +} + +// ParseAdvertise reads an advertised address. +// +// With the agent's own certificate (insecure false) the value is host or +// host:port; the port defaults to the one the agent listens on. +// +// In plain-HTTP mode the value is the URL of the proxy in front, such as +// https://docker.example.com; without a value only the scheme "http" is +// known. +func ParseAdvertise(value string, insecure bool, listenPort string) (Advertise, error) { + value = strings.TrimSpace(value) + if !insecure { + if value == "" { + return Advertise{Port: listenPort}, nil + } + if strings.Contains(value, "://") { + return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q: give host or host:port, without a scheme", value) + } + host, port, err := net.SplitHostPort(value) + if err != nil { + // No port: the whole value is the host (an IPv6 literal may be + // in brackets). + host, port = strings.Trim(value, "[]"), listenPort + } + if host == "" { + return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q has no host", value) + } + return Advertise{Host: host, Port: port}, nil + } + if value == "" { + return Advertise{Scheme: "http", Port: listenPort}, nil + } + u, err := url.Parse(value) + if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Hostname() == "" { + return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q: with --insecure-http give the URL of the proxy in front, such as https://docker.example.com", value) + } + port := u.Port() + if port == "" { + port = "443" + if u.Scheme == "http" { + port = "80" + } + } + return Advertise{Scheme: u.Scheme, Host: u.Hostname(), Port: port}, nil +} + +// WithHost returns a with its host (and port, if given) replaced by an +// address typed on the command line. +func (a Advertise) WithHost(hostPort string) (Advertise, error) { + hostPort = strings.TrimSpace(hostPort) + if hostPort == "" { + return a, nil + } + if strings.Contains(hostPort, "://") { + return Advertise{}, fmt.Errorf("--host %q: give host or host:port, without a scheme", hostPort) + } + host, port, err := net.SplitHostPort(hostPort) + if err != nil { + host, port = strings.Trim(hostPort, "[]"), a.Port + } + if host == "" { + return Advertise{}, fmt.Errorf("--host %q has no host", hostPort) + } + a.Host, a.Port = host, port + return a, nil +} diff --git a/agent/internal/config/advertise_test.go b/agent/internal/config/advertise_test.go new file mode 100644 index 0000000..18c7cdf --- /dev/null +++ b/agent/internal/config/advertise_test.go @@ -0,0 +1,72 @@ +package config + +import "testing" + +func TestParseAdvertisePinned(t *testing.T) { + cases := map[string]Advertise{ + "": {Port: "8443"}, + "my-server.lan": {Host: "my-server.lan", Port: "8443"}, + "my-server.lan:9443": {Host: "my-server.lan", Port: "9443"}, + "192.168.1.20": {Host: "192.168.1.20", Port: "8443"}, + "[fd00::1]:9443": {Host: "fd00::1", Port: "9443"}, + "[fd00::1]": {Host: "fd00::1", Port: "8443"}, + " my-server.lan:1 ": {Host: "my-server.lan", Port: "1"}, + } + for in, want := range cases { + got, err := ParseAdvertise(in, false, "8443") + if err != nil || got != want { + t.Errorf("ParseAdvertise(%q) = %+v, %v, want %+v", in, got, err, want) + } + } + for _, bad := range []string{"https://my-server.lan", ":8443"} { + if _, err := ParseAdvertise(bad, false, "8443"); err == nil { + t.Errorf("ParseAdvertise(%q) was accepted", bad) + } + } +} + +func TestParseAdvertiseBehindAProxy(t *testing.T) { + cases := map[string]Advertise{ + "": {Scheme: "http", Port: "8080"}, + "https://docker.example.com": {Scheme: "https", Host: "docker.example.com", Port: "443"}, + "https://docker.example.com:8443": {Scheme: "https", Host: "docker.example.com", Port: "8443"}, + "http://10.0.0.5": {Scheme: "http", Host: "10.0.0.5", Port: "80"}, + "http://10.0.0.5:8080": {Scheme: "http", Host: "10.0.0.5", Port: "8080"}, + } + for in, want := range cases { + got, err := ParseAdvertise(in, true, "8080") + if err != nil || got != want { + t.Errorf("ParseAdvertise(%q) = %+v, %v, want %+v", in, got, err, want) + } + } + for _, bad := range []string{"docker.example.com", "ftp://docker.example.com", "https://"} { + if _, err := ParseAdvertise(bad, true, "8080"); err == nil { + t.Errorf("ParseAdvertise(%q) was accepted", bad) + } + } +} + +func TestWithHostOverridesTheAdvertisedAddress(t *testing.T) { + base := Advertise{Host: "old", Port: "8443"} + cases := map[string]Advertise{ + "": base, + "new.lan": {Host: "new.lan", Port: "8443"}, + "new.lan:9000": {Host: "new.lan", Port: "9000"}, + "[fd00::2]:9000": {Host: "fd00::2", Port: "9000"}, + } + for in, want := range cases { + got, err := base.WithHost(in) + if err != nil || got != want { + t.Errorf("WithHost(%q) = %+v, %v, want %+v", in, got, err, want) + } + } + proxied := Advertise{Scheme: "https", Host: "docker.example.com", Port: "443"} + if got, _ := proxied.WithHost("other.example.com"); got != (Advertise{Scheme: "https", Host: "other.example.com", Port: "443"}) { + t.Errorf("WithHost on a proxied address = %+v", got) + } + for _, bad := range []string{"https://new.lan", ":9000"} { + if _, err := base.WithHost(bad); err == nil { + t.Errorf("WithHost(%q) was accepted", bad) + } + } +} diff --git a/agent/internal/qr/qr.go b/agent/internal/qr/qr.go new file mode 100644 index 0000000..be4e42d --- /dev/null +++ b/agent/internal/qr/qr.go @@ -0,0 +1,58 @@ +// Package qr draws a QR code in a terminal with half-block characters, two +// rows of modules per line of text. +package qr + +import ( + "fmt" + "io" + "strings" + + rscqr "rsc.io/qr" +) + +// quiet is the blank border, in modules, that scanners need around a code. +const quiet = 4 + +const ( + full = "\u2588" // both halves + upper = "\u2580" // upper half + lower = "\u2584" // lower half +) + +// Render writes text as a QR code to w. A module that must be light is drawn +// with the text colour and a dark one is left blank, which reads as a normal +// code on a dark terminal. invert swaps the two, for a light terminal. +func Render(w io.Writer, text string, invert bool) error { + code, err := rscqr.Encode(text, rscqr.M) + if err != nil { + return fmt.Errorf("encode QR code: %w", err) + } + size := code.Size + 2*quiet + // lit reports whether the module at (x, y), border included, is drawn. + lit := func(x, y int) bool { + if y >= size { + return false + } + dark := x >= quiet && y >= quiet && x < size-quiet && y < size-quiet && code.Black(x-quiet, y-quiet) + return dark == invert + } + var b strings.Builder + for y := 0; y < size; y += 2 { + for x := 0; x < size; x++ { + top, bottom := lit(x, y), lit(x, y+1) + switch { + case top && bottom: + b.WriteString(full) + case top: + b.WriteString(upper) + case bottom: + b.WriteString(lower) + default: + b.WriteByte(' ') + } + } + b.WriteByte('\n') + } + _, err = io.WriteString(w, b.String()) + return err +} diff --git a/agent/internal/qr/qr_test.go b/agent/internal/qr/qr_test.go new file mode 100644 index 0000000..5d89589 --- /dev/null +++ b/agent/internal/qr/qr_test.go @@ -0,0 +1,88 @@ +package qr + +import ( + "bytes" + "strings" + "testing" + + rscqr "rsc.io/qr" +) + +const link = "dockermobile://pair?c=K7QM2XPA9TRC&f=OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI&h=my-server.lan&n=home+lab&p=8443&v=1" + +// decode rebuilds the module grid from the rendered text. +func decode(t *testing.T, out string, invert bool) [][]bool { + t.Helper() + lines := strings.Split(strings.TrimRight(out, "\n"), "\n") + var grid [][]bool + for _, line := range lines { + var top, bottom []bool + for _, r := range line { + var up, down bool + switch string(r) { + case full: + up, down = true, true + case upper: + up = true + case lower: + down = true + case " ": + default: + t.Fatalf("unexpected character %q", r) + } + // A drawn half is a light module unless inverted. + top = append(top, up == invert) + bottom = append(bottom, down == invert) + } + grid = append(grid, top, bottom) + } + return grid +} + +func TestRenderDrawsTheCodeWithItsQuietBorder(t *testing.T) { + for _, invert := range []bool{false, true} { + var buf bytes.Buffer + if err := Render(&buf, link, invert); err != nil { + t.Fatalf("Render: %v", err) + } + code, err := rscqr.Encode(link, rscqr.M) + if err != nil { + t.Fatal(err) + } + grid := decode(t, buf.String(), invert) + size := code.Size + 2*quiet + if len(grid) < size { + t.Fatalf("invert=%v: %d rows, want at least %d", invert, len(grid), size) + } + for y := 0; y < size; y++ { + if len(grid[y]) != size { + t.Fatalf("invert=%v: row %d has %d modules, want %d", invert, y, len(grid[y]), size) + } + for x := 0; x < size; x++ { + inside := x >= quiet && y >= quiet && x < size-quiet && y < size-quiet + want := inside && code.Black(x-quiet, y-quiet) + if grid[y][x] != want { + t.Fatalf("invert=%v: module (%d,%d) dark = %v, want %v", invert, x, y, grid[y][x], want) + } + } + } + } +} + +func TestAPairingLinkFitsAnEightyColumnTerminal(t *testing.T) { + var buf bytes.Buffer + if err := Render(&buf, link, false); err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") { + if n := len([]rune(line)); n > 80 { + t.Fatalf("a line is %d columns wide", n) + } + } +} + +func TestRenderRejectsTextThatDoesNotFit(t *testing.T) { + if err := Render(&bytes.Buffer{}, strings.Repeat("x", 5000), false); err == nil { + t.Fatal("text beyond the capacity of a QR code was accepted") + } +} From d11ffe0a7643a61b3b3548723c42aa8eb0300a10 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 07:05:48 +0530 Subject: [PATCH 19/32] fix(agent): lock the state folder, log how a pairing ended, refuse bad addresses --- agent/internal/admin/admin.go | 111 +++++- agent/internal/admin/admin_test.go | 479 +++++++++++++++++++++++- agent/internal/admin/client.go | 34 +- agent/internal/admin/os_unix.go | 37 ++ agent/internal/admin/os_windows.go | 42 +++ agent/internal/config/advertise.go | 155 +++++++- agent/internal/config/advertise_test.go | 175 ++++++++- 7 files changed, 987 insertions(+), 46 deletions(-) create mode 100644 agent/internal/admin/os_unix.go create mode 100644 agent/internal/admin/os_windows.go diff --git a/agent/internal/admin/admin.go b/agent/internal/admin/admin.go index 8a4ab63..a10a336 100644 --- a/agent/internal/admin/admin.go +++ b/agent/internal/admin/admin.go @@ -9,10 +9,12 @@ import ( "errors" "fmt" "io" + "io/fs" "log/slog" "net" "net/http" "os" + "sync" "time" "github.com/retransmit/docker-mobile/agent/internal/config" @@ -21,7 +23,30 @@ import ( "github.com/retransmit/docker-mobile/agent/internal/state" ) -const socketName = "admin.sock" +const ( + socketName = "admin.sock" + // lockName is the file an agent keeps locked for as long as it serves + // the state folder. + lockName = "agent.lock" + // maxSocketPath is the longest socket path that works everywhere. The + // address of a unix socket holds 104 bytes on macOS and the BSDs and 108 + // on Linux and Windows, the zero byte that ends the path included. + maxSocketPath = 103 +) + +// errLocked means the lock of the state folder is held. +var errLocked = errors.New("locked") + +// checkSocketPath refuses a state folder whose admin socket would have a +// path longer than a socket address can hold. Without it the failure would +// read as "invalid argument" in the agent and as no agent running in the +// command line. +func checkSocketPath(path string) error { + if len(path) > maxSocketPath { + return fmt.Errorf("the state folder path is too long for the admin socket: %s is %d bytes, the limit is %d", path, len(path), maxSocketPath) + } + return nil +} // PairRequest starts a pairing. type PairRequest struct { @@ -101,18 +126,39 @@ type Server struct { After func(time.Duration) <-chan time.Time } -// Listen opens the admin socket in dir, replacing a stale one. It refuses -// when another agent is already serving that folder. +// Listen takes the state folder for this agent and opens the admin socket in +// it. It refuses when another agent is already serving that folder. +// +// What says so is a lock on a file in the folder, held for as long as the +// returned listener is open. The operating system drops the lock when the +// process ends, however it ends, so a lock that is held always means a live +// agent. A socket file found once the lock is taken was left behind by an +// agent that died, and is replaced. Closing the listener removes the socket +// and gives the folder up. func Listen(dir *state.Dir) (net.Listener, error) { - path := dir.Path(socketName) - if _, err := os.Stat(path); err == nil { - if c, err := net.DialTimeout("unix", path, time.Second); err == nil { - c.Close() - return nil, errors.New("another agent is already running on this state folder") - } - if err := os.Remove(path); err != nil { - return nil, fmt.Errorf("remove stale admin socket: %w", err) - } + if err := checkSocketPath(dir.Path(socketName)); err != nil { + return nil, err + } + lock, err := lockFile(dir.Path(lockName)) + if errors.Is(err, errLocked) { + return nil, errors.New("another agent is already running on this state folder") + } + if err != nil { + return nil, fmt.Errorf("lock the state folder: %w", err) + } + ln, err := listenLocked(dir.Path(socketName)) + if err != nil { + lock.Close() + return nil, err + } + return &lockedListener{Listener: ln, lock: lock}, nil +} + +// listenLocked opens the admin socket at path, in place of whatever is +// there. The caller holds the lock of the folder. +func listenLocked(path string) (net.Listener, error) { + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, fmt.Errorf("remove stale admin socket: %w", err) } ln, err := net.Listen("unix", path) if err != nil { @@ -125,6 +171,29 @@ func Listen(dir *state.Dir) (net.Listener, error) { return ln, nil } +// lockedListener is the admin socket together with the lock of its folder. +type lockedListener struct { + net.Listener + lock *os.File + + once sync.Once + err error +} + +// Close closes the socket and then gives the folder up. Calling it again +// does nothing and returns what the first call returned. +func (l *lockedListener) Close() error { + l.once.Do(func() { + // The socket goes first. Closing it removes whatever is at its path, + // and once the lock is free that may be the socket of the next agent. + l.err = l.Listener.Close() + if err := l.lock.Close(); err != nil && l.err == nil { + l.err = fmt.Errorf("release the state folder: %w", err) + } + }) + return l.err +} + // Handler returns the admin API. func (s *Server) Handler() http.Handler { mux := http.NewServeMux() @@ -217,18 +286,30 @@ func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) { s.logf("pairing started", "role", string(p.Role)) var result pairing.Result + left := false select { case result = <-done: case <-s.after(p.ExpiresAt.Sub(s.now())): s.Pairing.Expire(p.ID) result = <-done case <-r.Context().Done(): - // The command line went away: the code must not stay usable. + // The command line went away: the code must not stay usable. The + // pairing may have ended a moment before, even with a device stored, + // and Cancel then changes nothing. So the result is read, not assumed. s.Pairing.Cancel(p.ID) - s.logf("pairing ended", "outcome", string(pairing.Cancelled)) + result = <-done + left = true + } + if result.Outcome == pairing.Paired { + s.logf("pairing ended", "outcome", string(result.Outcome), "device", result.Device.ID, "name", result.Device.Name) + } else { + s.logf("pairing ended", "outcome", string(result.Outcome)) + } + if left { + // No ending event: the request is over, so the stream just breaks + // off after "started". return } - s.logf("pairing ended", "outcome", string(result.Outcome)) e := Event{Event: string(result.Outcome), Error: result.Err} if result.Outcome == pairing.Paired { info := infoOf(result.Device) diff --git a/agent/internal/admin/admin_test.go b/agent/internal/admin/admin_test.go index 8e8fd9b..52053ed 100644 --- a/agent/internal/admin/admin_test.go +++ b/agent/internal/admin/admin_test.go @@ -4,13 +4,20 @@ import ( "bytes" "context" "crypto/rand" + "encoding/json" "errors" + "io/fs" "log/slog" + "net" "net/http" + "net/http/httptest" "os" + "path/filepath" "runtime" + "strconv" "strings" "sync" + "syscall" "testing" "time" @@ -45,6 +52,31 @@ type fixture struct { conns *conns.Registry expire chan time.Time log *lockedBuffer + + mu sync.Mutex + armed []time.Duration // what the expiry timer was armed with, in order +} + +// timers returns what the server has armed its expiry timer with so far. +func (f *fixture) timers() []time.Duration { + f.mu.Lock() + defer f.mu.Unlock() + return append([]time.Duration(nil), f.armed...) +} + +// steppingClock moves on by a second every time it is read, so that two +// things made one after the other never carry the same time, however coarse +// the clock of the machine is. +type steppingClock struct { + mu sync.Mutex + t time.Time +} + +func (c *steppingClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(time.Second) + return c.t } // lockedBuffer is a log sink the test can read while the server writes. @@ -70,9 +102,15 @@ var agentFP = bytes.Repeat([]byte{7}, 32) // start serves the admin API on a socket in a fresh folder. configure runs // before the server starts: its fields must not change afterwards. func start(t *testing.T, configure ...func(*Server)) *fixture { + t.Helper() + return startAt(t, time.Now, configure...) +} + +// startAt is start with the clock the device list reads. +func startAt(t *testing.T, now func() time.Time, configure ...func(*Server)) *fixture { t.Helper() dir := shortDir(t) - devices, err := state.LoadDevices(dir, time.Now) + devices, err := state.LoadDevices(dir, now) if err != nil { t.Fatal(err) } @@ -93,7 +131,12 @@ func start(t *testing.T, configure ...func(*Server)) *fixture { FingerprintDisplay: "SHA256:BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", AgentName: "home lab", Log: slog.New(slog.NewTextHandler(f.log, nil)), - After: func(time.Duration) <-chan time.Time { return f.expire }, + After: func(d time.Duration) <-chan time.Time { + f.mu.Lock() + f.armed = append(f.armed, d) + f.mu.Unlock() + return f.expire + }, } for _, c := range configure { c(f.server) @@ -201,7 +244,11 @@ func TestPairEndsAsExpiredWhenTheCodeRunsOut(t *testing.T) { if started.Role != "full" { t.Fatalf("the default role = %q, want full", started.Role) } + // The handler takes this only once it waits, so its timer is armed by now. f.expire <- time.Now() + if armed := f.timers(); len(armed) != 1 || armed[0] > pairing.Lifetime || armed[0] < pairing.Lifetime-5*time.Second { + t.Fatalf("the expiry timer was armed with %v, want once, with what is left of the %v a code lives", armed, pairing.Lifetime) + } if e := next(t, events); e.Event != "expired" { t.Fatalf("event = %+v", e) } @@ -302,9 +349,11 @@ func TestPairBehindAProxyCarriesASchemeInsteadOfAFingerprint(t *testing.T) { } func TestDevicesListsWithoutTokenHashes(t *testing.T) { - f := start(t) + // The list is ordered by when a device was paired, so the two get times + // that differ whatever the clock of the machine does. + clock := &steppingClock{t: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)} + f := startAt(t, clock.Now) a, _, _ := f.devices.Add("a", state.RoleFull) - time.Sleep(2 * time.Millisecond) b, _, _ := f.devices.Add("b", state.RoleReadOnly) list, err := f.client.Devices(context.Background()) if err != nil { @@ -362,6 +411,170 @@ func TestWithoutARunningAgentTheClientSaysSo(t *testing.T) { if err := c.Pair(context.Background(), PairRequest{}, func(Event) {}); !errors.Is(err, ErrNotRunning) { t.Fatalf("Pair err = %v, want ErrNotRunning", err) } + + // A state folder that was never created. + missing := filepath.Join(shortDir(t).Path(""), "missing") + if _, err := NewClient(missing).Devices(context.Background()); !errors.Is(err, ErrNotRunning) { + t.Fatalf("without the folder: err = %v, want ErrNotRunning", err) + } + + // A socket that an agent left behind when it died: nobody listens on it. + dir := shortDir(t) + dead, err := net.Listen("unix", dir.Path(socketName)) + if err != nil { + t.Fatal(err) + } + dead.(*net.UnixListener).SetUnlinkOnClose(false) + dead.Close() + if _, err := NewClient(dir.Path("")).Devices(context.Background()); !errors.Is(err, ErrNotRunning) { + t.Fatalf("with a socket nobody listens on: err = %v, want ErrNotRunning", err) + } +} + +func TestTheClientSaysWhyItCouldNotReachTheAgent(t *testing.T) { + // A file stands in for the socket, so that the cause of the failed + // connection is all that differs between the cases. + path := shortDir(t).Path(socketName) + if err := os.WriteFile(path, nil, 0o600); err != nil { + t.Fatal(err) + } + failed := func(cause syscall.Errno) error { + return dialFailure(path, &net.OpError{Op: "dial", Net: "unix", Err: os.NewSyscallError("connect", cause)}) + } + + denied := failed(syscall.EACCES) + if !errors.Is(denied, ErrNoAccess) || errors.Is(denied, ErrNotRunning) { + t.Fatalf("permission denied: err = %v, want ErrNoAccess", denied) + } + if !strings.Contains(denied.Error(), "the user the agent runs as") { + t.Fatalf("permission denied: the error does not say what to do: %v", denied) + } + + other := failed(syscall.EMFILE) + if errors.Is(other, ErrNotRunning) || errors.Is(other, ErrNoAccess) { + t.Fatalf("another failure was taken for one of the known ones: %v", other) + } + if !strings.Contains(other.Error(), syscall.EMFILE.Error()) { + t.Fatalf("another failure lost its cause: %v", other) + } +} + +func TestTheClientSaysWhenTheStateFolderBelongsToAnotherUser(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs file modes, and a user they hold for") + } + f := start(t) + // What a user other than the agent's finds: a folder that may not be + // entered, with a running agent behind it. + folder := f.dir.Path("") + if err := os.Chmod(folder, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(folder, 0o700) }) + _, err := f.client.Devices(context.Background()) + if !errors.Is(err, ErrNoAccess) || errors.Is(err, ErrNotRunning) { + t.Fatalf("Devices err = %v, want ErrNoAccess", err) + } + err = f.client.Pair(context.Background(), PairRequest{}, func(Event) {}) + if !errors.Is(err, ErrNoAccess) { + t.Fatalf("Pair err = %v, want ErrNoAccess", err) + } +} + +func TestAStateFolderPathTooLongForTheSocketIsAClearError(t *testing.T) { + if err := checkSocketPath(strings.Repeat("x", maxSocketPath)); err != nil { + t.Fatalf("a socket path of exactly %d bytes: %v", maxSocketPath, err) + } + if err := checkSocketPath(strings.Repeat("x", maxSocketPath+1)); err == nil { + t.Fatalf("a socket path of %d bytes was accepted", maxSocketPath+1) + } + + dir, err := state.Open(filepath.Join(shortDir(t).Path(""), strings.Repeat("x", 100))) + if err != nil { + t.Fatal(err) + } + length := strconv.Itoa(len(dir.Path(socketName))) + check := func(what string, err error) { + t.Helper() + if err == nil { + t.Errorf("%s: no error for a socket path of %s bytes", what, length) + return + } + for _, want := range []string{"too long", length, strconv.Itoa(maxSocketPath)} { + if !strings.Contains(err.Error(), want) { + t.Errorf("%s: the error does not say %q: %v", what, want, err) + } + } + if errors.Is(err, ErrNotRunning) { + t.Errorf("%s: a path that is too long was reported as no agent running: %v", what, err) + } + } + ln, err := Listen(dir) + if err == nil { + ln.Close() + } + check("Listen", err) + if _, err := os.Stat(dir.Path(lockName)); !errors.Is(err, fs.ErrNotExist) { + t.Errorf("Listen took the folder before it refused the path: %v", err) + } + _, err = NewClient(dir.Path("")).Devices(context.Background()) + check("Devices", err) + check("Pair", NewClient(dir.Path("")).Pair(context.Background(), PairRequest{}, func(Event) {})) +} + +func TestAStateFolderPathOfTheLongestLengthWorks(t *testing.T) { + base := shortDir(t).Path("") + // base, a separator, the folder, a separator and the socket's name. + pad := maxSocketPath - len(base) - len(socketName) - 2 + if pad < 1 { + t.Skipf("the temporary folder %s is too long to build a path of %d bytes in", base, maxSocketPath) + } + dir, err := state.Open(filepath.Join(base, strings.Repeat("x", pad))) + if err != nil { + t.Fatal(err) + } + if n := len(dir.Path(socketName)); n != maxSocketPath { + t.Fatalf("the socket path is %d bytes, want %d", n, maxSocketPath) + } + ln, err := Listen(dir) + if err != nil { + t.Fatalf("Listen: %v", err) + } + serve(t, ln) + if err := ask(dir); err != nil { + t.Fatalf("the agent does not answer: %v", err) + } +} + +// serve answers every request on ln until the test ends. +func serve(t *testing.T, ln net.Listener) { + t.Helper() + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + })} + go srv.Serve(ln) + t.Cleanup(func() { srv.Close() }) +} + +// ask sends one request to whoever serves the admin socket of dir. +func ask(dir *state.Dir) error { + c := NewClient(dir.Path("")) + defer c.http.CloseIdleConnections() + resp, err := c.do(context.Background(), http.MethodGet, "/", nil) + if err != nil { + return err + } + return resp.Body.Close() +} + +// refused reports whether Listen turned a second agent away. A listener that +// was handed out after all is closed, so that it cannot hold the folder. +func refused(ln net.Listener, err error) bool { + if err == nil { + ln.Close() + return false + } + return strings.Contains(err.Error(), "already running") } func TestListenRefusesASecondAgentAndReplacesAStaleSocket(t *testing.T) { @@ -370,21 +583,45 @@ func TestListenRefusesASecondAgentAndReplacesAStaleSocket(t *testing.T) { if err != nil { t.Fatalf("Listen: %v", err) } - go http.Serve(first, http.NotFoundHandler()) - if _, err := Listen(dir); err == nil || !strings.Contains(err.Error(), "already running") { + serve(t, first) + if err := ask(dir); err != nil { + t.Fatalf("the first agent does not answer: %v", err) + } + if ln, err := Listen(dir); !refused(ln, err) { t.Fatalf("a second agent on the same folder: err = %v", err) } - first.Close() + if err := ask(dir); err != nil { + t.Fatalf("the first agent stopped answering once a second one was refused: %v", err) + } + // The folder stays taken when the socket file is gone: what refuses a + // second agent is not whether a socket can be found and reached. + if err := os.Remove(dir.Path(socketName)); err != nil { + t.Fatal(err) + } + if ln, err := Listen(dir); !refused(ln, err) { + t.Fatalf("a second agent after the socket file was removed: err = %v", err) + } - // A socket file nobody listens on is stale and gets replaced. - if err := os.WriteFile(dir.Path(socketName), nil, 0o600); err != nil { + // An agent that died leaves its socket behind and holds nothing: the + // file is replaced. + dir = shortDir(t) + dead, err := net.Listen("unix", dir.Path(socketName)) + if err != nil { t.Fatal(err) } + dead.(*net.UnixListener).SetUnlinkOnClose(false) + dead.Close() + if _, err := os.Stat(dir.Path(socketName)); err != nil { + t.Fatalf("the left-over socket is not there: %v", err) + } second, err := Listen(dir) if err != nil { - t.Fatalf("Listen over a stale socket: %v", err) + t.Fatalf("Listen over a left-over socket: %v", err) + } + serve(t, second) + if err := ask(dir); err != nil { + t.Fatalf("the agent does not answer on the socket it replaced: %v", err) } - defer second.Close() if runtime.GOOS != "windows" { info, err := os.Stat(dir.Path(socketName)) if err != nil { @@ -393,5 +630,225 @@ func TestListenRefusesASecondAgentAndReplacesAStaleSocket(t *testing.T) { if info.Mode().Perm() != 0o600 { t.Fatalf("socket mode = %v, want 0600", info.Mode().Perm()) } + info, err = os.Stat(dir.Path(lockName)) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("lock file mode = %v, want 0600", info.Mode().Perm()) + } + } +} + +func TestClosingTheListenerFreesTheStateFolder(t *testing.T) { + dir := shortDir(t) + first, err := Listen(dir) + if err != nil { + t.Fatalf("Listen: %v", err) + } + if err := first.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if err := first.Close(); err != nil { + t.Fatalf("closing a second time: %v", err) + } + if _, err := os.Stat(dir.Path(socketName)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the socket is still there after Close: %v", err) + } + second, err := Listen(dir) + if err != nil { + t.Fatalf("Listen after the first listener was closed: %v", err) + } + serve(t, second) + if err := ask(dir); err != nil { + t.Fatalf("the second agent does not answer: %v", err) + } +} + +func TestAFailedListenDoesNotKeepTheStateFolder(t *testing.T) { + dir := shortDir(t) + // Something that cannot be removed the way a file can sits where the + // socket goes. + inTheWay := dir.Path(socketName) + if err := os.Mkdir(inTheWay, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(inTheWay, "x"), nil, 0o600); err != nil { + t.Fatal(err) + } + if ln, err := Listen(dir); err == nil { + ln.Close() + t.Fatal("Listen succeeded with a folder where the socket goes") + } else if strings.Contains(err.Error(), "already running") { + t.Fatalf("err = %v, want what is in the way", err) + } + if err := os.RemoveAll(inTheWay); err != nil { + t.Fatal(err) + } + ln, err := Listen(dir) + if err != nil { + t.Fatalf("Listen after one that failed: %v", err) + } + ln.Close() +} + +func TestOfAgentsStartedTogetherOnlyOneGetsTheStateFolder(t *testing.T) { + const rounds, agents = 5, 8 + for round := 0; round < rounds; round++ { + dir := shortDir(t) + var ( + wg sync.WaitGroup + mu sync.Mutex + won []net.Listener + ) + begin := make(chan struct{}) + for i := 0; i < agents; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-begin + ln, err := Listen(dir) + if err != nil { + if !strings.Contains(err.Error(), "already running") { + t.Errorf("round %d: an agent was turned away with %v", round, err) + } + return + } + mu.Lock() + won = append(won, ln) + mu.Unlock() + }() + } + close(begin) + wg.Wait() + if len(won) != 1 { + t.Errorf("round %d: %d agents got the folder, want 1", round, len(won)) + } + for _, ln := range won { + ln.Close() + } + } +} + +// departing is the context of a request whose client leaves at a moment the +// test picks. Done hands out a channel that is never closed: leave sends on +// it, and the send returns only when the handler has taken it. So the test +// knows, without waiting on a clock, that the handler has seen the client go +// and is past choosing what to do about it. +type departing struct { + context.Context + cancel context.CancelFunc + gone chan struct{} +} + +func newDeparting() *departing { + ctx, cancel := context.WithCancel(context.Background()) + return &departing{Context: ctx, cancel: cancel, gone: make(chan struct{})} +} + +func (d *departing) Done() <-chan struct{} { return d.gone } + +func (d *departing) leave(t *testing.T) { + t.Helper() + d.cancel() + select { + case d.gone <- struct{}{}: + case <-time.After(3 * time.Second): + t.Fatal("the handler did not notice that the command line left") + } +} + +// lineWriter is a response the test reads line by line while the handler is +// still running. +type lineWriter struct { + header http.Header + lines chan []byte +} + +func (w *lineWriter) Header() http.Header { return w.header } +func (w *lineWriter) WriteHeader(int) {} +func (w *lineWriter) Write(p []byte) (int, error) { + w.lines <- bytes.Clone(p) + return len(p), nil +} + +func TestTheLogSaysPairedWhenTheCommandLeavesWhileThePhoneRedeems(t *testing.T) { + f := start(t) + ctx := newDeparting() + w := &lineWriter{header: http.Header{}, lines: make(chan []byte, 4)} + req := httptest.NewRequest(http.MethodPost, "/pair", strings.NewReader("{}")).WithContext(ctx) + returned := make(chan struct{}) + go func() { + defer close(returned) + f.server.handlePair(w, req) + }() + var started Event + select { + case line := <-w.lines: + if err := json.Unmarshal(line, &started); err != nil { + t.Fatalf("the first line is not an event: %v", err) + } + case <-time.After(3 * time.Second): + t.Fatal("no event arrived") + } + code, ok := pairing.Normalize(started.Code) + if !ok { + t.Fatalf("the started event carries no valid code: %q", started.Code) + } + + // The phone's proof is right and its device is about to be stored: from + // here until release is closed the redeem is under way. + storing, release := make(chan struct{}), make(chan struct{}) + type outcome struct { + device state.Device + err error + } + redeemed := make(chan outcome, 1) + go func() { + nonce := bytes.Repeat([]byte{4}, pairing.NonceLen) + got, err := f.pairing.Redeem(agentFP, nonce, pairing.PhoneProof(code, agentFP, nonce), "Pixel 8", + func(name string, role state.Role) (state.Device, string, error) { + close(storing) + <-release + return f.devices.Add(name, role) + }) + redeemed <- outcome{got.Device, err} + }() + select { + case <-storing: + case <-time.After(3 * time.Second): + t.Fatal("the redeem did not get as far as storing the device") + } + + // Now the command line goes away, and only then does the redeem finish. + ctx.leave(t) + close(release) + + var got outcome + select { + case got = <-redeemed: + case <-time.After(3 * time.Second): + t.Fatal("the redeem did not return") + } + if got.err != nil { + t.Fatalf("redeem: %v", got.err) + } + select { + case <-returned: + case <-time.After(3 * time.Second): + t.Fatal("the handler did not return") + } + if list := f.devices.List(); len(list) != 1 || list[0].ID != got.device.ID { + t.Fatalf("devices = %+v, want the one that was paired", list) + } + log := f.log.String() + if strings.Contains(log, "outcome=cancelled") { + t.Fatalf("the log calls a pairing that stored a device cancelled:\n%s", log) + } + if !strings.Contains(log, "outcome=paired") || !strings.Contains(log, "device="+got.device.ID) || !strings.Contains(log, `name="Pixel 8"`) { + t.Fatalf("the log does not say which device was paired:\n%s", log) + } + if strings.Contains(log, code) || strings.Contains(log, started.Code) { + t.Fatal("the pairing code is in the log") } } diff --git a/agent/internal/admin/client.go b/agent/internal/admin/client.go index 9b61b89..02cc945 100644 --- a/agent/internal/admin/client.go +++ b/agent/internal/admin/client.go @@ -8,28 +8,38 @@ import ( "errors" "fmt" "io" + "io/fs" "net" "net/http" "net/url" + "os" "path/filepath" ) -// ErrNotRunning means nothing answers on the admin socket. +// ErrNotRunning means nothing answers on the admin socket: there is no +// socket, or nobody listens on the one that is there. var ErrNotRunning = errors.New("the agent is not running on this state folder") +// ErrNoAccess means the admin socket is out of reach for the user who runs +// the command. It does not say that an agent is running: a state folder +// that may not be entered hides whether there is a socket in it. +var ErrNoAccess = errors.New("this user may not use the admin socket of this state folder; run the command as the user the agent runs as") + // ErrStopped means the agent went away while a pairing was pending. var ErrStopped = errors.New("the agent stopped before the pairing ended") // Client talks to a running agent through its admin socket. type Client struct { http *http.Client + // socket is the path of the admin socket. + socket string } // NewClient returns a client for the agent whose state folder is dataDir. // It does not create the folder. func NewClient(dataDir string) *Client { path := filepath.Join(dataDir, socketName) - return &Client{http: &http.Client{Transport: &http.Transport{ + return &Client{socket: path, http: &http.Client{Transport: &http.Transport{ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, "unix", path) @@ -37,7 +47,25 @@ func NewClient(dataDir string) *Client { }}} } +// dialFailure says why the admin socket at path could not be connected to. +func dialFailure(path string, err error) error { + // What the folder says about the socket counts too: where the folder is + // missing, Windows fails the connection with an error of the network + // that says nothing about a file. + _, statErr := os.Stat(path) + switch { + case errors.Is(err, fs.ErrPermission), errors.Is(statErr, fs.ErrPermission): + return ErrNoAccess + case errors.Is(err, fs.ErrNotExist), errors.Is(statErr, fs.ErrNotExist), errors.Is(err, connRefused): + return ErrNotRunning + } + return fmt.Errorf("cannot reach the agent on its admin socket: %w", err) +} + func (c *Client) do(ctx context.Context, method, path string, body any) (*http.Response, error) { + if err := checkSocketPath(c.socket); err != nil { + return nil, err + } var reader io.Reader if body != nil { raw, err := json.Marshal(body) @@ -54,7 +82,7 @@ func (c *Client) do(ctx context.Context, method, path string, body any) (*http.R if err != nil { var opErr *net.OpError if errors.As(err, &opErr) && opErr.Op == "dial" { - return nil, ErrNotRunning + return nil, dialFailure(c.socket, opErr) } return nil, err } diff --git a/agent/internal/admin/os_unix.go b/agent/internal/admin/os_unix.go new file mode 100644 index 0000000..cba8c42 --- /dev/null +++ b/agent/internal/admin/os_unix.go @@ -0,0 +1,37 @@ +//go:build unix + +package admin + +import ( + "os" + "syscall" +) + +// connRefused is what connecting to a socket nobody listens on fails with. +const connRefused = syscall.ECONNREFUSED + +// lockFile opens the file at path, creating it if needed, and takes an +// exclusive lock on it without waiting. The lock goes when the file is +// closed, and the kernel closes the file when the process ends, however it +// ends. A lock that another open file holds is errLocked, also when that +// file was opened by this same process. +func lockFile(path string) (*os.File, error) { + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) + if err != nil { + return nil, err + } + for { + err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if err != syscall.EINTR { + break + } + } + if err != nil { + f.Close() + if err == syscall.EWOULDBLOCK { + return nil, errLocked + } + return nil, &os.PathError{Op: "lock", Path: path, Err: err} + } + return f, nil +} diff --git a/agent/internal/admin/os_windows.go b/agent/internal/admin/os_windows.go new file mode 100644 index 0000000..017f98d --- /dev/null +++ b/agent/internal/admin/os_windows.go @@ -0,0 +1,42 @@ +//go:build windows + +package admin + +import ( + "os" + "syscall" +) + +// Two error codes of Windows that package syscall does not name. +const ( + // sharingViolation is ERROR_SHARING_VIOLATION: the file is open + // elsewhere in a way that rules this open out. + sharingViolation = syscall.Errno(32) + // connRefused is WSAECONNREFUSED, what connecting to a socket nobody + // listens on fails with. The ECONNREFUSED that package syscall has for + // Windows is a value of its own making and does not match it. + connRefused = syscall.Errno(10061) +) + +// lockFile opens the file at path, creating it if needed, and shares it with +// nobody: while it is open no other open of the file succeeds, in this +// process or in another. That is the lock. It goes when the file is closed, +// and Windows closes the file when the process ends, however it ends. A file +// that is open elsewhere is errLocked. +func lockFile(path string) (*os.File, error) { + name, err := syscall.UTF16PtrFromString(path) + if err != nil { + return nil, &os.PathError{Op: "open", Path: path, Err: err} + } + // Share mode 0 only keeps others out when this open asks for access + // itself: an open that asks for none conflicts with nothing. + h, err := syscall.CreateFile(name, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, + syscall.OPEN_ALWAYS, syscall.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + if err == sharingViolation { + return nil, errLocked + } + return nil, &os.PathError{Op: "open", Path: path, Err: err} + } + return os.NewFile(uintptr(h), path), nil +} diff --git a/agent/internal/config/advertise.go b/agent/internal/config/advertise.go index e60e7e6..7b13c40 100644 --- a/agent/internal/config/advertise.go +++ b/agent/internal/config/advertise.go @@ -1,10 +1,13 @@ package config import ( + "errors" "fmt" "net" "net/url" + "strconv" "strings" + "unicode" ) // Advertise is the address pairing codes carry. Every field may be empty. @@ -23,7 +26,13 @@ type Advertise struct { // // In plain-HTTP mode the value is the URL of the proxy in front, such as // https://docker.example.com; without a value only the scheme "http" is -// known. +// known. Such a URL is a scheme, a host and perhaps a port, nothing else: +// what phones are told is an address, so a path, a query, a fragment or a +// user name would be lost. +// +// A value that cannot be right is refused, with an error that names it and +// says what is wrong with it, instead of ending up in pairing codes that +// lead nowhere. func ParseAdvertise(value string, insecure bool, listenPort string) (Advertise, error) { value = strings.TrimSpace(value) if !insecure { @@ -33,36 +42,67 @@ func ParseAdvertise(value string, insecure bool, listenPort string) (Advertise, if strings.Contains(value, "://") { return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q: give host or host:port, without a scheme", value) } - host, port, err := net.SplitHostPort(value) + host, port, err := splitAddress(value) if err != nil { - // No port: the whole value is the host (an IPv6 literal may be - // in brackets). - host, port = strings.Trim(value, "[]"), listenPort + return Advertise{}, refused("AGENT_ADVERTISE", value, err) } - if host == "" { - return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q has no host", value) + if port == "" { + port = listenPort } return Advertise{Host: host, Port: port}, nil } if value == "" { return Advertise{Scheme: "http", Port: listenPort}, nil } + if strings.IndexFunc(value, unicode.IsSpace) >= 0 { + return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q: a URL must not contain white space", value) + } + notAProxyURL := fmt.Errorf("AGENT_ADVERTISE %q: with --insecure-http give the URL of the proxy in front, such as https://docker.example.com", value) + if !strings.Contains(value, "://") { + return Advertise{}, notAProxyURL + } u, err := url.Parse(value) - if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Hostname() == "" { - return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q: with --insecure-http give the URL of the proxy in front, such as https://docker.example.com", value) + if err != nil { + // The cause alone: the error of the parser repeats the value. + var parse *url.Error + if errors.As(err, &parse) { + err = parse.Err + } + return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q: %v", value, err) + } + if (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + return Advertise{}, notAProxyURL + } + wrong := "" + switch { + case u.User != nil: + wrong = "the URL must not carry a user name or a password" + case u.RawQuery != "" || u.ForceQuery: + wrong = "the URL must not have a query, the part from the ? on" + case u.Fragment != "" || strings.Contains(value, "#"): + wrong = "the URL must not have a fragment, the part from the # on" + case u.Path != "" && u.Path != "/": + wrong = fmt.Sprintf("the URL must not have a path, and has %q: the proxy has to serve the agent at the root of its address", u.Path) + } + if wrong != "" { + return Advertise{}, fmt.Errorf("AGENT_ADVERTISE %q: %s", value, wrong) + } + host, port, err := splitAddress(u.Host) + if err != nil { + return Advertise{}, refused("AGENT_ADVERTISE", value, err) } - port := u.Port() if port == "" { port = "443" if u.Scheme == "http" { port = "80" } } - return Advertise{Scheme: u.Scheme, Host: u.Hostname(), Port: port}, nil + return Advertise{Scheme: u.Scheme, Host: host, Port: port}, nil } // WithHost returns a with its host (and port, if given) replaced by an -// address typed on the command line. +// address typed on the command line. It refuses what ParseAdvertise refuses +// in a host and a port. func (a Advertise) WithHost(hostPort string) (Advertise, error) { hostPort = strings.TrimSpace(hostPort) if hostPort == "" { @@ -71,13 +111,96 @@ func (a Advertise) WithHost(hostPort string) (Advertise, error) { if strings.Contains(hostPort, "://") { return Advertise{}, fmt.Errorf("--host %q: give host or host:port, without a scheme", hostPort) } - host, port, err := net.SplitHostPort(hostPort) + host, port, err := splitAddress(hostPort) if err != nil { - host, port = strings.Trim(hostPort, "[]"), a.Port + return Advertise{}, refused("--host", hostPort, err) } - if host == "" { - return Advertise{}, fmt.Errorf("--host %q has no host", hostPort) + if port == "" { + port = a.Port } a.Host, a.Port = host, port return a, nil } + +// errNoHost means an address has no host in it. +var errNoHost = errors.New("no host") + +// refused names a value that was turned down and says why. +func refused(what, value string, err error) error { + if errors.Is(err, errNoHost) { + return fmt.Errorf("%s %q has no host", what, value) + } + return fmt.Errorf("%s %q: %v", what, value, err) +} + +// splitAddress reads a host, or a host and a port, the way a person types +// them: a name or an IPv4 address, with :port after it if there is one, or +// an IPv6 address, which needs brackets around it when a port follows. port +// is empty when the value carries none. The error says what is wrong with +// the value and leaves naming it to the caller. +func splitAddress(value string) (host, port string, err error) { + withPort := false + switch { + case strings.HasPrefix(value, "["): + end := strings.IndexByte(value, ']') + if end < 0 { + return "", "", errors.New("the opening bracket has no closing bracket") + } + host = value[1:end] + if rest := value[end+1:]; rest != "" { + if rest[0] != ':' { + return "", "", errors.New("after the closing bracket only a colon and a port may follow") + } + port, withPort = rest[1:], true + } + case net.ParseIP(value) != nil || !strings.Contains(value, ":"): + // A name or an address by itself. An IPv6 address has colons of its + // own, so without brackets none of them can start a port. + host = value + case strings.Count(value, ":") == 1: + host, port, _ = strings.Cut(value, ":") + withPort = true + default: + return "", "", errors.New("it has more than one colon and is not an IPv6 address; with a port, an IPv6 address is written [address]:port") + } + if err := checkHost(host); err != nil { + return "", "", err + } + if withPort { + if err := checkPort(port); err != nil { + return "", "", err + } + } + return host, port, nil +} + +// checkHost refuses a host that no phone could connect to: an empty one, one +// with a character that belongs to another part of a URL or was left over +// from a bracket, and one with a colon that is not an IP address. +func checkHost(host string) error { + if host == "" { + return errNoHost + } + if i := strings.IndexAny(host, "/?#@[]"); i >= 0 { + return fmt.Errorf("the host must not contain %q", host[i:i+1]) + } + if strings.IndexFunc(host, unicode.IsSpace) >= 0 { + return errors.New("the host must not contain white space") + } + if strings.Contains(host, ":") && net.ParseIP(host) == nil { + return errors.New("the host has a colon in it and is not an IP address") + } + return nil +} + +// checkPort refuses a port that is not a number from 1 to 65535. It is +// called only when a colon announced a port. +func checkPort(port string) error { + if port == "" { + return errors.New("there is a colon with no port after it") + } + if n, err := strconv.ParseUint(port, 10, 16); err != nil || n == 0 { + return fmt.Errorf("the port %q is not a number from 1 to 65535", port) + } + return nil +} diff --git a/agent/internal/config/advertise_test.go b/agent/internal/config/advertise_test.go index 18c7cdf..ffc6116 100644 --- a/agent/internal/config/advertise_test.go +++ b/agent/internal/config/advertise_test.go @@ -1,6 +1,10 @@ package config -import "testing" +import ( + "strconv" + "strings" + "testing" +) func TestParseAdvertisePinned(t *testing.T) { cases := map[string]Advertise{ @@ -70,3 +74,172 @@ func TestWithHostOverridesTheAdvertisedAddress(t *testing.T) { } } } + +// refusal is a value that must be turned down, with words the error must use +// to say what is wrong with it. +type refusal struct{ in, says string } + +// check fails the test unless err turns the value down, names it and says +// what is wrong with it. +func (r refusal) check(t *testing.T, call string, got Advertise, err error) { + t.Helper() + switch { + case err == nil: + t.Errorf("%s(%q) was accepted as %+v", call, r.in, got) + case !strings.Contains(err.Error(), strconv.Quote(r.in)): + t.Errorf("%s(%q): the error does not name the value: %v", call, r.in, err) + case !strings.Contains(err.Error(), r.says): + t.Errorf("%s(%q): the error does not say %q: %v", call, r.in, r.says, err) + } +} + +func TestParseAdvertisePinnedRefusesWhatCannotBeRight(t *testing.T) { + for _, r := range []refusal{ + {"my-server.lan:", "no port after it"}, + {"my-server.lan:8443:", "more than one colon"}, + {"my-server.lan:abc", "not a number from 1 to 65535"}, + {"my-server.lan:0", "not a number from 1 to 65535"}, + {"my-server.lan:65536", "not a number from 1 to 65535"}, + {"my-server.lan:99999", "not a number from 1 to 65535"}, + {"my-server.lan:-1", "not a number from 1 to 65535"}, + {"my-server.lan:+80", "not a number from 1 to 65535"}, + {"my-server.lan:8443/agent", "not a number from 1 to 65535"}, + {"my-server.lan/agent", `must not contain "/"`}, + {"my-server.lan?x=1", `must not contain "?"`}, + {"my-server.lan#top", `must not contain "#"`}, + {"admin@my-server.lan", `must not contain "@"`}, + {"my-server.lan]", `must not contain "]"`}, + {"my server.lan", "white space"}, + {"my-server.lan: 8443", "not a number from 1 to 65535"}, + {"[fd00::1", "bracket"}, + {"[fd00::1]9443", "bracket"}, + {"[fd00::1]:", "no port after it"}, + {"[fd00::1]:0", "not a number from 1 to 65535"}, + {"[my:server]:8443", "not an IP address"}, + {"fd00::1:", "more than one colon"}, + {"a:b:c", "more than one colon"}, + {"[]:8443", "no host"}, + {":8443", "no host"}, + {"https://my-server.lan", "without a scheme"}, + } { + got, err := ParseAdvertise(r.in, false, "8443") + r.check(t, "ParseAdvertise", got, err) + } +} + +func TestParseAdvertiseBehindAProxyRefusesWhatCannotBeRight(t *testing.T) { + for _, r := range []refusal{ + {"https://docker.example.com/agent", "path"}, + {"https://docker.example.com/agent/", "path"}, + {"https://docker.example.com//", "path"}, + {"https://user:secret@docker.example.com", "user name"}, + {"https://user@docker.example.com", "user name"}, + {"https://@docker.example.com", "user name"}, + {"https://docker.example.com?x=1", "query"}, + {"https://docker.example.com/?x=1", "query"}, + {"https://docker.example.com?", "query"}, + {"https://docker.example.com#top", "fragment"}, + {"https://docker.example.com/#", "fragment"}, + {"https://docker.example.com:", "no port after it"}, + {"https://docker.example.com:0", "not a number from 1 to 65535"}, + {"https://docker.example.com:65536", "not a number from 1 to 65535"}, + {"https://docker.example.com:abc", "port"}, + {"https://[fd00::1]:", "no port after it"}, + {"https://docker example.com", "white space"}, + {"docker.example.com", "the URL of the proxy"}, + {"docker.example.com:8443", "the URL of the proxy"}, + {"ftp://docker.example.com", "the URL of the proxy"}, + {"https://", "the URL of the proxy"}, + {"https:///agent", "the URL of the proxy"}, + } { + got, err := ParseAdvertise(r.in, true, "8080") + r.check(t, "ParseAdvertise", got, err) + } +} + +func TestWithHostRefusesWhatCannotBeRight(t *testing.T) { + base := Advertise{Host: "old", Port: "8443"} + for _, r := range []refusal{ + {"new.lan:", "no port after it"}, + {"new.lan:9000:", "more than one colon"}, + {"new.lan:abc", "not a number from 1 to 65535"}, + {"new.lan:0", "not a number from 1 to 65535"}, + {"new.lan:65536", "not a number from 1 to 65535"}, + {"new.lan/x", `must not contain "/"`}, + {"new.lan?x", `must not contain "?"`}, + {"new.lan#x", `must not contain "#"`}, + {"user@new.lan", `must not contain "@"`}, + {"new.lan]", `must not contain "]"`}, + {"new lan", "white space"}, + {"[fd00::2", "bracket"}, + {"[fd00::2]9000", "bracket"}, + {"[fd00::2]:", "no port after it"}, + {"[new:lan]:9000", "not an IP address"}, + {"a:b:c", "more than one colon"}, + {":9000", "no host"}, + {"https://new.lan", "without a scheme"}, + } { + got, err := base.WithHost(r.in) + r.check(t, "WithHost", got, err) + } +} + +func TestAnIPv6AddressIsReadWithAndWithoutBracketsAndPort(t *testing.T) { + for in, want := range map[string]Advertise{ + "fd00::1": {Host: "fd00::1", Port: "8443"}, + "[fd00::1]": {Host: "fd00::1", Port: "8443"}, + "[fd00::1]:9443": {Host: "fd00::1", Port: "9443"}, + "::1": {Host: "::1", Port: "8443"}, + // Without brackets all of it is the address, the last group too. + "2001:db8::9443": {Host: "2001:db8::9443", Port: "8443"}, + } { + if got, err := ParseAdvertise(in, false, "8443"); err != nil || got != want { + t.Errorf("ParseAdvertise(%q) = %+v, %v, want %+v", in, got, err, want) + } + } + for in, want := range map[string]Advertise{ + "https://[fd00::1]": {Scheme: "https", Host: "fd00::1", Port: "443"}, + "https://[fd00::1]:8443": {Scheme: "https", Host: "fd00::1", Port: "8443"}, + "http://[fd00::1]/": {Scheme: "http", Host: "fd00::1", Port: "80"}, + } { + if got, err := ParseAdvertise(in, true, "8080"); err != nil || got != want { + t.Errorf("ParseAdvertise(%q) = %+v, %v, want %+v", in, got, err, want) + } + } + base := Advertise{Host: "old", Port: "8443"} + for in, want := range map[string]Advertise{ + "fd00::2": {Host: "fd00::2", Port: "8443"}, + "[fd00::2]": {Host: "fd00::2", Port: "8443"}, + "[fd00::2]:9000": {Host: "fd00::2", Port: "9000"}, + } { + if got, err := base.WithHost(in); err != nil || got != want { + t.Errorf("WithHost(%q) = %+v, %v, want %+v", in, got, err, want) + } + } +} + +func TestAddressesAtTheEdgeOfWhatIsRightAreAccepted(t *testing.T) { + for in, want := range map[string]Advertise{ + "my-server.lan:1": {Host: "my-server.lan", Port: "1"}, + "my-server.lan:65535": {Host: "my-server.lan", Port: "65535"}, + "192.168.1.20:9443": {Host: "192.168.1.20", Port: "9443"}, + } { + if got, err := ParseAdvertise(in, false, "8443"); err != nil || got != want { + t.Errorf("ParseAdvertise(%q) = %+v, %v, want %+v", in, got, err, want) + } + } + for in, want := range map[string]Advertise{ + // A lone slash is no path: the proxy serves the agent at its root. + "https://docker.example.com/": {Scheme: "https", Host: "docker.example.com", Port: "443"}, + "https://docker.example.com:8443/": {Scheme: "https", Host: "docker.example.com", Port: "8443"}, + "https://docker.example.com:65535": {Scheme: "https", Host: "docker.example.com", Port: "65535"}, + } { + if got, err := ParseAdvertise(in, true, "8080"); err != nil || got != want { + t.Errorf("ParseAdvertise(%q) = %+v, %v, want %+v", in, got, err, want) + } + } + // The port the agent listens on is the caller's and is not judged here. + if got, err := ParseAdvertise("my-server.lan", false, "0"); err != nil || got != (Advertise{Host: "my-server.lan", Port: "0"}) { + t.Errorf("ParseAdvertise with listen port 0 = %+v, %v", got, err) + } +} From 6bd9ebe22072cf90f461338ba3b540ae6131603b Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 07:29:49 +0530 Subject: [PATCH 20/32] feat(agent): serve TLS by default, with state and graceful shutdown --- .gitignore | 1 + README.md | 16 +- agent/cmd/agent/commands.go | 95 +++++ agent/cmd/agent/main.go | 72 +++- agent/cmd/agent/main_test.go | 521 +++++++++++++++++++++++++++ agent/cmd/agent/serve.go | 196 ++++++++++ agent/internal/auth/auth.go | 23 -- agent/internal/auth/auth_test.go | 81 ----- agent/internal/config/config.go | 86 ++++- agent/internal/config/config_test.go | 106 ++++-- agent/internal/exec/bridge_test.go | 13 +- agent/internal/server/server.go | 31 -- agent/internal/server/server_test.go | 65 ---- 13 files changed, 1041 insertions(+), 265 deletions(-) create mode 100644 agent/cmd/agent/commands.go create mode 100644 agent/cmd/agent/main_test.go create mode 100644 agent/cmd/agent/serve.go delete mode 100644 agent/internal/auth/auth.go delete mode 100644 agent/internal/auth/auth_test.go delete mode 100644 agent/internal/server/server.go delete mode 100644 agent/internal/server/server_test.go diff --git a/.gitignore b/.gitignore index fd7e146..63d71f1 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,7 @@ app/android/key.properties # === Go (agent/) === agent/bin/ +agent/.agent-data/ agent/vendor/ *.test *.out diff --git a/README.md b/README.md index 60f0d35..ed51611 100644 --- a/README.md +++ b/README.md @@ -8,12 +8,22 @@ Docker from your phone. - `app/` - Flutter app. ## Run the agent (dev) +The agent serves TLS with a certificate of its own and keeps its state (key, +certificate, paired phones) in a folder: ``` cd agent -AGENT_TOKEN=dev-secret DOCKER_HOST=unix:///var/run/docker.sock go run ./cmd/agent +AGENT_DATA=./.agent-data go run ./cmd/agent ``` -The agent listens on `:8080` by default. On Docker Desktop you can instead point it at -the exposed TCP API, e.g. `DOCKER_HOST=tcp://127.0.0.1:2375`. +It listens on `:8443`. On Docker Desktop point it at the exposed TCP API with +`DOCKER_HOST=tcp://127.0.0.1:2375`. + +The app in this repository does not yet connect to that certificate. Until it does, +run the agent the way the app expects, over plain HTTP with a shared token of at +least 16 characters: +``` +AGENT_DATA=./.agent-data AGENT_TOKEN=dev-secret-0123456789 go run ./cmd/agent --insecure-http +``` +That listens on `:8080`. `go run ./cmd/agent help` lists every command and setting. ## Run the app (dev) ``` diff --git a/agent/cmd/agent/commands.go b/agent/cmd/agent/commands.go new file mode 100644 index 0000000..0d50e5f --- /dev/null +++ b/agent/cmd/agent/commands.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "net" + "net/http" + "os" + "runtime" + "runtime/debug" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/tlsid" +) + +func cmdFingerprint(getenv func(string) string, stdout io.Writer) error { + dataDir := config.DataDir(getenv) + fp, err := tlsid.ReadFingerprint(dataDir) + if errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("no certificate in %s: the agent has not run yet, or it runs with --insecure-http", dataDir) + } + if err != nil { + return err + } + fmt.Fprintln(stdout, fp.Display()) + return nil +} + +// cmdHealthcheck asks the agent on this machine for /healthz. Over TLS it +// trusts exactly the certificate in the state folder. +func cmdHealthcheck(ctx context.Context, args []string, getenv func(string) string) error { + fs := flag.NewFlagSet("healthcheck", flag.ContinueOnError) + fs.SetOutput(io.Discard) + insecure := fs.Bool("insecure-http", false, "the agent serves plain HTTP") + if err := fs.Parse(args); err != nil { + return fmt.Errorf("healthcheck: %v", err) + } + cfg, err := config.Load(getenv, *insecure) + if err != nil { + return err + } + host, port, err := net.SplitHostPort(cfg.ListenAddr) + if err != nil { + return err + } + if ip := net.ParseIP(host); host == "" || (ip != nil && ip.IsUnspecified()) { + host = "127.0.0.1" + } + scheme := "http" + transport := &http.Transport{} + if !cfg.InsecureHTTP { + scheme = "https" + transport.TLSClientConfig, err = tlsid.LocalClientConfig(cfg.DataDir) + if err != nil { + return fmt.Errorf("read the agent's certificate: %w", err) + } + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, scheme+"://"+net.JoinHostPort(host, port)+"/healthz", nil) + if err != nil { + return err + } + resp, err := (&http.Client{Transport: transport}).Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("the agent answered %s", resp.Status) + } + return nil +} + +func versionLine() string { + commit, built := "unknown", "unknown" + if info, ok := debug.ReadBuildInfo(); ok { + for _, s := range info.Settings { + switch s.Key { + case "vcs.revision": + commit = s.Value + if len(commit) > 12 { + commit = commit[:12] + } + case "vcs.time": + built = s.Value + } + } + } + return fmt.Sprintf("docker-mobile-agent %s (commit %s, built %s, %s)", version, commit, built, runtime.Version()) +} diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go index 4880d2a..2f5e5fd 100644 --- a/agent/cmd/agent/main.go +++ b/agent/cmd/agent/main.go @@ -1,28 +1,66 @@ -// Command agent runs the docker-mobile companion agent. +// Command agent runs the docker-mobile companion agent and manages the +// phones paired with it. package main import ( - "log" - "net/http" + "context" + "fmt" + "io" "os" - "time" - - "github.com/retransmit/docker-mobile/agent/internal/config" - "github.com/retransmit/docker-mobile/agent/internal/server" + "strings" ) +// version is set at build time with -ldflags "-X main.version=...". +var version = "dev" + +const usage = `docker-mobile-agent - lets the docker-mobile app control this Docker host + +Usage: + docker-mobile-agent [serve] [--insecure-http] run the agent (default) + docker-mobile-agent fingerprint print the certificate fingerprint + docker-mobile-agent healthcheck [--insecure-http] + exit 0 when the agent answers + docker-mobile-agent version print the version + +Environment: + AGENT_LISTEN listen address (default :8443, or :8080 with --insecure-http) + AGENT_DATA state folder (default /var/lib/docker-mobile-agent) + AGENT_ADVERTISE address phones reach the agent at, for pairing codes + AGENT_NAME name shown on the phone while pairing (default: host name) + AGENT_INSECURE_HTTP 1 = serve plain HTTP, behind a proxy that terminates TLS + AGENT_TOKEN shared token of older setups (at least 16 characters) + DOCKER_HOST Docker daemon (default unix:///var/run/docker.sock) +` + func main() { - cfg, err := config.Load(os.Getenv) - if err != nil { - log.Fatalf("config: %v", err) + os.Exit(run(context.Background(), os.Args[1:], os.Getenv, os.Stdout, os.Stderr)) +} + +// run executes one command and returns the process exit code. +func run(ctx context.Context, args []string, getenv func(string) string, stdout, stderr io.Writer) int { + cmd, rest := "serve", args + if len(args) > 0 && !strings.HasPrefix(args[0], "-") { + cmd, rest = args[0], args[1:] } - h, err := server.Handler(cfg) - if err != nil { - log.Fatalf("server: %v", err) + var err error + switch cmd { + case "serve": + err = cmdServe(ctx, rest, getenv, stderr) + case "fingerprint": + err = cmdFingerprint(getenv, stdout) + case "healthcheck": + err = cmdHealthcheck(ctx, rest, getenv) + case "version": + fmt.Fprintln(stdout, versionLine()) + case "help": + fmt.Fprint(stdout, usage) + default: + fmt.Fprintf(stderr, "docker-mobile-agent: unknown command %q\n\n%s", cmd, usage) + return 2 } - log.Printf("docker-mobile-agent listening on %s (docker host: %s)", cfg.ListenAddr, cfg.DockerHost) - srv := &http.Server{Addr: cfg.ListenAddr, Handler: h, ReadHeaderTimeout: 10 * time.Second} - if err := srv.ListenAndServe(); err != nil { - log.Fatalf("listen: %v", err) + if err != nil { + fmt.Fprintln(stderr, "docker-mobile-agent:", err) + return 1 } + return 0 } diff --git a/agent/cmd/agent/main_test.go b/agent/cmd/agent/main_test.go new file mode 100644 index 0000000..a767634 --- /dev/null +++ b/agent/cmd/agent/main_test.go @@ -0,0 +1,521 @@ +package main + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "errors" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/tlsid" +) + +func TestMain(m *testing.M) { + // Streams never end by themselves, so every test that stops an agent + // with one open would wait the whole grace. + shutdownGrace = 200 * time.Millisecond + os.Exit(m.Run()) +} + +// syncBuf is a buffer a command can write to while the test reads it. +type syncBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuf) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuf) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +func waitFor(t *testing.T, what string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(10 * time.Millisecond) + } +} + +// fakeDocker answers lists at once and keeps /events open until the caller +// goes away. +func fakeDocker(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/events") { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte("{\"Type\":\"container\"}\n")) + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`[{"Id":"x"}]`)) + })) + t.Cleanup(srv.Close) + return srv +} + +// agent is a running agent under test. +type agent struct { + t *testing.T + env map[string]string + addr string + log *syncBuf + cancel context.CancelFunc + done chan error +} + +func (a *agent) getenv(k string) string { return a.env[k] } + +// startAgent runs serve in the background on a free port with a fresh state +// folder. extra is more environment, as key, value pairs. +func startAgent(t *testing.T, extra ...string) *agent { + t.Helper() + // A short path: the admin socket lives in it, and a unix socket path + // may not exceed about a hundred bytes. + dataDir, err := os.MkdirTemp("", "dma") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dataDir) }) + probe, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + listen := probe.Addr().String() + probe.Close() + + a := &agent{t: t, log: &syncBuf{}, done: make(chan error, 1), env: map[string]string{ + "AGENT_DATA": dataDir, + "AGENT_LISTEN": listen, + "AGENT_ADVERTISE": "127.0.0.1", + "AGENT_NAME": "test agent", + "DOCKER_HOST": "tcp://" + fakeDocker(t).Listener.Addr().String(), + }} + for i := 0; i+1 < len(extra); i += 2 { + a.env[extra[i]] = extra[i+1] + } + cfg, err := config.Load(a.getenv, false) + if err != nil { + t.Fatalf("config: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + a.cancel = cancel + ready := make(chan net.Addr, 1) + go func() { + a.done <- serve(ctx, cfg, slog.New(slog.NewTextHandler(a.log, nil)), func(addr net.Addr) { ready <- addr }) + }() + select { + case addr := <-ready: + a.addr = addr.String() + case err := <-a.done: + t.Fatalf("serve ended at once: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("the agent did not start") + } + t.Cleanup(func() { a.stop() }) + return a +} + +// stop ends the agent and returns what serve returned. It may be called +// more than once. +func (a *agent) stop() error { + a.cancel() + select { + case err := <-a.done: + a.done <- err + return err + case <-time.After(5 * time.Second): + a.t.Fatal("the agent did not stop") + return nil + } +} + +// command runs one command line against this agent's environment. +func (a *agent) command(args ...string) (code int, stdout, stderr string) { + var out, errOut syncBuf + code = run(context.Background(), args, a.getenv, &out, &errOut) + return code, out.String(), errOut.String() +} + +// fingerprint is what the agent's state folder says its identity is. +func (a *agent) fingerprint() tlsid.Fingerprint { + a.t.Helper() + fp, err := tlsid.ReadFingerprint(a.env["AGENT_DATA"]) + if err != nil { + a.t.Fatalf("read the fingerprint: %v", err) + } + return fp +} + +// phone plays the app: it pins a fingerprint the way the app does and +// carries a token. +type phone struct { + t *testing.T + scheme string + addr string + pin *tlsid.Fingerprint // nil until the phone trusts a certificate + seen tlsid.Fingerprint // what the last handshake presented + token string + client *http.Client +} + +func newPhone(t *testing.T, scheme, addr string) *phone { + p := &phone{t: t, scheme: scheme, addr: addr} + p.client = &http.Client{Transport: &http.Transport{ + DisableKeepAlives: true, + TLSClientConfig: &tls.Config{ + // The agent's certificate is self-signed, so the chain check + // cannot pass. Like the app, the phone replaces it with a + // stricter one: the key must be exactly the pinned one. + InsecureSkipVerify: true, + VerifyPeerCertificate: func(raw [][]byte, _ [][]*x509.Certificate) error { + fp, err := tlsid.FingerprintOfDER(raw[0]) + if err != nil { + return err + } + p.seen = fp + if p.pin != nil && fp != *p.pin { + return errors.New("server identity changed") + } + return nil + }, + }, + }} + return p +} + +// pinned returns a phone that already trusts this agent's certificate. +func (a *agent) pinned(token string) *phone { + p := newPhone(a.t, "https", a.addr) + fp := a.fingerprint() + p.pin, p.token = &fp, token + return p +} + +func (p *phone) do(method, path string, body []byte) (*http.Response, error) { + req, err := http.NewRequest(method, p.scheme+"://"+p.addr+path, bytes.NewReader(body)) + if err != nil { + return nil, err + } + if p.token != "" { + req.Header.Set("Authorization", "Bearer "+p.token) + } + return p.client.Do(req) +} + +func (p *phone) status(method, path string) int { + p.t.Helper() + resp, err := p.do(method, path, nil) + if err != nil { + p.t.Fatalf("%s %s: %v", method, path, err) + } + defer resp.Body.Close() + io.Copy(io.Discard, resp.Body) + return resp.StatusCode +} + +const shared = "a-shared-token-of-enough-length" + +func TestTheSharedTokenWorksOverThePinnedCertificate(t *testing.T) { + a := startAgent(t, "AGENT_TOKEN", shared) + log := a.log.String() + if !strings.Contains(log, "AGENT_TOKEN is set") || !strings.Contains(log, "AGENT_TOKEN is short") { + t.Fatalf("the log lacks the notice or the warning about the shared token: %s", log) + } + if strings.Contains(log, shared) { + t.Fatal("the shared token is in the log") + } + p := a.pinned(shared) + if got := p.status("GET", "/v1.45/containers/json"); got != http.StatusOK { + t.Fatalf("code = %d, want 200", got) + } + p.token = "wrong" + if got := p.status("GET", "/containers/json"); got != http.StatusUnauthorized { + t.Fatalf("code = %d, want 401", got) + } +} + +func TestAFreshAgentSaysHowToPairAndPrintsNoCode(t *testing.T) { + a := startAgent(t) + log := a.log.String() + if !strings.Contains(log, "no phone is paired yet") || !strings.Contains(log, "docker-mobile-agent pair") { + t.Fatalf("log = %s", log) + } + if !strings.Contains(log, "fingerprint="+a.fingerprint().Display()) { + t.Fatalf("the fingerprint is not in the startup log: %s", log) + } + if strings.Contains(log, "dockermobile://") { + t.Fatal("a pairing link was written to the log") + } +} + +func TestTheFingerprintCommandPrintsWhatThePortPresents(t *testing.T) { + a := startAgent(t) + p := newPhone(t, "https", a.addr) + p.status("GET", "/healthz") + code, out, errOut := a.command("fingerprint") + if code != 0 || strings.TrimSpace(out) != p.seen.Display() { + t.Fatalf("fingerprint: exit %d, %q (stderr %q); the port presents %q", code, out, errOut, p.seen.Display()) + } +} + +func TestHealthcheck(t *testing.T) { + a := startAgent(t) + if code, _, errOut := a.command("healthcheck"); code != 0 { + t.Fatalf("healthcheck of a running agent failed: %s", errOut) + } + a.stop() + if code, _, _ := a.command("healthcheck"); code != 1 { + t.Fatalf("healthcheck of a stopped agent: exit %d, want 1", code) + } +} + +func TestPlainHTTPMode(t *testing.T) { + a := startAgent(t, "AGENT_INSECURE_HTTP", "1", "AGENT_ADVERTISE", "https://docker.example.com", "AGENT_TOKEN", shared) + if !strings.Contains(a.log.String(), "serving plain HTTP") { + t.Fatalf("no warning about plain HTTP in the log: %s", a.log.String()) + } + p := newPhone(t, "http", a.addr) + p.token = shared + if got := p.status("GET", "/containers/json"); got != http.StatusOK { + t.Fatalf("code = %d, want 200", got) + } + if code, _, errOut := a.command("healthcheck"); code != 0 { + t.Fatalf("healthcheck failed: %s", errOut) + } + if code, _, errOut := a.command("fingerprint"); code != 1 || !strings.Contains(errOut, "no certificate") { + t.Fatalf("fingerprint in plain-HTTP mode: %d %q", code, errOut) + } + if _, err := os.Stat(filepath.Join(a.env["AGENT_DATA"], "tls.key")); !os.IsNotExist(err) { + t.Fatal("plain-HTTP mode created a TLS key") + } +} + +func TestStoppingTheAgentEndsStreamsAndCleansUp(t *testing.T) { + a := startAgent(t, "AGENT_TOKEN", shared) + before := a.fingerprint() + p := a.pinned(shared) + stream, err := p.do("GET", "/events", nil) + if err != nil { + t.Fatal(err) + } + defer stream.Body.Close() + if _, err := io.ReadFull(stream.Body, make([]byte, 1)); err != nil { + t.Fatalf("the stream did not start: %v", err) + } + + began := time.Now() + if err := a.stop(); err != nil { + t.Fatalf("serve returned %v", err) + } + if took := time.Since(began); took > 3*time.Second { + t.Fatalf("stopping took %v", took) + } + ended := make(chan struct{}) + go func() { + io.Copy(io.Discard, stream.Body) + close(ended) + }() + select { + case <-ended: + case <-time.After(3 * time.Second): + t.Fatal("the stream outlived the agent") + } + if _, err := os.Stat(filepath.Join(a.env["AGENT_DATA"], "admin.sock")); !os.IsNotExist(err) { + t.Fatalf("the admin socket was left behind: %v", err) + } + + // The same folder starts again with the same identity. + again := startAgent(t, "AGENT_DATA", a.env["AGENT_DATA"], "AGENT_TOKEN", shared) + if again.fingerprint() != before { + t.Fatal("the fingerprint changed across a restart") + } + if got := again.pinned(shared).status("GET", "/containers/json"); got != http.StatusOK { + t.Fatalf("after a restart: %d, want 200", got) + } +} + +func TestASecondAgentOnTheSameFolderIsRefused(t *testing.T) { + a := startAgent(t) + env := func(k string) string { + if k == "AGENT_LISTEN" { + return "127.0.0.1:0" + } + return a.env[k] + } + var errOut bytes.Buffer + if code := run(context.Background(), []string{"serve"}, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "already running") { + t.Fatalf("a second agent: exit %d, %s", code, errOut.String()) + } +} + +func TestASecondAgentIsRefusedBeforeItTouchesTheState(t *testing.T) { + a := startAgent(t) + // Damage the device list on disk. A second agent that read the state + // before taking the admin socket would stop on this file instead. + if err := os.WriteFile(filepath.Join(a.env["AGENT_DATA"], "devices.json"), []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + env := func(k string) string { + if k == "AGENT_LISTEN" { + return "127.0.0.1:0" + } + return a.env[k] + } + var errOut bytes.Buffer + if code := run(context.Background(), []string{"serve"}, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "already running") { + t.Fatalf("a second agent: exit %d, %s", code, errOut.String()) + } +} + +func TestTheStateFolderStaysLockedUntilRequestsHaveStopped(t *testing.T) { + // A longer grace for this test: with a stream open, stopping takes all + // of it, which leaves time to try a second agent meanwhile. + old := shutdownGrace + shutdownGrace = 2 * time.Second + t.Cleanup(func() { shutdownGrace = old }) + + a := startAgent(t, "AGENT_TOKEN", shared) + stream, err := a.pinned(shared).do("GET", "/events", nil) + if err != nil { + t.Fatal(err) + } + defer stream.Body.Close() + if _, err := io.ReadFull(stream.Body, make([]byte, 1)); err != nil { + t.Fatalf("the stream did not start: %v", err) + } + + a.cancel() + waitFor(t, "the agent to begin stopping", func() bool { return strings.Contains(a.log.String(), "stopping") }) + + // The first agent is still letting its stream finish. A second one on the + // same folder must be refused now; if it were let in, it would serve + // until its own context ends and exit cleanly. + env := func(k string) string { + if k == "AGENT_LISTEN" { + return "127.0.0.1:0" + } + return a.env[k] + } + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + var errOut bytes.Buffer + if code := run(ctx, []string{"serve"}, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "already running") { + t.Fatalf("a second agent while the first is stopping: exit %d, %s", code, errOut.String()) + } + if err := a.stop(); err != nil { + t.Fatalf("serve returned %v", err) + } +} + +func TestAPortInUseIsAClearError(t *testing.T) { + a := startAgent(t) + dataDir, err := os.MkdirTemp("", "dma") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(dataDir) + env := func(k string) string { + switch k { + case "AGENT_DATA": + return dataDir + case "AGENT_LISTEN": + return a.addr + } + return "" + } + var errOut bytes.Buffer + if code := run(context.Background(), nil, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "listen on "+a.addr) { + t.Fatalf("a port in use: exit %d, %s", code, errOut.String()) + } + if _, err := os.Stat(filepath.Join(dataDir, "admin.sock")); !os.IsNotExist(err) { + t.Fatal("the admin socket was left behind after a failed start") + } +} + +func TestAnUnusableStateFolderIsAClearError(t *testing.T) { + notAFolder := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(notAFolder, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + env := func(k string) string { + switch k { + case "AGENT_DATA": + return notAFolder + case "AGENT_LISTEN": + return "127.0.0.1:0" + } + return "" + } + var errOut bytes.Buffer + if code := run(context.Background(), nil, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "state folder") { + t.Fatalf("exit %d: %s", code, errOut.String()) + } +} + +// commandCase is one command line and what it must produce. +type commandCase struct { + name string + args []string + env []string // key, value pairs on top of an empty state folder + code int + inStdout string + inStderr string +} + +func runCommandCases(t *testing.T, cases []commandCase) { + t.Helper() + for _, c := range cases { + m := map[string]string{"AGENT_DATA": t.TempDir()} + for i := 0; i+1 < len(c.env); i += 2 { + m[c.env[i]] = c.env[i+1] + } + var out, errOut bytes.Buffer + code := run(context.Background(), c.args, func(k string) string { return m[k] }, &out, &errOut) + if code != c.code { + t.Errorf("%s: exit %d, want %d (stderr: %s)", c.name, code, c.code, errOut.String()) + } + if c.inStdout != "" && !strings.Contains(out.String(), c.inStdout) { + t.Errorf("%s: stdout lacks %q: %s", c.name, c.inStdout, out.String()) + } + if c.inStderr != "" && !strings.Contains(errOut.String(), c.inStderr) { + t.Errorf("%s: stderr lacks %q: %s", c.name, c.inStderr, errOut.String()) + } + } +} + +func TestCommandLine(t *testing.T) { + runCommandCases(t, []commandCase{ + {name: "unknown command", args: []string{"frobnicate"}, code: 2, inStderr: `unknown command "frobnicate"`}, + {name: "help", args: []string{"help"}, code: 0, inStdout: "docker-mobile-agent fingerprint"}, + {name: "version", args: []string{"version"}, code: 0, inStdout: "docker-mobile-agent dev (commit "}, + {name: "fingerprint before the first run", args: []string{"fingerprint"}, code: 1, inStderr: "no certificate"}, + {name: "a short shared token", env: []string{"AGENT_TOKEN", "too-short"}, code: 1, inStderr: "AGENT_TOKEN is too short (9 characters)"}, + {name: "a bad listen address", args: []string{"serve"}, env: []string{"AGENT_LISTEN", "nope"}, code: 1, inStderr: "AGENT_LISTEN"}, + {name: "a bad flag for serve", args: []string{"--verbose"}, code: 1, inStderr: "flag provided but not defined"}, + {name: "healthcheck without an agent", args: []string{"healthcheck", "--insecure-http"}, env: []string{"AGENT_LISTEN", "127.0.0.1:1"}, code: 1}, + }) +} diff --git a/agent/cmd/agent/serve.go b/agent/cmd/agent/serve.go new file mode 100644 index 0000000..a5fc3a7 --- /dev/null +++ b/agent/cmd/agent/serve.go @@ -0,0 +1,196 @@ +package main + +import ( + "context" + "crypto/rand" + "crypto/tls" + "errors" + "flag" + "fmt" + "io" + "log" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/admin" + "github.com/retransmit/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/conns" + "github.com/retransmit/docker-mobile/agent/internal/pairing" + "github.com/retransmit/docker-mobile/agent/internal/server" + "github.com/retransmit/docker-mobile/agent/internal/state" + "github.com/retransmit/docker-mobile/agent/internal/throttle" + "github.com/retransmit/docker-mobile/agent/internal/tlsid" +) + +// shutdownGrace is how long requests in flight get to finish when the agent +// stops. After it, streams and terminals are closed. It is a variable so +// that tests can shorten it. +var shutdownGrace = 5 * time.Second + +func cmdServe(ctx context.Context, args []string, getenv func(string) string, stderr io.Writer) error { + fs := flag.NewFlagSet("serve", flag.ContinueOnError) + fs.SetOutput(stderr) + insecure := fs.Bool("insecure-http", false, "serve plain HTTP, behind a proxy that terminates TLS") + if err := fs.Parse(args); err != nil { + return err + } + cfg, err := config.Load(getenv, *insecure) + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) + defer stop() + return serve(ctx, cfg, slog.New(slog.NewTextHandler(stderr, nil)), nil) +} + +// serve runs the agent until ctx ends. ready, when not nil, is called once +// with the address the agent listens on. +func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready func(net.Addr)) error { + dir, err := state.Open(cfg.DataDir) + if err != nil { + return err + } + // The admin socket is what keeps a second agent off this folder, so it is + // taken before anything reads or writes the state: the device list and + // the certificate below are state. + adminLn, err := admin.Listen(dir) + if err != nil { + return err + } + adminServing := false + defer func() { + if !adminServing { + adminLn.Close() + } + }() + devices, err := state.LoadDevices(dir, time.Now) + if err != nil { + return err + } + + var ( + cert tls.Certificate + fingerprint []byte + fpLink string + fpDisplay string + ) + if !cfg.InsecureHTTP { + cert, err = tlsid.LoadOrCreate(dir, time.Now()) + if err != nil { + return err + } + fp, err := tlsid.FingerprintOf(cert) + if err != nil { + return err + } + fingerprint, fpLink, fpDisplay = fp[:], fp.String(), fp.Display() + } + + name := cfg.Name + if name == "" { + name, _ = os.Hostname() + } + registry := conns.New() + manager := pairing.NewManager(time.Now, rand.Reader) + handler, err := server.New(server.Options{ + DockerHost: cfg.DockerHost, + Devices: devices, + LegacyToken: cfg.LegacyToken, + Pairing: manager, + Fingerprint: fingerprint, + Limiter: throttle.New(time.Now), + Conns: registry, + Version: version, + Log: logger, + }) + if err != nil { + return err + } + adminServer := &admin.Server{ + Pairing: manager, + Devices: devices, + Conns: registry, + Advertise: cfg.Advertise, + Fingerprint: fpLink, + FingerprintDisplay: fpDisplay, + AgentName: name, + Log: logger, + } + + ln, err := net.Listen("tcp", cfg.ListenAddr) + if err != nil { + return fmt.Errorf("listen on %s: %w", cfg.ListenAddr, err) + } + if !cfg.InsecureHTTP { + ln = tls.NewListener(ln, tlsid.ServerConfig(cert)) + } + + // The standard library reports every failed TLS handshake through + // ErrorLog; on an open port that is mostly scanners, so it is dropped. + quiet := log.New(io.Discard, "", 0) + srv := &http.Server{ + Handler: handler, + ReadHeaderTimeout: 10 * time.Second, + IdleTimeout: 120 * time.Second, + MaxHeaderBytes: 64 << 10, + ErrorLog: quiet, + } + adminSrv := &http.Server{Handler: adminServer.Handler(), ReadHeaderTimeout: 10 * time.Second, ErrorLog: quiet} + + logger.Info("docker-mobile-agent started", "version", version, "listen", ln.Addr().String(), "docker", cfg.DockerHost, "data", cfg.DataDir) + switch { + case cfg.InsecureHTTP: + logger.Warn("serving plain HTTP: nothing is encrypted unless a proxy in front terminates TLS") + default: + logger.Info("serving TLS with the agent's own certificate", "fingerprint", fpDisplay) + } + if cfg.LegacyToken != "" { + logger.Info("AGENT_TOKEN is set: it gives full control to whoever holds it; pairing gives each phone its own revocable token") + if len(cfg.LegacyToken) < config.WeakLegacyToken { + logger.Warn("AGENT_TOKEN is short; use at least 32 characters", "length", len(cfg.LegacyToken)) + } + } + if cfg.LegacyToken == "" && len(devices.List()) == 0 { + logger.Info("no phone is paired yet; run: docker-mobile-agent pair") + } + + errc := make(chan error, 2) + go func() { errc <- srv.Serve(ln) }() + adminServing = true + go func() { errc <- adminSrv.Serve(adminLn) }() + if ready != nil { + ready(ln.Addr()) + } + + var serveErr error + select { + case <-ctx.Done(): + case serveErr = <-errc: + } + + logger.Info("stopping") + grace, cancel := context.WithTimeout(context.Background(), shutdownGrace) + defer cancel() + // Stop accepting and let short requests finish. Streams and terminals + // never finish by themselves: once the grace is over, end them so that + // clients see the connection close instead of hanging. + shutdownErr := srv.Shutdown(grace) + registry.CloseAll() + srv.Close() + // The admin socket goes last: closing it gives up the lock on the state + // folder, and until here a request could still write there. It also ends + // a pair command that is still waiting. + adminSrv.Close() + if serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) { + return serveErr + } + if shutdownErr != nil && !errors.Is(shutdownErr, context.DeadlineExceeded) { + return shutdownErr + } + return nil +} diff --git a/agent/internal/auth/auth.go b/agent/internal/auth/auth.go deleted file mode 100644 index 077dc36..0000000 --- a/agent/internal/auth/auth.go +++ /dev/null @@ -1,23 +0,0 @@ -// Package auth provides the agent's bearer-token gate. -package auth - -import ( - "crypto/subtle" - "net/http" -) - -func RequireToken(token string, next http.Handler) http.Handler { - want := []byte("Bearer " + token) - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if token == "" { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - got := []byte(r.Header.Get("Authorization")) - if subtle.ConstantTimeCompare(got, want) != 1 { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - next.ServeHTTP(w, r) - }) -} diff --git a/agent/internal/auth/auth_test.go b/agent/internal/auth/auth_test.go deleted file mode 100644 index 965ccd7..0000000 --- a/agent/internal/auth/auth_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package auth - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -func okHandler() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Write([]byte("ok")) - }) -} - -func TestRequireTokenAllows(t *testing.T) { - h := RequireToken("secret", okHandler()) - req := httptest.NewRequest(http.MethodGet, "/containers/json", nil) - req.Header.Set("Authorization", "Bearer secret") - rec := httptest.NewRecorder() - h.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("code = %d, want 200", rec.Code) - } -} - -func TestRequireTokenRejectsMissing(t *testing.T) { - called := false - next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - w.WriteHeader(http.StatusOK) - }) - h := RequireToken("secret", next) - req := httptest.NewRequest(http.MethodGet, "/", nil) - rec := httptest.NewRecorder() - h.ServeHTTP(rec, req) - if rec.Code != http.StatusUnauthorized { - t.Fatalf("code = %d, want 401", rec.Code) - } - if called { - t.Fatal("next handler was invoked, want not invoked") - } -} - -func TestRequireTokenRejectsWrong(t *testing.T) { - called := false - next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - w.WriteHeader(http.StatusOK) - }) - h := RequireToken("secret", next) - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.Header.Set("Authorization", "Bearer nope") - rec := httptest.NewRecorder() - h.ServeHTTP(rec, req) - if rec.Code != http.StatusUnauthorized { - t.Fatalf("code = %d, want 401", rec.Code) - } - if called { - t.Fatal("next handler was invoked, want not invoked") - } -} - -func TestRequireTokenEmptyTokenRejectsAll(t *testing.T) { - called := false - next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - w.WriteHeader(http.StatusOK) - }) - h := RequireToken("", next) - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.Header.Set("Authorization", "Bearer ") - rec := httptest.NewRecorder() - h.ServeHTTP(rec, req) - if rec.Code != http.StatusUnauthorized { - t.Fatalf("code = %d, want 401", rec.Code) - } - if called { - t.Fatal("next handler was invoked, want not invoked") - } -} diff --git a/agent/internal/config/config.go b/agent/internal/config/config.go index ec75566..a77056e 100644 --- a/agent/internal/config/config.go +++ b/agent/internal/config/config.go @@ -1,29 +1,93 @@ // Package config loads the agent's runtime configuration from the environment. package config -import "errors" +import ( + "errors" + "fmt" + "net" + "strings" + "github.com/retransmit/docker-mobile/agent/internal/state" +) + +const ( + // MinLegacyToken is the shortest shared token the agent accepts. + MinLegacyToken = 16 + // WeakLegacyToken is the length below which the agent warns. + WeakLegacyToken = 32 + + defaultTLSListen = ":8443" + defaultPlainListen = ":8080" + defaultDockerHost = "unix:///var/run/docker.sock" + defaultDataDir = "/var/lib/docker-mobile-agent" +) + +// Config is everything the agent reads from its environment. type Config struct { ListenAddr string - Token string DockerHost string + DataDir string + // Advertise is where phones reach the agent, for pairing codes. + Advertise Advertise + // InsecureHTTP serves plain HTTP, for use behind a proxy that does TLS. + InsecureHTTP bool + // LegacyToken is the shared token from AGENT_TOKEN; empty when unset. + LegacyToken string + // Name is how the agent calls itself in pairing codes (AGENT_NAME); + // empty means the host name. + Name string } -// Load builds a Config from getenv. AGENT_TOKEN is required. -func Load(getenv func(string) string) (Config, error) { +// Load builds a Config from getenv. insecureFlag is the --insecure-http +// flag; AGENT_INSECURE_HTTP=1 means the same. +func Load(getenv func(string) string, insecureFlag bool) (Config, error) { cfg := Config{ - ListenAddr: getenv("AGENT_LISTEN"), - Token: getenv("AGENT_TOKEN"), - DockerHost: getenv("DOCKER_HOST"), + ListenAddr: getenv("AGENT_LISTEN"), + DockerHost: getenv("DOCKER_HOST"), + InsecureHTTP: insecureFlag || truthy(getenv("AGENT_INSECURE_HTTP")), + LegacyToken: getenv("AGENT_TOKEN"), + Name: strings.TrimSpace(getenv("AGENT_NAME")), } if cfg.ListenAddr == "" { - cfg.ListenAddr = ":8080" + cfg.ListenAddr = defaultTLSListen + if cfg.InsecureHTTP { + cfg.ListenAddr = defaultPlainListen + } } if cfg.DockerHost == "" { - cfg.DockerHost = "unix:///var/run/docker.sock" + cfg.DockerHost = defaultDockerHost + } + cfg.DataDir = DataDir(getenv) + if n := len(cfg.LegacyToken); n > 0 && n < MinLegacyToken { + return Config{}, fmt.Errorf("AGENT_TOKEN is too short (%d characters): use at least %d, or remove it and pair devices instead", n, MinLegacyToken) + } + if state.IsDeviceToken(cfg.LegacyToken) { + return Config{}, errors.New("AGENT_TOKEN must not start with \"dm1.\": that prefix marks the tokens of paired devices") + } + _, listenPort, err := net.SplitHostPort(cfg.ListenAddr) + if err != nil { + return Config{}, fmt.Errorf("AGENT_LISTEN %q is not host:port: %v", cfg.ListenAddr, err) } - if cfg.Token == "" { - return Config{}, errors.New("AGENT_TOKEN is required") + cfg.Advertise, err = ParseAdvertise(getenv("AGENT_ADVERTISE"), cfg.InsecureHTTP, listenPort) + if err != nil { + return Config{}, err } return cfg, nil } + +// DataDir returns the state folder alone, for commands that need nothing +// else from the configuration. +func DataDir(getenv func(string) string) string { + if dir := getenv("AGENT_DATA"); dir != "" { + return dir + } + return defaultDataDir +} + +func truthy(v string) bool { + switch strings.ToLower(strings.TrimSpace(v)) { + case "1", "true", "yes", "on": + return true + } + return false +} diff --git a/agent/internal/config/config_test.go b/agent/internal/config/config_test.go index d096231..f681cec 100644 --- a/agent/internal/config/config_test.go +++ b/agent/internal/config/config_test.go @@ -1,43 +1,103 @@ package config -import "testing" +import ( + "strings" + "testing" +) -func env(m map[string]string) func(string) string { +func env(pairs ...string) func(string) string { + m := map[string]string{} + for i := 0; i+1 < len(pairs); i += 2 { + m[pairs[i]] = pairs[i+1] + } return func(k string) string { return m[k] } } -func TestLoadDefaults(t *testing.T) { - cfg, err := Load(env(map[string]string{"AGENT_TOKEN": "secret"})) +func TestDefaultsServeTLSOn8443WithoutAnyToken(t *testing.T) { + cfg, err := Load(env(), false) if err != nil { - t.Fatalf("unexpected error: %v", err) + t.Fatalf("Load: %v", err) + } + want := Config{ + ListenAddr: ":8443", + DockerHost: "unix:///var/run/docker.sock", + DataDir: "/var/lib/docker-mobile-agent", + Advertise: Advertise{Port: "8443"}, } - if cfg.ListenAddr != ":8080" { - t.Errorf("ListenAddr = %q, want :8080", cfg.ListenAddr) + if cfg != want { + t.Fatalf("cfg = %+v, want %+v", cfg, want) } - if cfg.DockerHost != "unix:///var/run/docker.sock" { - t.Errorf("DockerHost = %q, want unix:///var/run/docker.sock", cfg.DockerHost) +} + +func TestPlainHTTPDefaultsTo8080(t *testing.T) { + for name, load := range map[string]func() (Config, error){ + "flag": func() (Config, error) { return Load(env(), true) }, + "env": func() (Config, error) { return Load(env("AGENT_INSECURE_HTTP", "1"), false) }, + "TRUE": func() (Config, error) { return Load(env("AGENT_INSECURE_HTTP", "TRUE"), false) }, + } { + cfg, err := load() + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if !cfg.InsecureHTTP || cfg.ListenAddr != ":8080" || cfg.Advertise != (Advertise{Scheme: "http", Port: "8080"}) { + t.Fatalf("%s: cfg = %+v", name, cfg) + } } - if cfg.Token != "secret" { - t.Errorf("Token = %q, want secret", cfg.Token) + if cfg, _ := Load(env("AGENT_INSECURE_HTTP", "0"), false); cfg.InsecureHTTP { + t.Fatal("AGENT_INSECURE_HTTP=0 turned plain HTTP on") } } -func TestLoadOverrides(t *testing.T) { - cfg, err := Load(env(map[string]string{ - "AGENT_TOKEN": "t", - "AGENT_LISTEN": ":9000", - "DOCKER_HOST": "tcp://127.0.0.1:2375", - })) +func TestEverySettingIsRead(t *testing.T) { + cfg, err := Load(env( + "AGENT_LISTEN", "127.0.0.1:9000", + "DOCKER_HOST", "tcp://127.0.0.1:2375", + "AGENT_DATA", "/srv/agent", + "AGENT_ADVERTISE", "my-server.lan", + "AGENT_TOKEN", "sixteen-chars-ok", + "AGENT_NAME", " home lab ", + ), false) if err != nil { - t.Fatalf("unexpected error: %v", err) + t.Fatalf("Load: %v", err) } - if cfg.ListenAddr != ":9000" || cfg.DockerHost != "tcp://127.0.0.1:2375" { - t.Errorf("overrides not applied: %+v", cfg) + want := Config{ + ListenAddr: "127.0.0.1:9000", + DockerHost: "tcp://127.0.0.1:2375", + DataDir: "/srv/agent", + Advertise: Advertise{Host: "my-server.lan", Port: "9000"}, + LegacyToken: "sixteen-chars-ok", + Name: "home lab", + } + if cfg != want { + t.Fatalf("cfg = %+v, want %+v", cfg, want) + } +} + +func TestAShortSharedTokenStopsTheAgent(t *testing.T) { + _, err := Load(env("AGENT_TOKEN", "fifteen-chars-x"), false) + if err == nil || !strings.Contains(err.Error(), "too short (15 characters)") { + t.Fatalf("err = %v", err) } } -func TestLoadRequiresToken(t *testing.T) { - if _, err := Load(env(map[string]string{})); err == nil { - t.Fatal("expected error when AGENT_TOKEN is missing") +func TestASharedTokenShapedLikeADeviceTokenStopsTheAgent(t *testing.T) { + _, err := Load(env("AGENT_TOKEN", "dm1.abcd1234.this-would-never-match"), false) + if err == nil || !strings.Contains(err.Error(), "dm1.") { + t.Fatalf("err = %v", err) + } +} + +func TestABadListenAddressIsAnError(t *testing.T) { + if _, err := Load(env("AGENT_LISTEN", "8443"), false); err == nil { + t.Fatal("a listen address without a port separator was accepted") + } +} + +func TestDataDir(t *testing.T) { + if got := DataDir(env()); got != "/var/lib/docker-mobile-agent" { + t.Fatalf("default = %q", got) + } + if got := DataDir(env("AGENT_DATA", "/data")); got != "/data" { + t.Fatalf("DataDir = %q", got) } } diff --git a/agent/internal/exec/bridge_test.go b/agent/internal/exec/bridge_test.go index 8b03d49..8acd7d9 100644 --- a/agent/internal/exec/bridge_test.go +++ b/agent/internal/exec/bridge_test.go @@ -13,7 +13,6 @@ import ( "time" "github.com/gorilla/websocket" - "github.com/retransmit/docker-mobile/agent/internal/auth" ) // fakeExecStart serves one connection: records the request, replies with @@ -111,20 +110,12 @@ func TestExecBridgeEchoesBothDirections(t *testing.T) { t.Fatalf("NewHandler: %v", err) } mux := http.NewServeMux() - mux.Handle("GET /exec/{id}/ws", auth.RequireToken("secret", h)) + mux.Handle("GET /exec/{id}/ws", h) srv := httptest.NewServer(mux) defer srv.Close() wsURL := "ws" + strings.TrimPrefix(srv.URL, "http") + "/exec/abc/ws" - // Without a token -> rejected at the auth layer. - if _, resp, err := websocket.DefaultDialer.Dial(wsURL, nil); err == nil { - t.Fatal("expected auth rejection") - } else if resp == nil || resp.StatusCode != http.StatusUnauthorized { - t.Fatalf("want 401, got %v", resp) - } - - // With a token -> connect and echo. - c, _, err := websocket.DefaultDialer.Dial(wsURL, http.Header{"Authorization": {"Bearer secret"}}) + c, _, err := websocket.DefaultDialer.Dial(wsURL, nil) if err != nil { t.Fatalf("dial: %v", err) } diff --git a/agent/internal/server/server.go b/agent/internal/server/server.go deleted file mode 100644 index 2fb089f..0000000 --- a/agent/internal/server/server.go +++ /dev/null @@ -1,31 +0,0 @@ -// Package server composes the agent's HTTP handler: an unauthenticated health -// check plus the token-gated transparent Docker proxy. -package server - -import ( - "net/http" - - "github.com/retransmit/docker-mobile/agent/internal/auth" - "github.com/retransmit/docker-mobile/agent/internal/config" - "github.com/retransmit/docker-mobile/agent/internal/exec" - "github.com/retransmit/docker-mobile/agent/internal/proxy" -) - -func Handler(cfg config.Config) (http.Handler, error) { - dockerProxy, err := proxy.New(cfg.DockerHost) - if err != nil { - return nil, err - } - mux := http.NewServeMux() - mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Write([]byte("ok")) - }) - execHandler, err := exec.NewHandler(cfg.DockerHost) - if err != nil { - return nil, err - } - mux.Handle("GET /exec/{id}/ws", auth.RequireToken(cfg.Token, execHandler)) - mux.Handle("/", auth.RequireToken(cfg.Token, dockerProxy)) - return mux, nil -} diff --git a/agent/internal/server/server_test.go b/agent/internal/server/server_test.go deleted file mode 100644 index 7af0cae..0000000 --- a/agent/internal/server/server_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package server - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/retransmit/docker-mobile/agent/internal/config" -) - -func fakeDaemon() *httptest.Server { - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode([]map[string]any{{"Id": "x"}}) - })) -} - -func newHandler(t *testing.T, daemon *httptest.Server) http.Handler { - t.Helper() - h, err := Handler(config.Config{ - ListenAddr: ":0", - Token: "secret", - DockerHost: "tcp://" + daemon.Listener.Addr().String(), - }) - if err != nil { - t.Fatalf("Handler: %v", err) - } - return h -} - -func TestHealthzNoAuth(t *testing.T) { - d := fakeDaemon() - defer d.Close() - h := newHandler(t, d) - rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil)) - if rec.Code != http.StatusOK { - t.Fatalf("healthz code = %d, want 200", rec.Code) - } -} - -func TestProxiedPathRequiresAuth(t *testing.T) { - d := fakeDaemon() - defer d.Close() - h := newHandler(t, d) - rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/containers/json", nil)) - if rec.Code != http.StatusUnauthorized { - t.Fatalf("unauthenticated proxy code = %d, want 401", rec.Code) - } -} - -func TestProxiedPathWithAuth(t *testing.T) { - d := fakeDaemon() - defer d.Close() - h := newHandler(t, d) - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/containers/json", nil) - req.Header.Set("Authorization", "Bearer secret") - h.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("authenticated proxy code = %d, want 200", rec.Code) - } -} From d55ef22615d25ad5a79484b646bcf84b66c5bcbc Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 18:18:11 +0530 Subject: [PATCH 21/32] fix(agent): keep server errors in the log and tidy start and stop --- README.md | 2 +- agent/cmd/agent/main_test.go | 191 +++++++++++++++++++++++++- agent/cmd/agent/serve.go | 70 +++++++--- agent/internal/config/config.go | 64 +++++++-- agent/internal/config/config_test.go | 71 +++++++++- agent/internal/server/handler_test.go | 3 + 6 files changed, 369 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index ed51611..096d2ce 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ The app in this repository does not yet connect to that certificate. Until it do run the agent the way the app expects, over plain HTTP with a shared token of at least 16 characters: ``` -AGENT_DATA=./.agent-data AGENT_TOKEN=dev-secret-0123456789 go run ./cmd/agent --insecure-http +AGENT_DATA=./.agent-data AGENT_TOKEN=replace-me-with-32-or-more-characters go run ./cmd/agent --insecure-http ``` That listens on `:8080`. `go run ./cmd/agent help` lists every command and setting. diff --git a/agent/cmd/agent/main_test.go b/agent/cmd/agent/main_test.go index a767634..f856e6b 100644 --- a/agent/cmd/agent/main_test.go +++ b/agent/cmd/agent/main_test.go @@ -18,6 +18,8 @@ import ( "testing" "time" + "github.com/gorilla/websocket" + "github.com/retransmit/docker-mobile/agent/internal/admin" "github.com/retransmit/docker-mobile/agent/internal/config" "github.com/retransmit/docker-mobile/agent/internal/tlsid" ) @@ -58,11 +60,28 @@ func waitFor(t *testing.T, what string, ok func() bool) { } } +// terminalGreeting is what the fake daemon sends once a terminal is open. +const terminalGreeting = "ready" + // fakeDocker answers lists at once and keeps /events open until the caller -// goes away. +// goes away. It starts a terminal the way the daemon does: for POST +// /exec//start it takes the connection over, answers 101, sends +// terminalGreeting and then holds the connection until the caller closes it. func fakeDocker(t *testing.T) *httptest.Server { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/exec/") && strings.HasSuffix(r.URL.Path, "/start") { + io.Copy(io.Discard, r.Body) + conn, rw, err := w.(http.Hijacker).Hijack() + if err != nil { + return + } + defer conn.Close() + rw.WriteString("HTTP/1.1 101 UPGRADED\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n" + terminalGreeting) + rw.Flush() + io.Copy(io.Discard, rw) + return + } if strings.HasSuffix(r.URL.Path, "/events") { w.Header().Set("Content-Type", "application/json") w.Write([]byte("{\"Type\":\"container\"}\n")) @@ -100,6 +119,10 @@ func startAgent(t *testing.T, extra ...string) *agent { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(dataDir) }) + // The fake daemon takes its port before the agent's is looked for: + // started after the probe, it would be the nearest contender for the + // port the probe has just given back. + docker := fakeDocker(t) probe, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) @@ -112,7 +135,7 @@ func startAgent(t *testing.T, extra ...string) *agent { "AGENT_LISTEN": listen, "AGENT_ADVERTISE": "127.0.0.1", "AGENT_NAME": "test agent", - "DOCKER_HOST": "tcp://" + fakeDocker(t).Listener.Addr().String(), + "DOCKER_HOST": "tcp://" + docker.Listener.Addr().String(), }} for i := 0; i+1 < len(extra); i += 2 { a.env[extra[i]] = extra[i+1] @@ -122,6 +145,10 @@ func startAgent(t *testing.T, extra ...string) *agent { t.Fatalf("config: %v", err) } ctx, cancel := context.WithCancel(context.Background()) + // Whatever happens below, the agent is told to stop when the test is + // over: one that never reported ready would otherwise keep its port, its + // folder and its goroutine. + t.Cleanup(cancel) a.cancel = cancel ready := make(chan net.Addr, 1) go func() { @@ -248,6 +275,9 @@ func TestTheSharedTokenWorksOverThePinnedCertificate(t *testing.T) { if strings.Contains(log, shared) { t.Fatal("the shared token is in the log") } + if strings.Contains(log, "length=") { + t.Fatalf("the length of the shared token is in the log: %s", log) + } p := a.pinned(shared) if got := p.status("GET", "/v1.45/containers/json"); got != http.StatusOK { t.Fatalf("code = %d, want 200", got) @@ -258,6 +288,17 @@ func TestTheSharedTokenWorksOverThePinnedCertificate(t *testing.T) { } } +func TestASharedTokenOf32CharactersStartsWithoutTheWarning(t *testing.T) { + a := startAgent(t, "AGENT_TOKEN", strings.Repeat("s", 32)) + log := a.log.String() + if !strings.Contains(log, "AGENT_TOKEN is set") { + t.Fatalf("the log lacks the notice about the shared token: %s", log) + } + if strings.Contains(log, "AGENT_TOKEN is short") { + t.Fatalf("a shared token of 32 characters was called short: %s", log) + } +} + func TestAFreshAgentSaysHowToPairAndPrintsNoCode(t *testing.T) { a := startAgent(t) log := a.log.String() @@ -272,6 +313,75 @@ func TestAFreshAgentSaysHowToPairAndPrintsNoCode(t *testing.T) { } } +func TestTheServerLogDropsFailedHandshakesAndKeepsTheRest(t *testing.T) { + var out syncBuf + w := serverLog{slog.New(slog.NewTextHandler(&out, nil))} + + // What net/http writes about a scanner that does not speak TLS. + handshake := []byte("http: TLS handshake error from 203.0.113.9:40000: tls: first record does not look like a TLS handshake\n") + if n, err := w.Write(handshake); n != len(handshake) || err != nil { + t.Fatalf("Write = %d, %v", n, err) + } + if out.String() != "" { + t.Fatalf("a failed handshake was logged: %s", out.String()) + } + + for name, c := range map[string]struct { + report string + want []string // what the log must hold of it + }{ + "the panic of a handler": { + "http: panic serving 203.0.113.9:40000: boom\ngoroutine 7 [running]:\nmain.handler()\n", + []string{"http: panic serving 203.0.113.9:40000: boom", "main.handler()"}, + }, + "an accept that fails": { + "http: Accept error: accept tcp [::]:8443: accept4: too many open files; retrying in 1s\n", + []string{"http: Accept error: accept tcp [::]:8443: accept4: too many open files; retrying in 1s"}, + }, + } { + before := out.String() + if n, err := w.Write([]byte(c.report)); n != len(c.report) || err != nil { + t.Fatalf("%s: Write = %d, %v", name, n, err) + } + logged := strings.TrimPrefix(out.String(), before) + if !strings.Contains(logged, "level=ERROR") { + t.Errorf("%s is not logged as an error: %q", name, logged) + } + for _, want := range c.want { + if !strings.Contains(logged, want) { + t.Errorf("%s: the log lacks %q: %q", name, want, logged) + } + } + if strings.Count(logged, "\n") != 1 { + t.Errorf("%s does not take exactly one line of the log: %q", name, logged) + } + } +} + +func TestGarbageOnTheTLSPortLeavesNoLineAndTheAgentKeepsServing(t *testing.T) { + a := startAgent(t) + conn, err := net.Dial("tcp", a.addr) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(3 * time.Second)) + if _, err := conn.Write([]byte("this is not a TLS handshake\r\n")); err != nil { + t.Fatal(err) + } + // The agent gives the connection up; by then it has reported whatever it + // reports about it. + if _, err := io.Copy(io.Discard, conn); errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatal("the agent kept a connection that does not speak TLS") + } + if got := a.pinned("").status("GET", "/healthz"); got != http.StatusOK { + t.Fatalf("after the garbage: /healthz = %d, want 200", got) + } + if log := a.log.String(); strings.Contains(log, "handshake") || strings.Contains(log, "level=ERROR") { + t.Fatalf("the failed handshake is in the log: %s", log) + } +} + func TestTheFingerprintCommandPrintsWhatThePortPresents(t *testing.T) { a := startAgent(t) p := newPhone(t, "https", a.addr) @@ -358,6 +468,44 @@ func TestStoppingTheAgentEndsStreamsAndCleansUp(t *testing.T) { } } +func TestStoppingTheAgentEndsAnOpenTerminal(t *testing.T) { + // A terminal is a connection the handler has taken over: stopping the + // HTTP server neither waits for it nor closes it. + a := startAgent(t, "AGENT_TOKEN", shared) + p := a.pinned(shared) + dialer := websocket.Dialer{ + TLSClientConfig: p.client.Transport.(*http.Transport).TLSClientConfig, + HandshakeTimeout: 3 * time.Second, + } + id := strings.Repeat("0123456789abcdef", 4) + ws, _, err := dialer.Dial("wss://"+a.addr+"/exec/"+id+"/ws", http.Header{"Authorization": {"Bearer " + p.token}}) + if err != nil { + t.Fatalf("open the terminal: %v", err) + } + defer ws.Close() + ws.SetReadDeadline(time.Now().Add(3 * time.Second)) + if _, data, err := ws.ReadMessage(); err != nil || string(data) != terminalGreeting { + t.Fatalf("the terminal is not through to the daemon: %q, %v", data, err) + } + ws.SetReadDeadline(time.Time{}) + + if err := a.stop(); err != nil { + t.Fatalf("serve returned %v", err) + } + // The daemon sends nothing more, so a read that returns means that the + // terminal is over. + ended := make(chan struct{}) + go func() { + ws.ReadMessage() + close(ended) + }() + select { + case <-ended: + case <-time.After(3 * time.Second): + t.Fatal("the terminal outlived the agent") + } +} + func TestASecondAgentOnTheSameFolderIsRefused(t *testing.T) { a := startAgent(t) env := func(k string) string { @@ -379,6 +527,12 @@ func TestASecondAgentIsRefusedBeforeItTouchesTheState(t *testing.T) { if err := os.WriteFile(filepath.Join(a.env["AGENT_DATA"], "devices.json"), []byte("{"), 0o600); err != nil { t.Fatal(err) } + // And take the certificate away. A second agent that loaded its identity + // before taking the admin socket would issue a new one. + certificate := filepath.Join(a.env["AGENT_DATA"], "tls.crt") + if err := os.Remove(certificate); err != nil { + t.Fatal(err) + } env := func(k string) string { if k == "AGENT_LISTEN" { return "127.0.0.1:0" @@ -389,6 +543,9 @@ func TestASecondAgentIsRefusedBeforeItTouchesTheState(t *testing.T) { if code := run(context.Background(), []string{"serve"}, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "already running") { t.Fatalf("a second agent: exit %d, %s", code, errOut.String()) } + if _, err := os.Stat(certificate); !os.IsNotExist(err) { + t.Fatalf("the agent that was refused wrote a certificate: %v", err) + } } func TestTheStateFolderStaysLockedUntilRequestsHaveStopped(t *testing.T) { @@ -408,9 +565,37 @@ func TestTheStateFolderStaysLockedUntilRequestsHaveStopped(t *testing.T) { t.Fatalf("the stream did not start: %v", err) } + // A pair command that waits for its phone. + waiting := make(chan struct{}) + pairEnded := make(chan error, 1) + go func() { + pairEnded <- admin.NewClient(a.env["AGENT_DATA"]).Pair(context.Background(), admin.PairRequest{}, func(e admin.Event) { + if e.Event == admin.EventStarted { + close(waiting) + } + }) + }() + select { + case <-waiting: + case err := <-pairEnded: + t.Fatalf("the pairing ended before it began to wait: %v", err) + case <-time.After(3 * time.Second): + t.Fatal("the pairing did not start") + } + a.cancel() waitFor(t, "the agent to begin stopping", func() bool { return strings.Contains(a.log.String(), "stopping") }) + // The pair command hears of it now, not when the grace is over. + select { + case err := <-pairEnded: + if !errors.Is(err, admin.ErrStopped) { + t.Fatalf("the waiting pairing ended with %v, want %v", err, admin.ErrStopped) + } + case <-time.After(time.Second): + t.Fatal("the waiting pairing did not end when the agent began to stop") + } + // The first agent is still letting its stream finish. A second one on the // same folder must be refused now; if it were let in, it would serve // until its own context ends and exit cleanly. @@ -513,7 +698,7 @@ func TestCommandLine(t *testing.T) { {name: "help", args: []string{"help"}, code: 0, inStdout: "docker-mobile-agent fingerprint"}, {name: "version", args: []string{"version"}, code: 0, inStdout: "docker-mobile-agent dev (commit "}, {name: "fingerprint before the first run", args: []string{"fingerprint"}, code: 1, inStderr: "no certificate"}, - {name: "a short shared token", env: []string{"AGENT_TOKEN", "too-short"}, code: 1, inStderr: "AGENT_TOKEN is too short (9 characters)"}, + {name: "a short shared token", env: []string{"AGENT_TOKEN", "too-short"}, code: 1, inStderr: "AGENT_TOKEN is too short: use at least 16 characters"}, {name: "a bad listen address", args: []string{"serve"}, env: []string{"AGENT_LISTEN", "nope"}, code: 1, inStderr: "AGENT_LISTEN"}, {name: "a bad flag for serve", args: []string{"--verbose"}, code: 1, inStderr: "flag provided but not defined"}, {name: "healthcheck without an agent", args: []string{"healthcheck", "--insecure-http"}, env: []string{"AGENT_LISTEN", "127.0.0.1:1"}, code: 1}, diff --git a/agent/cmd/agent/serve.go b/agent/cmd/agent/serve.go index a5fc3a7..6439d20 100644 --- a/agent/cmd/agent/serve.go +++ b/agent/cmd/agent/serve.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "crypto/rand" "crypto/tls" @@ -14,6 +15,7 @@ import ( "net/http" "os" "os/signal" + "strings" "syscall" "time" @@ -32,6 +34,17 @@ import ( // that tests can shorten it. var shutdownGrace = 5 * time.Second +// serverLog hands what net/http reports to the agent's log, except failed +// TLS handshakes: on an open port those are mostly scanners. +type serverLog struct{ log *slog.Logger } + +func (w serverLog) Write(p []byte) (int, error) { + if !bytes.HasPrefix(p, []byte("http: TLS handshake error")) { + w.log.Error(strings.TrimSpace(string(p))) + } + return len(p), nil +} + func cmdServe(ctx context.Context, args []string, getenv func(string) string, stderr io.Writer) error { fs := flag.NewFlagSet("serve", flag.ContinueOnError) fs.SetOutput(stderr) @@ -45,6 +58,10 @@ func cmdServe(ctx context.Context, args []string, getenv func(string) string, st } ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) defer stop() + // Once the agent has been told to stop, the signals get their default + // behaviour back: a second interrupt ends the process at once instead of + // being swallowed while the first one is still being acted on. + context.AfterFunc(ctx, stop) return serve(ctx, cfg, slog.New(slog.NewTextHandler(stderr, nil)), nil) } @@ -62,12 +79,10 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu if err != nil { return err } - adminServing := false - defer func() { - if !adminServing { - adminLn.Close() - } - }() + // However this function ends, the socket is removed and the folder given + // up. On the ordinary way out the admin server has closed the listener + // before; closing it a second time does nothing. + defer adminLn.Close() devices, err := state.LoadDevices(dir, time.Now) if err != nil { return err @@ -130,17 +145,27 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu ln = tls.NewListener(ln, tlsid.ServerConfig(cert)) } - // The standard library reports every failed TLS handshake through - // ErrorLog; on an open port that is mostly scanners, so it is dropped. - quiet := log.New(io.Discard, "", 0) + // What net/http has to report, such as the panic of a handler or an + // accept that fails, goes to the agent's log. The logger adds nothing in + // front of a report: serverLog tells failed handshakes by how they start. + errorLog := log.New(serverLog{logger}, "", 0) srv := &http.Server{ Handler: handler, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second, MaxHeaderBytes: 64 << 10, - ErrorLog: quiet, + ErrorLog: errorLog, + } + // Requests on the admin socket end when the agent begins to stop. The + // socket itself stays to the end, and with it the lock on the folder. + adminCtx, endAdminRequests := context.WithCancel(context.Background()) + defer endAdminRequests() + adminSrv := &http.Server{ + Handler: adminServer.Handler(), + ReadHeaderTimeout: 10 * time.Second, + ErrorLog: errorLog, + BaseContext: func(net.Listener) context.Context { return adminCtx }, } - adminSrv := &http.Server{Handler: adminServer.Handler(), ReadHeaderTimeout: 10 * time.Second, ErrorLog: quiet} logger.Info("docker-mobile-agent started", "version", version, "listen", ln.Addr().String(), "docker", cfg.DockerHost, "data", cfg.DataDir) switch { @@ -152,7 +177,9 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu if cfg.LegacyToken != "" { logger.Info("AGENT_TOKEN is set: it gives full control to whoever holds it; pairing gives each phone its own revocable token") if len(cfg.LegacyToken) < config.WeakLegacyToken { - logger.Warn("AGENT_TOKEN is short; use at least 32 characters", "length", len(cfg.LegacyToken)) + // The length itself stays out of the log: the authentication + // takes care that it cannot be learned from outside. + logger.Warn("AGENT_TOKEN is short; use at least 32 characters") } } if cfg.LegacyToken == "" && len(devices.List()) == 0 { @@ -161,7 +188,6 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu errc := make(chan error, 2) go func() { errc <- srv.Serve(ln) }() - adminServing = true go func() { errc <- adminSrv.Serve(adminLn) }() if ready != nil { ready(ln.Addr()) @@ -174,6 +200,10 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu } logger.Info("stopping") + // A pair command that is waiting ends now and not after the grace: no + // phone could use its code any more. One that starts from here on ends + // at once for the same reason. + endAdminRequests() grace, cancel := context.WithTimeout(context.Background(), shutdownGrace) defer cancel() // Stop accepting and let short requests finish. Streams and terminals @@ -181,11 +211,17 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu // clients see the connection close instead of hanging. shutdownErr := srv.Shutdown(grace) registry.CloseAll() - srv.Close() + // What fails on the way out is reported, unless it only says that the + // thing was closed already. + report := func(what string, err error) { + if err != nil && !errors.Is(err, net.ErrClosed) { + logger.Warn(what, "error", err) + } + } + report("stopping: closing the server failed", srv.Close()) // The admin socket goes last: closing it gives up the lock on the state - // folder, and until here a request could still write there. It also ends - // a pair command that is still waiting. - adminSrv.Close() + // folder, and until here a request could still write there. + report("stopping: closing the admin socket failed", adminSrv.Close()) if serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) { return serveErr } diff --git a/agent/internal/config/config.go b/agent/internal/config/config.go index a77056e..1486a70 100644 --- a/agent/internal/config/config.go +++ b/agent/internal/config/config.go @@ -6,6 +6,7 @@ import ( "fmt" "net" "strings" + "unicode" "github.com/retransmit/docker-mobile/agent/internal/state" ) @@ -41,10 +42,14 @@ type Config struct { // Load builds a Config from getenv. insecureFlag is the --insecure-http // flag; AGENT_INSECURE_HTTP=1 means the same. func Load(getenv func(string) string, insecureFlag bool) (Config, error) { + insecureEnv, err := onOff("AGENT_INSECURE_HTTP", getenv("AGENT_INSECURE_HTTP")) + if err != nil { + return Config{}, err + } cfg := Config{ ListenAddr: getenv("AGENT_LISTEN"), DockerHost: getenv("DOCKER_HOST"), - InsecureHTTP: insecureFlag || truthy(getenv("AGENT_INSECURE_HTTP")), + InsecureHTTP: insecureFlag || insecureEnv, LegacyToken: getenv("AGENT_TOKEN"), Name: strings.TrimSpace(getenv("AGENT_NAME")), } @@ -58,11 +63,8 @@ func Load(getenv func(string) string, insecureFlag bool) (Config, error) { cfg.DockerHost = defaultDockerHost } cfg.DataDir = DataDir(getenv) - if n := len(cfg.LegacyToken); n > 0 && n < MinLegacyToken { - return Config{}, fmt.Errorf("AGENT_TOKEN is too short (%d characters): use at least %d, or remove it and pair devices instead", n, MinLegacyToken) - } - if state.IsDeviceToken(cfg.LegacyToken) { - return Config{}, errors.New("AGENT_TOKEN must not start with \"dm1.\": that prefix marks the tokens of paired devices") + if err := checkLegacyToken(cfg.LegacyToken); err != nil { + return Config{}, err } _, listenPort, err := net.SplitHostPort(cfg.ListenAddr) if err != nil { @@ -84,10 +86,52 @@ func DataDir(getenv func(string) string) string { return defaultDataDir } -func truthy(v string) bool { - switch strings.ToLower(strings.TrimSpace(v)) { +// checkLegacyToken refuses a shared token that is too short, that could not +// match, or that would be taken for the token of a device. No token at all +// is fine. Its errors say what is wrong without the token and without its +// length: they end up in a log, and the authentication takes care that the +// length cannot be learned from outside. +func checkLegacyToken(token string) error { + if token == "" { + return nil + } + // A phone sends neither white space around its token nor a control + // character in it, so no request would ever match such a token, with + // nothing but a 401 to show for it. The usual cause is the carriage + // return that an env file written on Windows leaves at the end of the + // line. This comes before the length: the hidden character would count + // toward it. + wrong := "" + switch { + case strings.TrimLeftFunc(token, unicode.IsSpace) != token: + wrong = "starts with white space" + case strings.TrimRightFunc(token, unicode.IsSpace) != token: + wrong = "ends with white space" + case strings.IndexFunc(token, unicode.IsControl) >= 0: + wrong = "contains a control character" + } + if wrong != "" { + return fmt.Errorf("AGENT_TOKEN %s: a phone does not send that, so the token would never match; look for a stray space or a line ending in the value", wrong) + } + if len(token) < MinLegacyToken { + return fmt.Errorf("AGENT_TOKEN is too short: use at least %d characters, or remove it and pair devices instead", MinLegacyToken) + } + if state.IsDeviceToken(token) { + return errors.New("AGENT_TOKEN must not start with \"dm1.\": that prefix marks the tokens of paired devices") + } + return nil +} + +// onOff reads a switch from the environment. No value is off; 1, true, yes +// and on are on; 0, false, no and off are off, in any case and with white +// space around them. Anything else is an error that names the variable and +// the value: a mistyped switch must not pass for off. +func onOff(name, value string) (bool, error) { + switch strings.ToLower(strings.TrimSpace(value)) { + case "", "0", "false", "no", "off": + return false, nil case "1", "true", "yes", "on": - return true + return true, nil } - return false + return false, fmt.Errorf("%s %q is neither on nor off: use 1, true, yes or on, or 0, false, no or off", name, value) } diff --git a/agent/internal/config/config_test.go b/agent/internal/config/config_test.go index f681cec..8dc3c2e 100644 --- a/agent/internal/config/config_test.go +++ b/agent/internal/config/config_test.go @@ -75,7 +75,76 @@ func TestEverySettingIsRead(t *testing.T) { func TestAShortSharedTokenStopsTheAgent(t *testing.T) { _, err := Load(env("AGENT_TOKEN", "fifteen-chars-x"), false) - if err == nil || !strings.Contains(err.Error(), "too short (15 characters)") { + if err == nil || !strings.Contains(err.Error(), "AGENT_TOKEN is too short") { + t.Fatalf("err = %v", err) + } + // The error ends up in a log, where neither the token nor its length + // belongs. + if strings.Contains(err.Error(), "15") || strings.Contains(err.Error(), "fifteen") { + t.Fatalf("the error gives away the token or its length: %v", err) + } +} + +func TestASharedTokenWithWhiteSpaceAroundItOrAControlCharacterStopsTheAgent(t *testing.T) { + const token = "sEcReT-0123456789abcdef" + for name, c := range map[string]struct{ value, wrong string }{ + "a carriage return at the end": {token + "\r", "ends with white space"}, + "a line feed at the end": {token + "\n", "ends with white space"}, + "a space at the end": {token + " ", "ends with white space"}, + "a space at the start": {" " + token, "starts with white space"}, + "a tab at the start": {"\t" + token, "starts with white space"}, + "a zero byte inside": {"sEcReT-01234\x0056789abcdef", "contains a control character"}, + "a line feed inside": {"sEcReT-01234\n56789abcdef", "contains a control character"}, + "nothing but white space": {" ", "starts with white space"}, + // Fifteen characters and a carriage return: that must neither pass + // for sixteen nor be called short. + "a short one with a carriage return": {"sEcReT-01234567\r", "ends with white space"}, + } { + _, err := Load(env("AGENT_TOKEN", c.value), false) + if err == nil { + t.Errorf("%s: accepted", name) + continue + } + if !strings.Contains(err.Error(), "AGENT_TOKEN") || !strings.Contains(err.Error(), c.wrong) { + t.Errorf("%s: err = %v, want one that names AGENT_TOKEN and says that it %s", name, err, c.wrong) + } + if strings.Contains(err.Error(), "sEcReT") { + t.Errorf("%s: the error prints the token: %v", name, err) + } + } + // White space inside a token is the user's choice. + if _, err := Load(env("AGENT_TOKEN", "correct horse battery staple"), false); err != nil { + t.Fatalf("a token with spaces inside: %v", err) + } +} + +func TestTheSwitchForPlainHTTPIsReadStrictly(t *testing.T) { + for _, v := range []string{"1", "true", "TRUE", "yes", "Yes", "on", " ON "} { + cfg, err := Load(env("AGENT_INSECURE_HTTP", v), false) + if err != nil || !cfg.InsecureHTTP { + t.Errorf("%q: plain HTTP = %v, err = %v; want it on", v, cfg.InsecureHTTP, err) + } + } + for _, v := range []string{"", " ", "0", "false", "False", "no", "off", " OFF "} { + cfg, err := Load(env("AGENT_INSECURE_HTTP", v), false) + if err != nil || cfg.InsecureHTTP { + t.Errorf("%q: plain HTTP = %v, err = %v; want it off", v, cfg.InsecureHTTP, err) + } + } + for _, v := range []string{"2", "enabled", "tru", "y", "of"} { + // With the flag given as well: that does not excuse a mistyped value. + for _, flag := range []bool{false, true} { + _, err := Load(env("AGENT_INSECURE_HTTP", v), flag) + if err == nil || !strings.Contains(err.Error(), "AGENT_INSECURE_HTTP") || !strings.Contains(err.Error(), `"`+v+`"`) { + t.Errorf("%q (flag %v): err = %v, want one that names AGENT_INSECURE_HTTP and the value", v, flag, err) + } + } + } +} + +func TestABadAdvertisedAddressIsAnErrorThatNamesTheVariable(t *testing.T) { + _, err := Load(env("AGENT_ADVERTISE", "my-server.lan:99999"), false) + if err == nil || !strings.Contains(err.Error(), "AGENT_ADVERTISE") || !strings.Contains(err.Error(), "99999") { t.Fatalf("err = %v", err) } } diff --git a/agent/internal/server/handler_test.go b/agent/internal/server/handler_test.go index a85e530..2435dfe 100644 --- a/agent/internal/server/handler_test.go +++ b/agent/internal/server/handler_test.go @@ -157,6 +157,9 @@ func TestTheProxyNeedsCredentials(t *testing.T) { if rec := f.do("GET", "/containers/json", "", nil); rec.Code != http.StatusUnauthorized { t.Fatalf("code = %d, want 401", rec.Code) } + if rec := f.do("GET", "/exec/abc/ws", "", nil); rec.Code != http.StatusUnauthorized { + t.Fatalf("the terminal route without a token: code = %d, want 401", rec.Code) + } if rec := f.do("GET", "/containers/json", legacy, nil); rec.Code != http.StatusOK { t.Fatalf("shared token: code = %d, want 200", rec.Code) } From a9129f0d32e6b6a155eb062bf5622aad3a2bf1f4 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 18:44:09 +0530 Subject: [PATCH 22/32] feat(agent): pair, devices and revoke commands --- README.md | 23 ++ agent/cmd/agent/admin_commands.go | 129 ++++++++++ agent/cmd/agent/main.go | 10 + agent/cmd/agent/pair_test.go | 403 ++++++++++++++++++++++++++++++ 4 files changed, 565 insertions(+) create mode 100644 agent/cmd/agent/admin_commands.go create mode 100644 agent/cmd/agent/pair_test.go diff --git a/README.md b/README.md index 096d2ce..74b1f19 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,29 @@ AGENT_DATA=./.agent-data AGENT_TOKEN=replace-me-with-32-or-more-characters go ru ``` That listens on `:8080`. `go run ./cmd/agent help` lists every command and setting. +Pair a phone with the running agent, then list or remove paired phones: +``` +AGENT_DATA=./.agent-data go run ./cmd/agent pair +AGENT_DATA=./.agent-data go run ./cmd/agent devices +AGENT_DATA=./.agent-data go run ./cmd/agent revoke +``` + +`pair --read-only` pairs a phone that may look but not change anything. It +can still see everything: lists, logs, and the full inspect output, which +includes every container's environment variables. Two consequences when +the agent itself runs in a container: + +- Do not give the agent `AGENT_TOKEN` through its container's environment. + A read-only phone could read it there, and that token gives full + control. Pair phones instead. +- Run `pair` inside the running agent's container, never as the main + process of a container of its own: + ``` + docker exec -it docker-mobile-agent pair + ``` + A container's main process writes to that container's log, and the + pairing code would be readable there for as long as it is valid. + ## Run the app (dev) ``` cd app diff --git a/agent/cmd/agent/admin_commands.go b/agent/cmd/agent/admin_commands.go new file mode 100644 index 0000000..0149efd --- /dev/null +++ b/agent/cmd/agent/admin_commands.go @@ -0,0 +1,129 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "os/signal" + "syscall" + "text/tabwriter" + + "github.com/retransmit/docker-mobile/agent/internal/admin" + "github.com/retransmit/docker-mobile/agent/internal/config" + "github.com/retransmit/docker-mobile/agent/internal/qr" +) + +func accessLabel(role string) string { + if role == "readonly" { + return "read-only" + } + return "full control" +} + +func cmdPair(ctx context.Context, args []string, getenv func(string) string, stdout io.Writer) error { + fs := flag.NewFlagSet("pair", flag.ContinueOnError) + fs.SetOutput(io.Discard) + readOnly := fs.Bool("read-only", false, "pair a phone that may look but not change anything") + name := fs.String("name", "", "name for the phone (default: what the phone calls itself)") + host := fs.String("host", "", "address phones reach this agent at, host or host:port") + invert := fs.Bool("invert", false, "draw the QR code for a light terminal") + noQR := fs.Bool("no-qr", false, "do not draw the QR code") + if err := fs.Parse(args); err != nil { + return fmt.Errorf("pair: %v", err) + } + if fs.NArg() > 0 { + return fmt.Errorf("pair: unexpected argument %q", fs.Arg(0)) + } + req := admin.PairRequest{Name: *name, Host: *host} + if *readOnly { + req.Role = "readonly" + } + ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) + defer stop() + + var end admin.Event + err := admin.NewClient(config.DataDir(getenv)).Pair(ctx, req, func(e admin.Event) { + if e.Event != admin.EventStarted { + end = e + return + } + if !*noQR { + fmt.Fprintln(stdout, "Scan this with the docker-mobile app (Connections, Add, Scan QR code):") + fmt.Fprintln(stdout) + if err := qr.Render(stdout, e.Link, *invert); err != nil { + fmt.Fprintln(stdout, "(the QR code could not be drawn:", err.Error()+")") + } + fmt.Fprintln(stdout) + fmt.Fprintln(stdout, "Or enter it by hand:") + } + address := e.Address + if address == "" { + address = "(enter this server's address in the app; AGENT_ADVERTISE or --host puts it in the code)" + } + fmt.Fprintln(stdout, " Address: "+address) + fmt.Fprintln(stdout, " Code: "+e.Code) + if e.Fingerprint != "" { + fmt.Fprintln(stdout, " Fingerprint: "+e.Fingerprint) + } + fmt.Fprintln(stdout, " Access: "+accessLabel(e.Role)) + fmt.Fprintln(stdout) + fmt.Fprintln(stdout, "Or open this link on the phone:") + fmt.Fprintln(stdout, " "+e.Link) + fmt.Fprintln(stdout) + fmt.Fprintf(stdout, "The code works once and expires in %d minutes. Waiting for the phone (Ctrl-C cancels)...\n", (e.ExpiresIn+59)/60) + }) + if errors.Is(err, context.Canceled) { + return errors.New("pairing cancelled; the code no longer works") + } + if err != nil { + return err + } + switch end.Event { + case "paired": + fmt.Fprintf(stdout, "Paired: %s (id %s, %s)\n", end.Device.Name, end.Device.ID, accessLabel(end.Device.Role)) + return nil + case "expired": + return errors.New("the code expired before a phone used it; run pair again") + case "replaced": + return errors.New("another pair command replaced this code") + case "voided": + return errors.New("too many wrong attempts: the code was voided; run pair again") + case "failed": + return fmt.Errorf("the phone proved the code but the agent could not store it: %s", end.Error) + default: + return fmt.Errorf("pairing ended as %q", end.Event) + } +} + +func cmdDevices(ctx context.Context, getenv func(string) string, stdout io.Writer) error { + list, err := admin.NewClient(config.DataDir(getenv)).Devices(ctx) + if err != nil { + return err + } + if len(list) == 0 { + fmt.Fprintln(stdout, "No phone is paired. Run: docker-mobile-agent pair") + return nil + } + tw := tabwriter.NewWriter(stdout, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, "ID\tNAME\tACCESS\tPAIRED\tLAST SEEN") + for _, d := range list { + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", d.ID, d.Name, accessLabel(d.Role), + d.CreatedAt.Local().Format("2006-01-02 15:04"), d.LastSeenAt.Local().Format("2006-01-02 15:04")) + } + return tw.Flush() +} + +func cmdRevoke(ctx context.Context, args []string, getenv func(string) string, stdout io.Writer) error { + if len(args) != 1 || args[0] == "" { + return errors.New("revoke: give the id of one device (see: docker-mobile-agent devices)") + } + dev, closed, err := admin.NewClient(config.DataDir(getenv)).Revoke(ctx, args[0]) + if err != nil { + return err + } + fmt.Fprintf(stdout, "Revoked %s (id %s); closed %d open connection(s).\n", dev.Name, dev.ID, closed) + return nil +} diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go index 2f5e5fd..05c4b23 100644 --- a/agent/cmd/agent/main.go +++ b/agent/cmd/agent/main.go @@ -17,6 +17,10 @@ const usage = `docker-mobile-agent - lets the docker-mobile app control this Doc Usage: docker-mobile-agent [serve] [--insecure-http] run the agent (default) + docker-mobile-agent pair [--read-only] [--name NAME] [--host ADDR] [--invert] [--no-qr] + pair a phone with the running agent + docker-mobile-agent devices list paired phones + docker-mobile-agent revoke ID remove a paired phone docker-mobile-agent fingerprint print the certificate fingerprint docker-mobile-agent healthcheck [--insecure-http] exit 0 when the agent answers @@ -46,6 +50,12 @@ func run(ctx context.Context, args []string, getenv func(string) string, stdout, switch cmd { case "serve": err = cmdServe(ctx, rest, getenv, stderr) + case "pair": + err = cmdPair(ctx, rest, getenv, stdout) + case "devices": + err = cmdDevices(ctx, getenv, stdout) + case "revoke": + err = cmdRevoke(ctx, rest, getenv, stdout) case "fingerprint": err = cmdFingerprint(getenv, stdout) case "healthcheck": diff --git a/agent/cmd/agent/pair_test.go b/agent/cmd/agent/pair_test.go new file mode 100644 index 0000000..4723554 --- /dev/null +++ b/agent/cmd/agent/pair_test.go @@ -0,0 +1,403 @@ +package main + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/tls" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httputil" + "net/url" + "regexp" + "strings" + "testing" + "time" + + "github.com/retransmit/docker-mobile/agent/internal/pairing" + "github.com/retransmit/docker-mobile/agent/internal/state" + "github.com/retransmit/docker-mobile/agent/internal/tlsid" +) + +var ( + linkInOutput = regexp.MustCompile(`dockermobile://pair\?\S+`) + codeInOutput = regexp.MustCompile(`Code:\s+(\S+)`) +) + +// startPair runs "pair" in the background and returns once it has printed +// its code and link. +func (a *agent) startPair(args ...string) (link, code string, out *syncBuf, exit <-chan int) { + a.t.Helper() + out = &syncBuf{} + done := make(chan int, 1) + go func() { + done <- run(context.Background(), append([]string{"pair", "--no-qr"}, args...), a.getenv, out, out) + }() + waitFor(a.t, "the pairing code", func() bool { return strings.Contains(out.String(), "Waiting for the phone") }) + return linkInOutput.FindString(out.String()), codeInOutput.FindStringSubmatch(out.String())[1], out, done +} + +// pair runs the proof exchange with a typed code. The fingerprint in the +// proof is whatever this connection presented, which is what makes a relay +// useless. +func (p *phone) pair(code, name string) (status int, err error) { + canonical, ok := pairing.Normalize(code) + if !ok { + return 0, fmt.Errorf("bad code %q", code) + } + var fp []byte + if p.scheme == "https" { + // Learn what the server presents before computing the proof. + probe, err := p.do(http.MethodGet, "/healthz", nil) + if err != nil { + return 0, err + } + probe.Body.Close() + fp = p.seen[:] + } + nonce := make([]byte, pairing.NonceLen) + rand.Read(nonce) + body, _ := json.Marshal(map[string]any{ + "v": 1, + "nonce": base64.RawURLEncoding.EncodeToString(nonce), + "proof": base64.RawURLEncoding.EncodeToString(pairing.PhoneProof(canonical, fp, nonce)), + "name": name, + }) + resp, err := p.do(http.MethodPost, "/agent/v1/pair", body) + if err != nil { + return 0, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return resp.StatusCode, nil + } + var got struct { + Nonce, Proof, Token string + } + if err := json.NewDecoder(resp.Body).Decode(&got); err != nil { + return 0, err + } + agentNonce, _ := base64.RawURLEncoding.DecodeString(got.Nonce) + proof, _ := base64.RawURLEncoding.DecodeString(got.Proof) + if !bytes.Equal(proof, pairing.AgentProof(canonical, fp, nonce, agentNonce)) { + return 0, errors.New("the server could not prove it holds the code") + } + if p.scheme == "https" { + pinned := p.seen + p.pin = &pinned + } + p.token = got.Token + return http.StatusOK, nil +} + +// pairWithLink is the QR path: the fingerprint comes from the link, and the +// phone refuses any other certificate from the first byte on. +func (p *phone) pairWithLink(link, name string) (int, error) { + u, err := url.Parse(link) + if err != nil { + return 0, err + } + q := u.Query() + if f := q.Get("f"); f != "" { + raw, err := base64.RawURLEncoding.DecodeString(f) + if err != nil || len(raw) != 32 { + return 0, fmt.Errorf("bad fingerprint in the link: %q", f) + } + var pin tlsid.Fingerprint + copy(pin[:], raw) + p.pin = &pin + } + return p.pair(q.Get("c"), name) +} + +func TestPairUseAndRevokeOverTLS(t *testing.T) { + a := startAgent(t) + + // A read-only phone pairs by scanning. + link, _, out, exit := a.startPair("--read-only") + port := a.addr[strings.LastIndex(a.addr, ":")+1:] + for _, want := range []string{"h=127.0.0.1", "p=" + port, "n=test+agent", "f=" + a.fingerprint().String(), "c="} { + if !strings.Contains(link, want) { + t.Fatalf("the link lacks %s: %s", want, link) + } + } + viewer := newPhone(t, "https", a.addr) + if status, err := viewer.pairWithLink(link, "Pixel 8"); err != nil || status != http.StatusOK { + t.Fatalf("pairing by link: %d, %v", status, err) + } + if code := <-exit; code != 0 { + t.Fatalf("pair exited %d: %s", code, out.String()) + } + for _, want := range []string{"Paired: Pixel 8", "read-only", "Address: 127.0.0.1:" + port, "Fingerprint: " + a.fingerprint().Display()} { + if !strings.Contains(out.String(), want) { + t.Fatalf("the pair output lacks %q:\n%s", want, out.String()) + } + } + if got := viewer.status("GET", "/v1.45/containers/json"); got != http.StatusOK { + t.Fatalf("a read: %d, want 200", got) + } + if got := viewer.status("POST", "/v1.45/containers/x/start"); got != http.StatusForbidden { + t.Fatalf("a write from a read-only phone: %d, want 403", got) + } + + // A second phone pairs with the typed code, knowing no fingerprint. + _, code, out2, exit2 := a.startPair("--name", "kitchen tablet") + full := newPhone(t, "https", a.addr) + if status, err := full.pair(code, "whatever the phone says"); err != nil || status != http.StatusOK { + t.Fatalf("pairing by code: %d, %v", status, err) + } + if code := <-exit2; code != 0 { + t.Fatalf("pair exited %d: %s", code, out2.String()) + } + if !strings.Contains(out2.String(), "Paired: kitchen tablet") || !strings.Contains(out2.String(), "full control") { + t.Fatalf("pair output: %s", out2.String()) + } + if *full.pin != a.fingerprint() { + t.Fatal("the phone pinned something other than the agent's fingerprint") + } + if got := full.status("POST", "/containers/x/start"); got != http.StatusOK { + t.Fatalf("a write from a full phone: %d, want 200", got) + } + + // Both show up in the list, and nothing secret anywhere. + _, list, _ := a.command("devices") + for _, want := range []string{"Pixel 8", "read-only", "kitchen tablet", "full control"} { + if !strings.Contains(list, want) { + t.Fatalf("the devices output lacks %q:\n%s", want, list) + } + } + canonical, _ := pairing.Normalize(code) + for _, secret := range []string{viewer.token, full.token, code, canonical} { + if strings.Contains(list, secret) || strings.Contains(a.log.String(), secret) { + t.Fatal("a token or a code leaked into the output or the log") + } + } + + // Revoking a phone ends its open stream and its access. + stream, err := viewer.do("GET", "/events", nil) + if err != nil { + t.Fatal(err) + } + defer stream.Body.Close() + if _, err := io.ReadFull(stream.Body, make([]byte, 1)); err != nil { + t.Fatalf("the stream did not start: %v", err) + } + id := regexp.MustCompile(`(?m)^([0-9a-f]{8})\s+Pixel 8`).FindStringSubmatch(list)[1] + exitCode, revokeOut, errOut := a.command("revoke", id) + if exitCode != 0 || !strings.Contains(revokeOut, "Revoked Pixel 8") || !strings.Contains(revokeOut, "closed 1 open connection") { + t.Fatalf("revoke: %d %q %q", exitCode, revokeOut, errOut) + } + ended := make(chan struct{}) + go func() { + io.Copy(io.Discard, stream.Body) + close(ended) + }() + select { + case <-ended: + case <-time.After(3 * time.Second): + t.Fatal("the stream of the revoked phone stayed open") + } + if got := viewer.status("GET", "/containers/json"); got != http.StatusUnauthorized { + t.Fatalf("a revoked phone: %d, want 401", got) + } + if got := full.status("GET", "/containers/json"); got != http.StatusOK { + t.Fatalf("the other phone was affected: %d", got) + } + if exitCode, _, errOut := a.command("revoke", id); exitCode != 1 || !strings.Contains(errOut, "no device") { + t.Fatalf("revoking twice: %d %q", exitCode, errOut) + } +} + +func TestSomeoneInTheMiddleCannotPair(t *testing.T) { + a := startAgent(t) + + // The attacker terminates TLS with a certificate of their own and + // passes everything on to the real agent. + attackerDir, err := state.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + attackerCert, err := tlsid.LoadOrCreate(attackerDir, time.Now()) + if err != nil { + t.Fatal(err) + } + target, _ := url.Parse("https://" + a.addr) + relay := httputil.NewSingleHostReverseProxy(target) + // The attacker does not care who it talks to. + relay.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} + ln, err := tls.Listen("tcp", "127.0.0.1:0", tlsid.ServerConfig(attackerCert)) + if err != nil { + t.Fatal(err) + } + relaySrv := &http.Server{Handler: relay} + go relaySrv.Serve(ln) + defer relaySrv.Close() + + _, code, _, _ := a.startPair() + victim := newPhone(t, "https", ln.Addr().String()) + status, err := victim.pair(code, "Pixel 8") + if err != nil { + t.Fatalf("pairing through the relay: %v", err) + } + if status != http.StatusForbidden { + t.Fatalf("the agent answered %d to a relayed proof, want 403", status) + } + if victim.token != "" || victim.pin != nil { + t.Fatal("the phone trusted the attacker") + } + if _, list, _ := a.command("devices"); !strings.Contains(list, "No phone is paired") { + t.Fatalf("a device was created through the relay:\n%s", list) + } + + // Straight to the agent the same code still works: one wrong try does + // not void it. + direct := newPhone(t, "https", a.addr) + if status, err := direct.pair(code, "Pixel 8"); err != nil || status != http.StatusOK { + t.Fatalf("pairing directly afterwards: %d, %v", status, err) + } +} + +func TestAScannedCodeNeverReachesAnotherCertificate(t *testing.T) { + a := startAgent(t) + link, _, _, _ := a.startPair() + + // Another agent, with another key, answers where the phone connects. + other := startAgent(t) + p := newPhone(t, "https", other.addr) + if _, err := p.pairWithLink(link, "Pixel 8"); err == nil || !strings.Contains(err.Error(), "server identity changed") { + t.Fatalf("err = %v, want the pin from the link to refuse the other certificate", err) + } + if strings.Contains(other.log.String(), "/agent/v1/pair") { + t.Fatal("the pairing request was sent to the wrong server") + } +} + +func TestAPairedPhoneSurvivesARestartAndRefusesAnotherKey(t *testing.T) { + a := startAgent(t) + link, _, _, exit := a.startPair() + p := newPhone(t, "https", a.addr) + if _, err := p.pairWithLink(link, "Pixel 8"); err != nil { + t.Fatal(err) + } + <-exit + a.stop() + if code, _, errOut := a.command("devices"); code != 1 || !strings.Contains(errOut, "not running") { + t.Fatalf("devices against a stopped agent: %d %q", code, errOut) + } + + // The same folder starts again on the same address: the phone is known. + again := startAgent(t, "AGENT_DATA", a.env["AGENT_DATA"], "AGENT_LISTEN", a.addr) + if got := p.status("GET", "/containers/json"); got != http.StatusOK { + t.Fatalf("after a restart the paired phone gets %d", got) + } + again.stop() + + // A different agent takes over the address: the pin refuses it. + startAgent(t, "AGENT_LISTEN", a.addr) + if _, err := p.do("GET", "/containers/json", nil); err == nil || !strings.Contains(err.Error(), "server identity changed") { + t.Fatalf("err = %v, want the pin to refuse the new certificate", err) + } +} + +func TestPairingBehindAProxy(t *testing.T) { + a := startAgent(t, "AGENT_INSECURE_HTTP", "1", "AGENT_ADVERTISE", "https://docker.example.com") + link, code, out, exit := a.startPair() + if !strings.Contains(link, "s=https") || !strings.Contains(link, "h=docker.example.com") || !strings.Contains(link, "p=443") || strings.Contains(link, "f=") { + t.Fatalf("link = %s", link) + } + if strings.Contains(out.String(), "Fingerprint:") || !strings.Contains(out.String(), "Address: https://docker.example.com:443") { + t.Fatalf("pair output:\n%s", out.String()) + } + p := newPhone(t, "http", a.addr) + if status, err := p.pair(code, "Pixel 8"); err != nil || status != http.StatusOK { + t.Fatalf("pairing over plain HTTP: %d, %v", status, err) + } + if got := <-exit; got != 0 { + t.Fatalf("pair exited %d", got) + } + if got := p.status("GET", "/containers/json"); got != http.StatusOK { + t.Fatalf("code = %d, want 200", got) + } +} + +func TestPairWithoutAnAdvertisedAddressSaysWhatToDo(t *testing.T) { + a := startAgent(t, "AGENT_ADVERTISE", "") + link, _, out, _ := a.startPair() + if strings.Contains(link, "h=") || !strings.Contains(out.String(), "AGENT_ADVERTISE or --host") { + t.Fatalf("link = %s\noutput:\n%s", link, out.String()) + } + link, _, out, _ = a.startPair("--host", "my-server.lan:9443") + if !strings.Contains(link, "h=my-server.lan") || !strings.Contains(link, "p=9443") || !strings.Contains(out.String(), "Address: my-server.lan:9443") { + t.Fatalf("link = %s\noutput:\n%s", link, out.String()) + } +} + +func TestPairDrawsAQRCodeAndLeavingItCancelsTheCode(t *testing.T) { + a := startAgent(t) + out := &syncBuf{} + ctx, cancel := context.WithCancel(context.Background()) + exit := make(chan int, 1) + go func() { exit <- run(ctx, []string{"pair"}, a.getenv, out, out) }() + waitFor(t, "the pair output", func() bool { return strings.Contains(out.String(), "Waiting for the phone") }) + if !strings.Contains(out.String(), "\u2588") || !strings.Contains(out.String(), "Scan this with the docker-mobile app") { + t.Fatalf("no QR code in the output:\n%s", out.String()) + } + code := codeInOutput.FindStringSubmatch(out.String())[1] + + cancel() // Ctrl-C + if got := <-exit; got != 1 || !strings.Contains(out.String(), "pairing cancelled") { + t.Fatalf("exit %d: %s", got, out.String()) + } + waitFor(t, "the agent to cancel the pairing", func() bool { return strings.Contains(a.log.String(), "outcome=cancelled") }) + p := newPhone(t, "https", a.addr) + if status, err := p.pair(code, "x"); err != nil || status != http.StatusNotFound { + t.Fatalf("the cancelled code: %d, %v, want 404", status, err) + } + if _, list, _ := a.command("devices"); !strings.Contains(list, "No phone is paired") { + t.Fatalf("a device was created with a cancelled code: %s", list) + } +} + +func TestStoppingTheAgentEndsAPendingPairCommand(t *testing.T) { + a := startAgent(t) + _, code, out, exit := a.startPair() + a.stop() + select { + case got := <-exit: + if got != 1 || !strings.Contains(out.String(), "the agent stopped before the pairing ended") { + t.Fatalf("exit %d: %s", got, out.String()) + } + case <-time.After(3 * time.Second): + t.Fatal("the pair command kept waiting for a stopped agent") + } + // The code died with the agent: a restart does not bring it back. + again := startAgent(t, "AGENT_DATA", a.env["AGENT_DATA"]) + p := newPhone(t, "https", again.addr) + if status, err := p.pair(code, "x"); err != nil || status != http.StatusNotFound { + t.Fatalf("the old code after a restart: %d, %v, want 404", status, err) + } +} + +func TestPairCommandLine(t *testing.T) { + runCommandCases(t, []commandCase{ + {name: "help lists the pairing commands", args: []string{"help"}, code: 0, inStdout: "docker-mobile-agent pair"}, + {name: "devices without an agent", args: []string{"devices"}, code: 1, inStderr: "not running"}, + {name: "pair without an agent", args: []string{"pair"}, code: 1, inStderr: "not running"}, + {name: "revoke without an agent", args: []string{"revoke", "abcd1234"}, code: 1, inStderr: "not running"}, + {name: "revoke without an id", args: []string{"revoke"}, code: 1, inStderr: "give the id"}, + {name: "revoke with two ids", args: []string{"revoke", "a", "b"}, code: 1, inStderr: "give the id"}, + {name: "pair with a stray argument", args: []string{"pair", "now"}, code: 1, inStderr: `unexpected argument "now"`}, + {name: "pair with an unknown flag", args: []string{"pair", "--admin"}, code: 1, inStderr: "pair:"}, + }) +} + +func TestPairRejectsABadHost(t *testing.T) { + a := startAgent(t) + if code, _, errOut := a.command("pair", "--host", "https://x"); code != 1 || !strings.Contains(errOut, "without a scheme") { + t.Fatalf("exit %d: %s", code, errOut) + } +} From fc7dcf89b6c8f11314fb3c20ea546c2e04101615 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 19:28:15 +0530 Subject: [PATCH 23/32] fix(agent): honest pair and revoke messages, help flags, a stricter test phone --- README.md | 8 +- agent/cmd/agent/admin_commands.go | 52 ++- agent/cmd/agent/commands.go | 20 +- agent/cmd/agent/main.go | 86 +++- agent/cmd/agent/main_test.go | 85 +++- agent/cmd/agent/pair_test.go | 620 +++++++++++++++++++++++++++-- agent/cmd/agent/serve.go | 5 +- agent/internal/admin/admin.go | 5 +- agent/internal/admin/admin_test.go | 85 ++++ agent/internal/admin/client.go | 19 +- 10 files changed, 904 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index 74b1f19..b3153a4 100644 --- a/README.md +++ b/README.md @@ -32,10 +32,10 @@ AGENT_DATA=./.agent-data go run ./cmd/agent devices AGENT_DATA=./.agent-data go run ./cmd/agent revoke ``` -`pair --read-only` pairs a phone that may look but not change anything. It -can still see everything: lists, logs, and the full inspect output, which -includes every container's environment variables. Two consequences when -the agent itself runs in a container: +`pair --read-only` pairs a phone that can change nothing. It can read the +lists, the logs and the full inspect output of containers, which includes +their environment variables. Two consequences when the agent itself runs +in a container: - Do not give the agent `AGENT_TOKEN` through its container's environment. A read-only phone could read it there, and that token gives full diff --git a/agent/cmd/agent/admin_commands.go b/agent/cmd/agent/admin_commands.go index 0149efd..caace94 100644 --- a/agent/cmd/agent/admin_commands.go +++ b/agent/cmd/agent/admin_commands.go @@ -25,17 +25,14 @@ func accessLabel(role string) string { func cmdPair(ctx context.Context, args []string, getenv func(string) string, stdout io.Writer) error { fs := flag.NewFlagSet("pair", flag.ContinueOnError) - fs.SetOutput(io.Discard) readOnly := fs.Bool("read-only", false, "pair a phone that may look but not change anything") - name := fs.String("name", "", "name for the phone (default: what the phone calls itself)") - host := fs.String("host", "", "address phones reach this agent at, host or host:port") + // The word in back quotes is what the help shows as the flag's value. + name := fs.String("name", "", "`NAME` for the phone (default: what the phone calls itself)") + host := fs.String("host", "", "`ADDR` at which phones reach this agent, host or host:port") invert := fs.Bool("invert", false, "draw the QR code for a light terminal") noQR := fs.Bool("no-qr", false, "do not draw the QR code") - if err := fs.Parse(args); err != nil { - return fmt.Errorf("pair: %v", err) - } - if fs.NArg() > 0 { - return fmt.Errorf("pair: unexpected argument %q", fs.Arg(0)) + if done, err := parseArgs(fs, args, "pair [--read-only] [--name NAME] [--host ADDR] [--invert] [--no-qr]", stdout); done || err != nil { + return err } req := admin.PairRequest{Name: *name, Host: *host} if *readOnly { @@ -44,10 +41,11 @@ func cmdPair(ctx context.Context, args []string, getenv func(string) string, std ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) defer stop() - var end admin.Event + // end is the event that ended the pairing; nil for as long as none has. + var end *admin.Event err := admin.NewClient(config.DataDir(getenv)).Pair(ctx, req, func(e admin.Event) { if e.Event != admin.EventStarted { - end = e + end = &e return } if !*noQR { @@ -75,14 +73,27 @@ func cmdPair(ctx context.Context, args []string, getenv func(string) string, std fmt.Fprintln(stdout) fmt.Fprintf(stdout, "The code works once and expires in %d minutes. Waiting for the phone (Ctrl-C cancels)...\n", (e.ExpiresIn+59)/60) }) - if errors.Is(err, context.Canceled) { - return errors.New("pairing cancelled; the code no longer works") - } - if err != nil { + if end == nil { + // The pairing did not end where this command could see it, so the + // command does not know whether a phone was paired. The agent uses + // the code up and stores the device before it answers the phone: a + // phone can have paired in the very moment the command was + // interrupted or the agent stopped. + switch { + case errors.Is(err, context.Canceled): + return errors.New(`pairing cancelled; the code no longer works. If a phone used it in the same moment it is paired: check with "docker-mobile-agent devices"`) + case err == nil, errors.Is(err, admin.ErrStopped): + return fmt.Errorf(`%w; the code no longer works. If a phone used it in the same moment it is paired, and still is when the agent runs again: check then with "docker-mobile-agent devices"`, admin.ErrStopped) + } return err } + // How the pairing ended is reported whatever err says: a phone that was + // paired is paired, also when the command was interrupted just then. switch end.Event { case "paired": + if end.Device == nil { + return errors.New(`the agent says a phone was paired, but not which one: look at "docker-mobile-agent devices"`) + } fmt.Fprintf(stdout, "Paired: %s (id %s, %s)\n", end.Device.Name, end.Device.ID, accessLabel(end.Device.Role)) return nil case "expired": @@ -98,7 +109,10 @@ func cmdPair(ctx context.Context, args []string, getenv func(string) string, std } } -func cmdDevices(ctx context.Context, getenv func(string) string, stdout io.Writer) error { +func cmdDevices(ctx context.Context, args []string, getenv func(string) string, stdout io.Writer) error { + if done, err := parseArgs(flag.NewFlagSet("devices", flag.ContinueOnError), args, "devices", stdout); done || err != nil { + return err + } list, err := admin.NewClient(config.DataDir(getenv)).Devices(ctx) if err != nil { return err @@ -117,10 +131,14 @@ func cmdDevices(ctx context.Context, getenv func(string) string, stdout io.Write } func cmdRevoke(ctx context.Context, args []string, getenv func(string) string, stdout io.Writer) error { - if len(args) != 1 || args[0] == "" { + fs := flag.NewFlagSet("revoke", flag.ContinueOnError) + if done, err := parseFlags(fs, args, "revoke ID", stdout); done || err != nil { + return err + } + if fs.NArg() != 1 || fs.Arg(0) == "" { return errors.New("revoke: give the id of one device (see: docker-mobile-agent devices)") } - dev, closed, err := admin.NewClient(config.DataDir(getenv)).Revoke(ctx, args[0]) + dev, closed, err := admin.NewClient(config.DataDir(getenv)).Revoke(ctx, fs.Arg(0)) if err != nil { return err } diff --git a/agent/cmd/agent/commands.go b/agent/cmd/agent/commands.go index 0d50e5f..c21fdad 100644 --- a/agent/cmd/agent/commands.go +++ b/agent/cmd/agent/commands.go @@ -17,7 +17,10 @@ import ( "github.com/retransmit/docker-mobile/agent/internal/tlsid" ) -func cmdFingerprint(getenv func(string) string, stdout io.Writer) error { +func cmdFingerprint(args []string, getenv func(string) string, stdout io.Writer) error { + if done, err := parseArgs(flag.NewFlagSet("fingerprint", flag.ContinueOnError), args, "fingerprint", stdout); done || err != nil { + return err + } dataDir := config.DataDir(getenv) fp, err := tlsid.ReadFingerprint(dataDir) if errors.Is(err, os.ErrNotExist) { @@ -32,12 +35,11 @@ func cmdFingerprint(getenv func(string) string, stdout io.Writer) error { // cmdHealthcheck asks the agent on this machine for /healthz. Over TLS it // trusts exactly the certificate in the state folder. -func cmdHealthcheck(ctx context.Context, args []string, getenv func(string) string) error { +func cmdHealthcheck(ctx context.Context, args []string, getenv func(string) string, stdout io.Writer) error { fs := flag.NewFlagSet("healthcheck", flag.ContinueOnError) - fs.SetOutput(io.Discard) insecure := fs.Bool("insecure-http", false, "the agent serves plain HTTP") - if err := fs.Parse(args); err != nil { - return fmt.Errorf("healthcheck: %v", err) + if done, err := parseArgs(fs, args, "healthcheck [--insecure-http]", stdout); done || err != nil { + return err } cfg, err := config.Load(getenv, *insecure) if err != nil { @@ -76,6 +78,14 @@ func cmdHealthcheck(ctx context.Context, args []string, getenv func(string) stri return nil } +func cmdVersion(args []string, stdout io.Writer) error { + if done, err := parseArgs(flag.NewFlagSet("version", flag.ContinueOnError), args, "version", stdout); done || err != nil { + return err + } + fmt.Fprintln(stdout, versionLine()) + return nil +} + func versionLine() string { commit, built := "unknown", "unknown" if info, ok := debug.ReadBuildInfo(); ok { diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go index 05c4b23..0ffaec8 100644 --- a/agent/cmd/agent/main.go +++ b/agent/cmd/agent/main.go @@ -4,6 +4,8 @@ package main import ( "context" + "errors" + "flag" "fmt" "io" "os" @@ -25,13 +27,18 @@ Usage: docker-mobile-agent healthcheck [--insecure-http] exit 0 when the agent answers docker-mobile-agent version print the version + docker-mobile-agent help show this text + +Every command shows its flags with --help. Environment: AGENT_LISTEN listen address (default :8443, or :8080 with --insecure-http) AGENT_DATA state folder (default /var/lib/docker-mobile-agent) AGENT_ADVERTISE address phones reach the agent at, for pairing codes AGENT_NAME name shown on the phone while pairing (default: host name) - AGENT_INSECURE_HTTP 1 = serve plain HTTP, behind a proxy that terminates TLS + AGENT_INSECURE_HTTP 1, true, yes or on: serve plain HTTP, behind a proxy that + terminates TLS (the same as --insecure-http); 0, false, + no, off or not set: no effect; any other value is an error AGENT_TOKEN shared token of older setups (at least 16 characters) DOCKER_HOST Docker daemon (default unix:///var/run/docker.sock) ` @@ -42,26 +49,33 @@ func main() { // run executes one command and returns the process exit code. func run(ctx context.Context, args []string, getenv func(string) string, stdout, stderr io.Writer) int { + // Without a command the agent serves, and what is given are the flags of + // serve. Help asked for in that place is the help for all of it. cmd, rest := "serve", args - if len(args) > 0 && !strings.HasPrefix(args[0], "-") { - cmd, rest = args[0], args[1:] + if len(args) > 0 { + switch { + case isHelpFlag(args[0]): + cmd, rest = "help", args[1:] + case !strings.HasPrefix(args[0], "-"): + cmd, rest = args[0], args[1:] + } } var err error switch cmd { case "serve": - err = cmdServe(ctx, rest, getenv, stderr) + err = cmdServe(ctx, rest, getenv, stdout, stderr) case "pair": err = cmdPair(ctx, rest, getenv, stdout) case "devices": - err = cmdDevices(ctx, getenv, stdout) + err = cmdDevices(ctx, rest, getenv, stdout) case "revoke": err = cmdRevoke(ctx, rest, getenv, stdout) case "fingerprint": - err = cmdFingerprint(getenv, stdout) + err = cmdFingerprint(rest, getenv, stdout) case "healthcheck": - err = cmdHealthcheck(ctx, rest, getenv) + err = cmdHealthcheck(ctx, rest, getenv, stdout) case "version": - fmt.Fprintln(stdout, versionLine()) + err = cmdVersion(rest, stdout) case "help": fmt.Fprint(stdout, usage) default: @@ -74,3 +88,59 @@ func run(ctx context.Context, args []string, getenv func(string) string, stdout, } return 0 } + +// isHelpFlag reports whether arg is one of the spellings the flag package +// takes for a request for help. +func isHelpFlag(arg string) bool { + switch arg { + case "-h", "--h", "-help", "--help": + return true + } + return false +} + +// parseFlags reads the flags of one command from args. synopsis is how the +// command is called, as the usage text has it. When the arguments ask for +// help, the command's own help goes to stdout and done is true: the command +// has nothing left to do. What follows the flags stays in fs.Args for the +// caller. +// +// The help is all that is ever written here. The flag package would print +// every mistake itself, with the list of flags after it; the mistake comes +// back as the error instead, and whoever called the command prints it once. +func parseFlags(fs *flag.FlagSet, args []string, synopsis string, stdout io.Writer) (done bool, err error) { + fs.SetOutput(io.Discard) + err = fs.Parse(args) + if errors.Is(err, flag.ErrHelp) { + fmt.Fprintf(stdout, "Usage: docker-mobile-agent %s\n", synopsis) + first := true + fs.VisitAll(func(f *flag.Flag) { + if first { + fmt.Fprint(stdout, "\nFlags:\n") + first = false + } + value, about := flag.UnquoteUsage(f) + if value != "" { + value = " " + value + } + fmt.Fprintf(stdout, " --%s%s\n %s\n", f.Name, value, about) + }) + return true, nil + } + if err != nil { + return false, fmt.Errorf("%s: %v (see: docker-mobile-agent %s --help)", fs.Name(), err, fs.Name()) + } + return false, nil +} + +// parseArgs is parseFlags for a command that takes nothing besides flags: +// anything else on its command line is refused. +func parseArgs(fs *flag.FlagSet, args []string, synopsis string, stdout io.Writer) (done bool, err error) { + if done, err := parseFlags(fs, args, synopsis, stdout); done || err != nil { + return done, err + } + if fs.NArg() > 0 { + return false, fmt.Errorf("%s: unexpected argument %q (see: docker-mobile-agent %s --help)", fs.Name(), fs.Arg(0), fs.Name()) + } + return false, nil +} diff --git a/agent/cmd/agent/main_test.go b/agent/cmd/agent/main_test.go index f856e6b..186c2d7 100644 --- a/agent/cmd/agent/main_test.go +++ b/agent/cmd/agent/main_test.go @@ -243,7 +243,13 @@ func (a *agent) pinned(token string) *phone { } func (p *phone) do(method, path string, body []byte) (*http.Response, error) { - req, err := http.NewRequest(method, p.scheme+"://"+p.addr+path, bytes.NewReader(body)) + return p.doWithin(context.Background(), method, path, body) +} + +// doWithin is do for a request that ends with ctx, the reading of its answer +// included. +func (p *phone) doWithin(ctx context.Context, method, path string, body []byte) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, method, p.scheme+"://"+p.addr+path, bytes.NewReader(body)) if err != nil { return nil, err } @@ -669,6 +675,7 @@ type commandCase struct { code int inStdout string inStderr string + stderrIs string // when not empty, all that standard error may hold } func runCommandCases(t *testing.T, cases []commandCase) { @@ -689,6 +696,9 @@ func runCommandCases(t *testing.T, cases []commandCase) { if c.inStderr != "" && !strings.Contains(errOut.String(), c.inStderr) { t.Errorf("%s: stderr lacks %q: %s", c.name, c.inStderr, errOut.String()) } + if c.stderrIs != "" && errOut.String() != c.stderrIs { + t.Errorf("%s: stderr is %q, want %q", c.name, errOut.String(), c.stderrIs) + } } } @@ -696,11 +706,82 @@ func TestCommandLine(t *testing.T) { runCommandCases(t, []commandCase{ {name: "unknown command", args: []string{"frobnicate"}, code: 2, inStderr: `unknown command "frobnicate"`}, {name: "help", args: []string{"help"}, code: 0, inStdout: "docker-mobile-agent fingerprint"}, + {name: "help lists itself", args: []string{"help"}, code: 0, inStdout: "docker-mobile-agent help "}, + {name: "help says how the switch for plain HTTP is read", args: []string{"help"}, code: 0, inStdout: "AGENT_INSECURE_HTTP 1, true, yes or on: serve plain HTTP"}, {name: "version", args: []string{"version"}, code: 0, inStdout: "docker-mobile-agent dev (commit "}, {name: "fingerprint before the first run", args: []string{"fingerprint"}, code: 1, inStderr: "no certificate"}, {name: "a short shared token", env: []string{"AGENT_TOKEN", "too-short"}, code: 1, inStderr: "AGENT_TOKEN is too short: use at least 16 characters"}, {name: "a bad listen address", args: []string{"serve"}, env: []string{"AGENT_LISTEN", "nope"}, code: 1, inStderr: "AGENT_LISTEN"}, - {name: "a bad flag for serve", args: []string{"--verbose"}, code: 1, inStderr: "flag provided but not defined"}, + {name: "a bad flag for serve", args: []string{"--verbose"}, code: 1, + stderrIs: "docker-mobile-agent: serve: flag provided but not defined: -verbose (see: docker-mobile-agent serve --help)\n"}, + {name: "a bad flag for healthcheck", args: []string{"healthcheck", "--verbose"}, code: 1, + stderrIs: "docker-mobile-agent: healthcheck: flag provided but not defined: -verbose (see: docker-mobile-agent healthcheck --help)\n"}, {name: "healthcheck without an agent", args: []string{"healthcheck", "--insecure-http"}, env: []string{"AGENT_LISTEN", "127.0.0.1:1"}, code: 1}, + {name: "serve with a stray argument", args: []string{"serve", "extra"}, code: 1, + stderrIs: "docker-mobile-agent: serve: unexpected argument \"extra\" (see: docker-mobile-agent serve --help)\n"}, + {name: "a command after a flag", args: []string{"--insecure-http", "healthcheck"}, code: 1, inStderr: `serve: unexpected argument "healthcheck"`}, + {name: "fingerprint with a stray argument", args: []string{"fingerprint", "extra"}, code: 1, inStderr: `fingerprint: unexpected argument "extra"`}, + {name: "healthcheck with a stray argument", args: []string{"healthcheck", "extra"}, code: 1, inStderr: `healthcheck: unexpected argument "extra"`}, + {name: "version with a stray argument", args: []string{"version", "extra"}, code: 1, inStderr: `version: unexpected argument "extra"`}, }) } + +func TestHelpAtTheTopIsTheUsageText(t *testing.T) { + for _, args := range [][]string{{"--help"}, {"-h"}, {"help"}} { + var out, errOut bytes.Buffer + code := run(context.Background(), args, func(string) string { return "" }, &out, &errOut) + if code != 0 || out.String() != usage || errOut.Len() != 0 { + t.Errorf("%v: exit %d, stdout %q, stderr %q", args, code, out.String(), errOut.String()) + } + } +} + +func TestEveryCommandShowsItsOwnHelp(t *testing.T) { + for _, c := range []struct { + command string + synopsis string // how the command is called, as the usage text has it + flags []string // every flag with its description, as the help shows it + }{ + {"serve", "docker-mobile-agent [serve] [--insecure-http]", []string{ + " --insecure-http\n serve plain HTTP, behind a proxy that terminates TLS\n", + }}, + {"pair", "docker-mobile-agent pair [--read-only] [--name NAME] [--host ADDR] [--invert] [--no-qr]", []string{ + " --read-only\n pair a phone that may look but not change anything\n", + " --name NAME\n NAME for the phone (default: what the phone calls itself)\n", + " --host ADDR\n ADDR at which phones reach this agent, host or host:port\n", + " --invert\n draw the QR code for a light terminal\n", + " --no-qr\n do not draw the QR code\n", + }}, + {"devices", "docker-mobile-agent devices", nil}, + {"revoke", "docker-mobile-agent revoke ID", nil}, + {"fingerprint", "docker-mobile-agent fingerprint", nil}, + {"healthcheck", "docker-mobile-agent healthcheck [--insecure-http]", []string{ + " --insecure-http\n the agent serves plain HTTP\n", + }}, + {"version", "docker-mobile-agent version", nil}, + } { + if !strings.Contains(usage, "\n "+c.synopsis) { + t.Errorf("%s: the usage text does not show the command as %q", c.command, c.synopsis) + } + for _, help := range []string{"--help", "-h"} { + var out, errOut bytes.Buffer + // No environment: a command that did more than show its help + // would fail on it, or would not return. + code := run(context.Background(), []string{c.command, help}, func(string) string { return "" }, &out, &errOut) + if code != 0 || errOut.Len() != 0 { + t.Errorf("%s %s: exit %d, stderr %q", c.command, help, code, errOut.String()) + } + if !strings.HasPrefix(out.String(), "Usage: "+c.synopsis+"\n") { + t.Errorf("%s %s: the help does not begin with how the command is called: %q", c.command, help, out.String()) + } + for _, want := range c.flags { + if !strings.Contains(out.String(), want) { + t.Errorf("%s %s: the help lacks %q: %q", c.command, help, want, out.String()) + } + } + if strings.Contains(out.String(), "Flags:") != (len(c.flags) > 0) { + t.Errorf("%s %s: the help is wrong about whether the command has flags: %q", c.command, help, out.String()) + } + } + } +} diff --git a/agent/cmd/agent/pair_test.go b/agent/cmd/agent/pair_test.go index 4723554..f67d140 100644 --- a/agent/cmd/agent/pair_test.go +++ b/agent/cmd/agent/pair_test.go @@ -3,21 +3,29 @@ package main import ( "bytes" "context" + "crypto/hmac" "crypto/rand" + "crypto/sha256" "crypto/tls" "encoding/base64" "encoding/json" "errors" "fmt" "io" + "log" + "net" "net/http" "net/http/httputil" "net/url" + "os" + "path/filepath" "regexp" "strings" + "sync" "testing" "time" + "github.com/retransmit/docker-mobile/agent/internal/admin" "github.com/retransmit/docker-mobile/agent/internal/pairing" "github.com/retransmit/docker-mobile/agent/internal/state" "github.com/retransmit/docker-mobile/agent/internal/tlsid" @@ -41,23 +49,70 @@ func (a *agent) startPair(args ...string) (link, code string, out *syncBuf, exit return linkInOutput.FindString(out.String()), codeInOutput.FindStringSubmatch(out.String())[1], out, done } -// pair runs the proof exchange with a typed code. The fingerprint in the -// proof is whatever this connection presented, which is what makes a relay -// useless. +// exited waits for a pair command that runs in the background to end and +// returns its exit code. +func exited(t *testing.T, exit <-chan int) int { + t.Helper() + select { + case code := <-exit: + return code + case <-time.After(5 * time.Second): + t.Fatal("the pair command did not end") + return -1 + } +} + +// pairTimeout is how long the phone gives one pairing attempt. An agent +// needs a few hundredths of a second to check a proof and store a device. +// Whoever holds the connection open instead of answering holds a proof to +// test guesses of the code against, and must not get to choose how long. +const pairTimeout = 5 * time.Second + +// pair runs the proof exchange with a typed code. func (p *phone) pair(code, name string) (status int, err error) { + return p.pairWithin(pairTimeout, code, name) +} + +// pairWithin is pair with the time the whole attempt may take. +// +// A proof is good for one certificate. It must therefore travel on a +// connection that presented that certificate and no other: a proof made for +// the agent's certificate and sent over a connection that someone else +// terminated is all that person needs to pair in the phone's place. This +// phone opens a connection for every request, so it first looks at what the +// server presents and then pins exactly that for the rest of the attempt. +// The connection that carries the proof then presents the same key or fails +// its handshake before anything is sent on it. +// +// Nothing is kept unless the answer proves that the server holds the code +// too. Whenever the attempt does not end that way the phone is left as it +// was: without a token, and with the pin it had before or none. +func (p *phone) pairWithin(limit time.Duration, code, name string) (status int, err error) { canonical, ok := pairing.Normalize(code) if !ok { return 0, fmt.Errorf("bad code %q", code) } + ctx, cancel := context.WithTimeout(context.Background(), limit) + defer cancel() + + before, paired := p.pin, false + defer func() { + if !paired { + p.pin = before + } + }() var fp []byte if p.scheme == "https" { - // Learn what the server presents before computing the proof. - probe, err := p.do(http.MethodGet, "/healthz", nil) + probe, err := p.doWithin(ctx, http.MethodGet, "/healthz", nil) if err != nil { return 0, err } probe.Body.Close() - fp = p.seen[:] + // A copy: every later handshake writes to p.seen, also one that the + // pin then refuses. + presented := p.seen + p.pin = &presented + fp = presented[:] } nonce := make([]byte, pairing.NonceLen) rand.Read(nonce) @@ -67,7 +122,7 @@ func (p *phone) pair(code, name string) (status int, err error) { "proof": base64.RawURLEncoding.EncodeToString(pairing.PhoneProof(canonical, fp, nonce)), "name": name, }) - resp, err := p.do(http.MethodPost, "/agent/v1/pair", body) + resp, err := p.doWithin(ctx, http.MethodPost, "/agent/v1/pair", body) if err != nil { return 0, err } @@ -81,27 +136,33 @@ func (p *phone) pair(code, name string) (status int, err error) { if err := json.NewDecoder(resp.Body).Decode(&got); err != nil { return 0, err } - agentNonce, _ := base64.RawURLEncoding.DecodeString(got.Nonce) - proof, _ := base64.RawURLEncoding.DecodeString(got.Proof) - if !bytes.Equal(proof, pairing.AgentProof(canonical, fp, nonce, agentNonce)) { - return 0, errors.New("the server could not prove it holds the code") + // The lengths come first: the proof is computed over the two nonces one + // after the other, which says what it should only for nonces of the + // length both sides agreed on. + agentNonce, errNonce := base64.RawURLEncoding.DecodeString(got.Nonce) + proof, errProof := base64.RawURLEncoding.DecodeString(got.Proof) + if errNonce != nil || errProof != nil || len(agentNonce) != pairing.NonceLen || len(proof) != sha256.Size { + return 0, errors.New("the server's answer is malformed: its nonce or its proof is not 32 bytes") } - if p.scheme == "https" { - pinned := p.seen - p.pin = &pinned + if !hmac.Equal(proof, pairing.AgentProof(canonical, fp, nonce, agentNonce)) { + return 0, errors.New("the server could not prove it holds the code") } + // Only now does the phone trust the certificate and keep the token. + paired = true p.token = got.Token return http.StatusOK, nil } // pairWithLink is the QR path: the fingerprint comes from the link, and the -// phone refuses any other certificate from the first byte on. +// phone refuses any other certificate from the first byte on. A pin from a +// link is kept only together with the pairing it was for. func (p *phone) pairWithLink(link, name string) (int, error) { u, err := url.Parse(link) if err != nil { return 0, err } q := u.Query() + before := p.pin if f := q.Get("f"); f != "" { raw, err := base64.RawURLEncoding.DecodeString(f) if err != nil || len(raw) != 32 { @@ -111,14 +172,18 @@ func (p *phone) pairWithLink(link, name string) (int, error) { copy(pin[:], raw) p.pin = &pin } - return p.pair(q.Get("c"), name) + status, err := p.pair(q.Get("c"), name) + if err != nil || status != http.StatusOK { + p.pin = before + } + return status, err } func TestPairUseAndRevokeOverTLS(t *testing.T) { a := startAgent(t) // A read-only phone pairs by scanning. - link, _, out, exit := a.startPair("--read-only") + link, firstCode, out, exit := a.startPair("--read-only") port := a.addr[strings.LastIndex(a.addr, ":")+1:] for _, want := range []string{"h=127.0.0.1", "p=" + port, "n=test+agent", "f=" + a.fingerprint().String(), "c="} { if !strings.Contains(link, want) { @@ -129,7 +194,7 @@ func TestPairUseAndRevokeOverTLS(t *testing.T) { if status, err := viewer.pairWithLink(link, "Pixel 8"); err != nil || status != http.StatusOK { t.Fatalf("pairing by link: %d, %v", status, err) } - if code := <-exit; code != 0 { + if code := exited(t, exit); code != 0 { t.Fatalf("pair exited %d: %s", code, out.String()) } for _, want := range []string{"Paired: Pixel 8", "read-only", "Address: 127.0.0.1:" + port, "Fingerprint: " + a.fingerprint().Display()} { @@ -150,7 +215,7 @@ func TestPairUseAndRevokeOverTLS(t *testing.T) { if status, err := full.pair(code, "whatever the phone says"); err != nil || status != http.StatusOK { t.Fatalf("pairing by code: %d, %v", status, err) } - if code := <-exit2; code != 0 { + if code := exited(t, exit2); code != 0 { t.Fatalf("pair exited %d: %s", code, out2.String()) } if !strings.Contains(out2.String(), "Paired: kitchen tablet") || !strings.Contains(out2.String(), "full control") { @@ -170,10 +235,21 @@ func TestPairUseAndRevokeOverTLS(t *testing.T) { t.Fatalf("the devices output lacks %q:\n%s", want, list) } } - canonical, _ := pairing.Normalize(code) - for _, secret := range []string{viewer.token, full.token, code, canonical} { + secrets := []string{viewer.token, full.token} + for _, shown := range []string{firstCode, code} { + canonical, _ := pairing.Normalize(shown) + secrets = append(secrets, shown, canonical) + } + for _, secret := range secrets { if strings.Contains(list, secret) || strings.Contains(a.log.String(), secret) { - t.Fatal("a token or a code leaked into the output or the log") + t.Fatal("a token or a code leaked into the devices output or the log") + } + } + // The pair command shows its code. A device token never reaches it, so + // nothing that looks like one may be in what it printed. + for _, printed := range []string{out.String(), out2.String()} { + if strings.Contains(printed, "dm1.") { + t.Fatal("a device token is in the output of the pair command") } } @@ -261,6 +337,268 @@ func TestSomeoneInTheMiddleCannotPair(t *testing.T) { } } +// strangerCert makes a certificate with a key of its own, as anyone can. +func strangerCert(t *testing.T) tls.Certificate { + t.Helper() + dir, err := state.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + cert, err := tlsid.LoadOrCreate(dir, time.Now()) + if err != nil { + t.Fatal(err) + } + return cert +} + +// passFirst hands the first connection it accepts to pass and every later +// one to whoever accepts from it. +type passFirst struct { + net.Listener + once sync.Once + pass func(net.Conn) +} + +func (l *passFirst) Accept() (net.Conn, error) { + for { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + passed := false + l.once.Do(func() { + passed = true + go l.pass(conn) + }) + if !passed { + return conn, nil + } + } +} + +// tunnel joins conn to the server at addr and moves the bytes both ways +// until one side ends. It looks into nothing: whoever is on conn sees the +// certificate of the server at addr. +func tunnel(conn net.Conn, addr string) { + defer conn.Close() + upstream, err := net.Dial("tcp", addr) + if err != nil { + return + } + defer upstream.Close() + ended := make(chan struct{}, 2) + go func() { io.Copy(upstream, conn); ended <- struct{}{} }() + go func() { io.Copy(conn, upstream); ended <- struct{}{} }() + <-ended +} + +func TestARelayThatOnlyTerminatesTheProofConnectionGetsNothing(t *testing.T) { + a := startAgent(t) + + // The attacker lets the first connection through untouched, so a phone + // that looks at the certificate there sees the agent's. Every later + // connection it terminates with a certificate of its own and hands what + // it reads to the agent: a proof made for the agent's certificate would + // be accepted there, and the token in the answer would be the attacker's. + target, _ := url.Parse("https://" + a.addr) + forward := httputil.NewSingleHostReverseProxy(target) + forward.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} + var reached syncBuf // what the phone sent on a connection the attacker terminated + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + relaySrv := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(&reached, r.Method, r.URL.Path) + forward.ServeHTTP(w, r) + }), + // A handshake the phone refuses is what this test is about. + ErrorLog: log.New(io.Discard, "", 0), + } + split := &passFirst{Listener: ln, pass: func(conn net.Conn) { tunnel(conn, a.addr) }} + go relaySrv.Serve(tls.NewListener(split, tlsid.ServerConfig(strangerCert(t)))) + defer relaySrv.Close() + + _, code, out, exit := a.startPair() + victim := newPhone(t, "https", ln.Addr().String()) + if status, err := victim.pair(code, "Pixel 8"); err == nil || !strings.Contains(err.Error(), "server identity changed") { + t.Errorf("status %d, err = %v, want the phone to refuse the connection that presents another certificate", status, err) + } + if victim.token != "" || victim.pin != nil { + t.Error("the phone kept a token or a pin from the attempt through the relay") + } + if got := reached.String(); got != "" { + t.Errorf("the phone sent this on a connection the attacker terminated:\n%s", got) + } + if strings.Contains(a.log.String(), "/agent/v1/pair") { + t.Error("a pairing request reached the agent through the relay") + } + if _, list, _ := a.command("devices"); !strings.Contains(list, "No phone is paired") { + t.Errorf("a device was created through the relay:\n%s", list) + } + + // The pairing is still pending, and straight to the agent the code works. + direct := newPhone(t, "https", a.addr) + if status, err := direct.pair(code, "Pixel 8"); err != nil || status != http.StatusOK { + t.Fatalf("pairing directly afterwards: %d, %v", status, err) + } + if got := exited(t, exit); got != 0 || !strings.Contains(out.String(), "Paired: Pixel 8") { + t.Fatalf("the pair command ended with %d and without the phone that paired directly", got) + } +} + +// impostor is a server with a certificate of its own that answers a pairing +// request itself, with the nonce and the proof that answer returns for the +// phone's nonce and the fingerprint of the impostor's own certificate. It +// returns the address it listens on. +func impostor(t *testing.T, answer func(phoneNonce, fingerprint []byte) (nonce, proof []byte)) string { + t.Helper() + cert := strangerCert(t) + fp, err := tlsid.FingerprintOf(cert) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) }) + mux.HandleFunc("POST /agent/v1/pair", func(w http.ResponseWriter, r *http.Request) { + var req struct{ Nonce string } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "malformed", http.StatusBadRequest) + return + } + phoneNonce, _ := base64.RawURLEncoding.DecodeString(req.Nonce) + nonce, proof := answer(phoneNonce, fp[:]) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{ + "nonce": base64.RawURLEncoding.EncodeToString(nonce), + "proof": base64.RawURLEncoding.EncodeToString(proof), + "token": "dm1.0badc0de." + strings.Repeat("A", 43), + }) + }) + ln, err := tls.Listen("tcp", "127.0.0.1:0", tlsid.ServerConfig(cert)) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: mux, ErrorLog: log.New(io.Discard, "", 0)} + go srv.Serve(ln) + t.Cleanup(func() { srv.Close() }) + return ln.Addr().String() +} + +// someCode is a pairing code that no agent has issued. +func someCode(t *testing.T) string { + t.Helper() + code, err := pairing.NewCode(rand.Reader) + if err != nil { + t.Fatal(err) + } + return code +} + +func TestAPhoneRefusesAnAnswerItCannotVerify(t *testing.T) { + // Whoever terminates the phone's connection can answer the pairing + // request with anything. Without the code it cannot make the proof. + addr := impostor(t, func(_, _ []byte) (nonce, proof []byte) { + nonce, proof = make([]byte, pairing.NonceLen), make([]byte, sha256.Size) + rand.Read(nonce) + rand.Read(proof) + return nonce, proof + }) + p := newPhone(t, "https", addr) + if status, err := p.pair(someCode(t), "Pixel 8"); err == nil || !strings.Contains(err.Error(), "could not prove it holds the code") { + t.Fatalf("status %d, err = %v, want the phone to refuse an answer it cannot verify", status, err) + } + if p.token != "" || p.pin != nil { + t.Fatal("the phone kept a token or a pin from an answer it could not verify") + } +} + +func TestAPhoneRefusesAnAgentNonceOrProofOfTheWrongLength(t *testing.T) { + // The server here holds the code, so its proof is right for whatever + // nonce it sends: all that is wrong with an answer is a length. The first + // case shows that the same server is believed when the lengths are right. + code := someCode(t) + for _, c := range []struct { + name string + nonceLen int + proof func(right []byte) []byte + accepted bool + }{ + {"the right lengths", pairing.NonceLen, func(right []byte) []byte { return right }, true}, + {"a nonce one byte short", pairing.NonceLen - 1, func(right []byte) []byte { return right }, false}, + {"a nonce one byte long", pairing.NonceLen + 1, func(right []byte) []byte { return right }, false}, + {"no nonce", 0, func(right []byte) []byte { return right }, false}, + {"a proof one byte short", pairing.NonceLen, func(right []byte) []byte { return right[:len(right)-1] }, false}, + {"a proof one byte long", pairing.NonceLen, func(right []byte) []byte { return append(right, 0) }, false}, + } { + addr := impostor(t, func(phoneNonce, fingerprint []byte) (nonce, proof []byte) { + nonce = make([]byte, c.nonceLen) + rand.Read(nonce) + return nonce, c.proof(pairing.AgentProof(code, fingerprint, phoneNonce, nonce)) + }) + p := newPhone(t, "https", addr) + status, err := p.pair(code, "Pixel 8") + if c.accepted { + if err != nil || status != http.StatusOK || p.token == "" || p.pin == nil { + t.Errorf("%s: the phone did not pair: %d, %v", c.name, status, err) + } + continue + } + if err == nil || !strings.Contains(err.Error(), "not 32 bytes") { + t.Errorf("%s: status %d, err = %v, want the phone to refuse the answer for its form", c.name, status, err) + } + if p.token != "" || p.pin != nil { + t.Errorf("%s: the phone kept a token or a pin", c.name) + } + } +} + +func TestAPhoneDoesNotWaitForEverForTheAnswer(t *testing.T) { + // A server that takes the pairing request and then says nothing, for as + // long as the phone stays. + arrived := make(chan struct{}) + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) }) + mux.HandleFunc("POST /agent/v1/pair", func(_ http.ResponseWriter, r *http.Request) { + close(arrived) + <-r.Context().Done() + }) + ln, err := tls.Listen("tcp", "127.0.0.1:0", tlsid.ServerConfig(strangerCert(t))) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: mux, ErrorLog: log.New(io.Discard, "", 0)} + go srv.Serve(ln) + t.Cleanup(func() { srv.Close() }) + + p := newPhone(t, "https", ln.Addr().String()) + code := someCode(t) + ended := make(chan error, 1) + go func() { + // A shorter limit than a phone sets, so that the test is quick, and + // still many times what it takes to get the request to the server. + _, err := p.pairWithin(time.Second, code, "Pixel 8") + ended <- err + }() + select { + case err := <-ended: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err = %v, want the attempt to run out of time", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the phone still waits for an answer") + } + select { + case <-arrived: + default: + t.Fatal("the attempt ran out of time before its request was with the server") + } + if p.token != "" || p.pin != nil { + t.Fatal("the phone kept a token or a pin from an attempt that ran out of time") + } +} + func TestAScannedCodeNeverReachesAnotherCertificate(t *testing.T) { a := startAgent(t) link, _, _, _ := a.startPair() @@ -283,21 +621,26 @@ func TestAPairedPhoneSurvivesARestartAndRefusesAnotherKey(t *testing.T) { if _, err := p.pairWithLink(link, "Pixel 8"); err != nil { t.Fatal(err) } - <-exit + exited(t, exit) a.stop() if code, _, errOut := a.command("devices"); code != 1 || !strings.Contains(errOut, "not running") { t.Fatalf("devices against a stopped agent: %d %q", code, errOut) } - // The same folder starts again on the same address: the phone is known. - again := startAgent(t, "AGENT_DATA", a.env["AGENT_DATA"], "AGENT_LISTEN", a.addr) + // The same folder starts again: the agent is who it was and knows the + // phone. It takes a port of its own, and the phone is told where: the + // port the first agent gave up may be someone else's by now. + again := startAgent(t, "AGENT_DATA", a.env["AGENT_DATA"]) + p.addr = again.addr if got := p.status("GET", "/containers/json"); got != http.StatusOK { t.Fatalf("after a restart the paired phone gets %d", got) } again.stop() - // A different agent takes over the address: the pin refuses it. - startAgent(t, "AGENT_LISTEN", a.addr) + // Where the phone looks for its agent, a different one answers: the pin + // refuses it. + other := startAgent(t) + p.addr = other.addr if _, err := p.do("GET", "/containers/json", nil); err == nil || !strings.Contains(err.Error(), "server identity changed") { t.Fatalf("err = %v, want the pin to refuse the new certificate", err) } @@ -316,7 +659,7 @@ func TestPairingBehindAProxy(t *testing.T) { if status, err := p.pair(code, "Pixel 8"); err != nil || status != http.StatusOK { t.Fatalf("pairing over plain HTTP: %d, %v", status, err) } - if got := <-exit; got != 0 { + if got := exited(t, exit); got != 0 { t.Fatalf("pair exited %d", got) } if got := p.status("GET", "/containers/json"); got != http.StatusOK { @@ -349,7 +692,7 @@ func TestPairDrawsAQRCodeAndLeavingItCancelsTheCode(t *testing.T) { code := codeInOutput.FindStringSubmatch(out.String())[1] cancel() // Ctrl-C - if got := <-exit; got != 1 || !strings.Contains(out.String(), "pairing cancelled") { + if got := exited(t, exit); got != 1 || !strings.Contains(out.String(), "pairing cancelled") { t.Fatalf("exit %d: %s", got, out.String()) } waitFor(t, "the agent to cancel the pairing", func() bool { return strings.Contains(a.log.String(), "outcome=cancelled") }) @@ -382,16 +725,225 @@ func TestStoppingTheAgentEndsAPendingPairCommand(t *testing.T) { } } +func TestRevokeSaysSoWhenThePhoneIsStillPaired(t *testing.T) { + a := startAgent(t) + link, _, _, exit := a.startPair() + p := newPhone(t, "https", a.addr) + if status, err := p.pairWithLink(link, "Pixel 8"); err != nil || status != http.StatusOK { + t.Fatalf("pairing by link: %d, %v", status, err) + } + if got := exited(t, exit); got != 0 { + t.Fatalf("pair exited %d", got) + } + _, list, _ := a.command("devices") + found := regexp.MustCompile(`(?m)^([0-9a-f]{8})\s+Pixel 8`).FindStringSubmatch(list) + if found == nil { + t.Fatalf("the paired phone is not in the list:\n%s", list) + } + + // A folder is in the way where the device list is written: from here on + // the agent can store nothing. + file := filepath.Join(a.env["AGENT_DATA"], "devices.json") + if err := os.Remove(file); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(file, "in the way"), 0o700); err != nil { + t.Fatal(err) + } + + code, out, errOut := a.command("revoke", found[1]) + if code != 1 || out != "" || !strings.HasPrefix(errOut, "docker-mobile-agent: the device is still paired") || !strings.Contains(errOut, "the removal could not be stored") { + t.Fatalf("revoke: exit %d, stdout %q, stderr %q", code, out, errOut) + } + if got := p.status("GET", "/containers/json"); got != http.StatusOK { + t.Fatalf("the phone that is still paired gets %d, want 200", got) + } +} + +// scriptedAdmin stands in for an agent on the admin socket of a fresh state +// folder: it answers a pair command with what pair writes. It returns the +// environment that leads a command to it. +func scriptedAdmin(t *testing.T, pair http.HandlerFunc) func(string) string { + t.Helper() + // A short path, as for a real agent: a socket lives in it. + dataDir, err := os.MkdirTemp("", "dma") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dataDir) }) + ln, err := net.Listen("unix", filepath.Join(dataDir, "admin.sock")) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc("POST /pair", pair) + srv := &http.Server{Handler: mux} + go srv.Serve(ln) + t.Cleanup(func() { srv.Close() }) + return func(k string) string { + if k == "AGENT_DATA" { + return dataDir + } + return "" + } +} + +// eventLines is a pairing stream as the agent writes it: an event a line. +func eventLines(events ...admin.Event) []byte { + var b bytes.Buffer + enc := json.NewEncoder(&b) + for _, e := range events { + enc.Encode(e) + } + return b.Bytes() +} + +// scriptedStart is the first event of a scripted pairing. Nothing in it is +// real. +var scriptedStart = admin.Event{ + Event: admin.EventStarted, + Code: "0000-0000-0000", + Link: "dockermobile://pair?c=000000000000&v=1", + Address: "agent.example:8443", + Role: "full", + ExpiresIn: 300, +} + +// interrupted is an output that presses Ctrl-C the moment the command has +// printed its code and begun to wait: writing "Waiting for the phone" to it +// ends the command's context. +type interrupted struct { + syncBuf + interrupt context.CancelFunc +} + +func (o *interrupted) Write(p []byte) (int, error) { + n, err := o.syncBuf.Write(p) + if bytes.Contains(p, []byte("Waiting for the phone")) { + o.interrupt() + } + return n, err +} + +func TestPairReportsHowThePairingEnded(t *testing.T) { + pixel := &admin.DeviceInfo{ID: "0a1b2c3d", Name: "Pixel 8", Role: "readonly"} + for _, c := range []struct { + name string + end admin.Event + code int + inStdout string + inStderr string + }{ + {"paired", admin.Event{Event: "paired", Device: pixel}, 0, "Paired: Pixel 8 (id 0a1b2c3d, read-only)", ""}, + {"paired, without the device", admin.Event{Event: "paired"}, 1, "", `a phone was paired, but not which one: look at "docker-mobile-agent devices"`}, + {"expired", admin.Event{Event: "expired"}, 1, "", "the code expired before a phone used it; run pair again"}, + {"replaced", admin.Event{Event: "replaced"}, 1, "", "another pair command replaced this code"}, + {"voided", admin.Event{Event: "voided"}, 1, "", "too many wrong attempts: the code was voided; run pair again"}, + {"failed", admin.Event{Event: "failed", Error: "write devices.json: no space left on device"}, 1, "", + "the phone proved the code but the agent could not store it: write devices.json: no space left on device"}, + {"an event the command does not know", admin.Event{Event: "exploded"}, 1, "", `pairing ended as "exploded"`}, + } { + getenv := scriptedAdmin(t, func(w http.ResponseWriter, _ *http.Request) { + w.Write(eventLines(scriptedStart, c.end)) + }) + var out, errOut bytes.Buffer + code := run(context.Background(), []string{"pair", "--no-qr"}, getenv, &out, &errOut) + if code != c.code { + t.Errorf("%s: exit %d, want %d (stderr: %s)", c.name, code, c.code, errOut.String()) + } + if c.inStdout != "" && !strings.Contains(out.String(), c.inStdout) { + t.Errorf("%s: stdout lacks %q: %s", c.name, c.inStdout, out.String()) + } + if c.inStderr != "" && !strings.Contains(errOut.String(), c.inStderr) { + t.Errorf("%s: stderr lacks %q: %s", c.name, c.inStderr, errOut.String()) + } + if c.code == 0 && errOut.Len() != 0 { + t.Errorf("%s: a pairing that worked wrote to stderr: %s", c.name, errOut.String()) + } + if c.code != 0 && strings.Contains(out.String(), "Paired:") { + t.Errorf("%s: stdout says a phone was paired: %s", c.name, out.String()) + } + } +} + +func TestAPairingThatEndedIsReportedThoughTheCommandWasInterrupted(t *testing.T) { + // The whole pairing, its good end included, is in the agent's answer + // before the command has printed the code, and the command is interrupted + // while it prints: when it reads on, its context is over and the outcome + // is there to be read. Both events go out in one write, so that the + // command holds the second when it is interrupted over the first. + pixel := &admin.DeviceInfo{ID: "0a1b2c3d", Name: "Pixel 8", Role: "full"} + getenv := scriptedAdmin(t, func(w http.ResponseWriter, _ *http.Request) { + w.Write(eventLines(scriptedStart, admin.Event{Event: "paired", Device: pixel})) + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + out := &interrupted{interrupt: cancel} + var errOut bytes.Buffer + code := run(ctx, []string{"pair", "--no-qr"}, getenv, out, &errOut) + if ctx.Err() == nil { + t.Fatal("the command was not interrupted") + } + if code != 0 || !strings.Contains(out.String(), "Paired: Pixel 8 (id 0a1b2c3d, full control)") || errOut.Len() != 0 { + t.Fatalf("exit %d\nstdout:\n%s\nstderr:\n%s", code, out.String(), errOut.String()) + } +} + +func TestAnInterruptedPairClaimsOnlyWhatItKnows(t *testing.T) { + // The agent has sent the code and waits for a phone that does not come. + getenv := scriptedAdmin(t, func(w http.ResponseWriter, r *http.Request) { + w.Write(eventLines(scriptedStart)) + w.(http.Flusher).Flush() + <-r.Context().Done() + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + out := &interrupted{interrupt: cancel} + var errOut bytes.Buffer + code := run(ctx, []string{"pair", "--no-qr"}, getenv, out, &errOut) + want := `pairing cancelled; the code no longer works. If a phone used it in the same moment it is paired: check with "docker-mobile-agent devices"` + if code != 1 || !strings.Contains(errOut.String(), want) || strings.Contains(out.String(), "Paired:") { + t.Fatalf("exit %d\nstdout:\n%s\nstderr:\n%s", code, out.String(), errOut.String()) + } +} + +func TestAPairThatLosesTheAgentClaimsOnlyWhatItKnows(t *testing.T) { + // The stream ends after the code and before any outcome, as it does when + // the agent stops. + getenv := scriptedAdmin(t, func(w http.ResponseWriter, _ *http.Request) { + w.Write(eventLines(scriptedStart)) + }) + var out, errOut bytes.Buffer + code := run(context.Background(), []string{"pair", "--no-qr"}, getenv, &out, &errOut) + want := `the agent stopped before the pairing ended; the code no longer works. If a phone used it in the same moment it is paired, and still is when the agent runs again: check then with "docker-mobile-agent devices"` + if code != 1 || !strings.Contains(errOut.String(), want) || strings.Contains(out.String(), "Paired:") { + t.Fatalf("exit %d\nstdout:\n%s\nstderr:\n%s", code, out.String(), errOut.String()) + } +} + func TestPairCommandLine(t *testing.T) { + // The commands that look for an agent get a state folder with a short + // path: a longer one is refused for its length before anything is looked + // for, and the temporary folder of a test can be that long. + empty, err := os.MkdirTemp("", "dma") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(empty) }) + noAgent := []string{"AGENT_DATA", empty} runCommandCases(t, []commandCase{ {name: "help lists the pairing commands", args: []string{"help"}, code: 0, inStdout: "docker-mobile-agent pair"}, - {name: "devices without an agent", args: []string{"devices"}, code: 1, inStderr: "not running"}, - {name: "pair without an agent", args: []string{"pair"}, code: 1, inStderr: "not running"}, - {name: "revoke without an agent", args: []string{"revoke", "abcd1234"}, code: 1, inStderr: "not running"}, + {name: "devices without an agent", args: []string{"devices"}, env: noAgent, code: 1, inStderr: "not running"}, + {name: "pair without an agent", args: []string{"pair"}, env: noAgent, code: 1, inStderr: "not running"}, + {name: "revoke without an agent", args: []string{"revoke", "abcd1234"}, env: noAgent, code: 1, inStderr: "not running"}, {name: "revoke without an id", args: []string{"revoke"}, code: 1, inStderr: "give the id"}, {name: "revoke with two ids", args: []string{"revoke", "a", "b"}, code: 1, inStderr: "give the id"}, - {name: "pair with a stray argument", args: []string{"pair", "now"}, code: 1, inStderr: `unexpected argument "now"`}, - {name: "pair with an unknown flag", args: []string{"pair", "--admin"}, code: 1, inStderr: "pair:"}, + {name: "pair with a stray argument", args: []string{"pair", "now"}, code: 1, inStderr: `pair: unexpected argument "now"`}, + {name: "pair with an unknown flag", args: []string{"pair", "--admin"}, code: 1, + stderrIs: "docker-mobile-agent: pair: flag provided but not defined: -admin (see: docker-mobile-agent pair --help)\n"}, + {name: "devices with a stray argument", args: []string{"devices", "extra"}, code: 1, inStderr: `devices: unexpected argument "extra"`}, + {name: "revoke with an unknown flag", args: []string{"revoke", "--all"}, code: 1, + stderrIs: "docker-mobile-agent: revoke: flag provided but not defined: -all (see: docker-mobile-agent revoke --help)\n"}, }) } diff --git a/agent/cmd/agent/serve.go b/agent/cmd/agent/serve.go index 6439d20..49b13d7 100644 --- a/agent/cmd/agent/serve.go +++ b/agent/cmd/agent/serve.go @@ -45,11 +45,10 @@ func (w serverLog) Write(p []byte) (int, error) { return len(p), nil } -func cmdServe(ctx context.Context, args []string, getenv func(string) string, stderr io.Writer) error { +func cmdServe(ctx context.Context, args []string, getenv func(string) string, stdout, stderr io.Writer) error { fs := flag.NewFlagSet("serve", flag.ContinueOnError) - fs.SetOutput(stderr) insecure := fs.Bool("insecure-http", false, "serve plain HTTP, behind a proxy that terminates TLS") - if err := fs.Parse(args); err != nil { + if done, err := parseArgs(fs, args, "[serve] [--insecure-http]", stdout); done || err != nil { return err } cfg, err := config.Load(getenv, *insecure) diff --git a/agent/internal/admin/admin.go b/agent/internal/admin/admin.go index a10a336..9d7a984 100644 --- a/agent/internal/admin/admin.go +++ b/agent/internal/admin/admin.go @@ -351,7 +351,10 @@ func (s *Server) handleRevoke(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") dev, found, err := s.Devices.Remove(id) if err != nil { - writeJSON(w, http.StatusInternalServerError, errorResponse{err.Error()}) + // The device is back in the list and none of its requests was + // closed. The answer says that first: the cause alone names a file, + // and reads as if the phone were gone. + writeJSON(w, http.StatusInternalServerError, errorResponse{"the device is still paired and its connections stay open: the removal could not be stored: " + err.Error()}) return } if !found { diff --git a/agent/internal/admin/admin_test.go b/agent/internal/admin/admin_test.go index 52053ed..302e699 100644 --- a/agent/internal/admin/admin_test.go +++ b/agent/internal/admin/admin_test.go @@ -285,6 +285,45 @@ func TestLeavingThePairCommandCancelsTheCode(t *testing.T) { } } +func TestPairReportsAnOutcomeItHasHandedOnWhateverBecomesOfTheContext(t *testing.T) { + // An agent that sends the outcome and then keeps the stream open. The + // command line is interrupted with the outcome in hand: that is the + // moment a phone completes the pairing and its owner presses Ctrl-C. + dir := shortDir(t) + ln, err := Listen(dir) + if err != nil { + t.Fatalf("Listen: %v", err) + } + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + enc := json.NewEncoder(w) + enc.Encode(Event{Event: EventStarted}) + enc.Encode(Event{Event: "paired", Device: &DeviceInfo{ID: "0a1b2c3d", Name: "Pixel 8", Role: "full"}}) + w.(http.Flusher).Flush() + <-r.Context().Done() + })} + go srv.Serve(ln) + t.Cleanup(func() { srv.Close() }) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var got []string + done := make(chan error, 1) + go func() { + done <- NewClient(dir.Path("")).Pair(ctx, PairRequest{}, func(e Event) { + got = append(got, e.Event) + if e.Event == "paired" { + cancel() + } + }) + }() + if err := finished(t, done); err != nil { + t.Fatalf("Pair returned %v although it had handed on how the pairing ended", err) + } + if len(got) != 2 || got[0] != EventStarted || got[1] != "paired" { + t.Fatalf("events = %v, want started and paired", got) + } +} + func TestASecondPairReplacesTheFirst(t *testing.T) { f := start(t) firstEvents, firstDone := f.pairAsync(context.Background(), PairRequest{}) @@ -403,6 +442,52 @@ func TestRevokeRemovesTheDeviceAndClosesItsRequests(t *testing.T) { } } +func TestRevokeSaysTheDeviceIsStillPairedWhenTheRemovalCannotBeStored(t *testing.T) { + // The device list lives in a folder of its own here, apart from the + // socket and the lock, so that the folder can go while the server runs. + store := shortDir(t) + devices, err := state.LoadDevices(store, time.Now) + if err != nil { + t.Fatal(err) + } + f := start(t, func(s *Server) { s.Devices = devices }) + dev, token, err := devices.Add("phone", state.RoleFull) + if err != nil { + t.Fatal(err) + } + open, release := f.conns.Track(context.Background(), dev.ID) + defer release() + // Nothing can be written from here on. + if err := os.RemoveAll(store.Path("")); err != nil { + t.Fatal(err) + } + + _, _, err = f.client.Revoke(context.Background(), dev.ID) + if err == nil { + t.Fatal("Revoke reported success although the removal could not be stored") + } + if !strings.HasPrefix(err.Error(), "the device is still paired") { + t.Errorf("the error does not begin by saying that the device is still paired: %v", err) + } + for _, want := range []string{"the removal could not be stored", "write devices.json"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("the error does not say %q: %v", want, err) + } + } + // And so it is: the device works as before and its request is open. + if _, ok := devices.Authenticate(token); !ok { + t.Fatal("the device no longer authenticates") + } + if list := devices.List(); len(list) != 1 || list[0].ID != dev.ID { + t.Fatalf("the list holds %d devices, want the one whose removal failed", len(list)) + } + select { + case <-open.Done(): + t.Fatal("the open request of the device was closed") + default: + } +} + func TestWithoutARunningAgentTheClientSaysSo(t *testing.T) { c := NewClient(shortDir(t).Path("")) if _, err := c.Devices(context.Background()); !errors.Is(err, ErrNotRunning) { diff --git a/agent/internal/admin/client.go b/agent/internal/admin/client.go index 02cc945..8f6fc02 100644 --- a/agent/internal/admin/client.go +++ b/agent/internal/admin/client.go @@ -100,6 +100,13 @@ func (c *Client) do(ctx context.Context, method, path string, body any) (*http.R // Pair starts a pairing and calls onEvent for the "started" event and then // for the one that ends it. It returns when the pairing is over. Cancelling // ctx cancels the pairing. +// +// Once the event that ends the pairing has been handed to onEvent, Pair +// returns nil, whatever has become of ctx by then: how the pairing ended is +// known, and a phone that was paired stays paired. An error therefore means +// that the pairing did not begin, or that the caller did not see it end: +// then it is the error of ctx when ctx ended first, and ErrStopped when the +// stream broke off. func (c *Client) Pair(ctx context.Context, req PairRequest, onEvent func(Event)) error { resp, err := c.do(ctx, http.MethodPost, "/pair", req) if err != nil { @@ -107,23 +114,21 @@ func (c *Client) Pair(ctx context.Context, req PairRequest, onEvent func(Event)) } defer resp.Body.Close() lines := bufio.NewScanner(resp.Body) - last := "" for lines.Scan() { var e Event if err := json.Unmarshal(lines.Bytes(), &e); err != nil { return fmt.Errorf("unreadable answer from the agent: %w", err) } - last = e.Event onEvent(e) + if e.Event != EventStarted { + return nil + } } if ctx.Err() != nil { return ctx.Err() } - if last == "" || last == EventStarted { - // The stream broke off without an ending event. - return ErrStopped - } - return lines.Err() + // The stream broke off without an ending event. + return ErrStopped } // Devices lists the paired devices, oldest first. From 0ed3d550599d2a23844173e482d12b13a2a7ce7e Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 21:00:45 +0530 Subject: [PATCH 24/32] fix(agent): guard the test phone's fields and report a pairing that just made it --- agent/cmd/agent/admin_commands.go | 68 +++-- agent/cmd/agent/main_test.go | 160 +++++++++--- agent/cmd/agent/pair_test.go | 397 +++++++++++++++++++++++------ agent/internal/admin/admin.go | 24 +- agent/internal/admin/admin_test.go | 21 ++ agent/internal/admin/client.go | 8 +- 6 files changed, 530 insertions(+), 148 deletions(-) diff --git a/agent/cmd/agent/admin_commands.go b/agent/cmd/agent/admin_commands.go index caace94..f0e7a10 100644 --- a/agent/cmd/agent/admin_commands.go +++ b/agent/cmd/agent/admin_commands.go @@ -41,13 +41,16 @@ func cmdPair(ctx context.Context, args []string, getenv func(string) string, std ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) defer stop() - // end is the event that ended the pairing; nil for as long as none has. - var end *admin.Event + var ( + end *admin.Event // the event that ended the pairing; nil for as long as none has + shown bool // whether a code has been shown + ) err := admin.NewClient(config.DataDir(getenv)).Pair(ctx, req, func(e admin.Event) { if e.Event != admin.EventStarted { end = &e return } + shown = true if !*noQR { fmt.Fprintln(stdout, "Scan this with the docker-mobile app (Connections, Add, Scan QR code):") fmt.Fprintln(stdout) @@ -73,39 +76,62 @@ func cmdPair(ctx context.Context, args []string, getenv func(string) string, std fmt.Fprintln(stdout) fmt.Fprintf(stdout, "The code works once and expires in %d minutes. Waiting for the phone (Ctrl-C cancels)...\n", (e.ExpiresIn+59)/60) }) + said, err := pairEnding(end, err, shown) + fmt.Fprint(stdout, said) + return err +} + +// pairEnding decides what the pair command says once the pairing is over for +// it: what goes to standard output, and the error the command ends with. A +// nil error is exit status 0. Any other is printed to standard error by the +// caller and is exit status 1. +// +// end is the event that ended the pairing, nil when the command saw none. +// err is what the client returned. shown says whether the command had shown +// a code. +func pairEnding(end *admin.Event, err error, shown bool) (stdout string, failure error) { if end == nil { - // The pairing did not end where this command could see it, so the - // command does not know whether a phone was paired. The agent uses - // the code up and stores the device before it answers the phone: a - // phone can have paired in the very moment the command was - // interrupted or the agent stopped. - switch { - case errors.Is(err, context.Canceled): - return errors.New(`pairing cancelled; the code no longer works. If a phone used it in the same moment it is paired: check with "docker-mobile-agent devices"`) - case err == nil, errors.Is(err, admin.ErrStopped): - return fmt.Errorf(`%w; the code no longer works. If a phone used it in the same moment it is paired, and still is when the agent runs again: check then with "docker-mobile-agent devices"`, admin.ErrStopped) + interrupted := errors.Is(err, context.Canceled) + stopped := err == nil || errors.Is(err, admin.ErrStopped) + if !interrupted && !stopped { + return "", err } - return err + if !shown { + // Nobody has seen a code: there is none to speak of, and no + // phone that could have used one. + if interrupted { + return "", errors.New("pairing cancelled before a code was shown") + } + return "", admin.ErrStopped + } + // A code was shown, and the pairing did not end where this command + // could see it: the command does not know whether a phone was + // paired. The agent uses the code up and stores the device before it + // answers the phone, so a phone can have paired in the very moment + // the command was interrupted or the agent stopped. + if interrupted { + return "", errors.New(`pairing cancelled; the code no longer works. If a phone used it in the same moment it is paired: check with "docker-mobile-agent devices"`) + } + return "", fmt.Errorf(`%w; the code no longer works. If a phone used it in the same moment it is paired, and still is when the agent runs again: check then with "docker-mobile-agent devices"`, admin.ErrStopped) } // How the pairing ended is reported whatever err says: a phone that was // paired is paired, also when the command was interrupted just then. switch end.Event { case "paired": if end.Device == nil { - return errors.New(`the agent says a phone was paired, but not which one: look at "docker-mobile-agent devices"`) + return "", errors.New(`the agent says a phone was paired, but not which one: look at "docker-mobile-agent devices"`) } - fmt.Fprintf(stdout, "Paired: %s (id %s, %s)\n", end.Device.Name, end.Device.ID, accessLabel(end.Device.Role)) - return nil + return fmt.Sprintf("Paired: %s (id %s, %s)\n", end.Device.Name, end.Device.ID, accessLabel(end.Device.Role)), nil case "expired": - return errors.New("the code expired before a phone used it; run pair again") + return "", errors.New("the code expired before a phone used it; run pair again") case "replaced": - return errors.New("another pair command replaced this code") + return "", errors.New("another pair command replaced this code") case "voided": - return errors.New("too many wrong attempts: the code was voided; run pair again") + return "", errors.New("too many wrong attempts: the code was voided; run pair again") case "failed": - return fmt.Errorf("the phone proved the code but the agent could not store it: %s", end.Error) + return "", fmt.Errorf("the phone proved the code but the agent could not store it: %s", end.Error) default: - return fmt.Errorf("pairing ended as %q", end.Event) + return "", fmt.Errorf("pairing ended as %q", end.Event) } } diff --git a/agent/cmd/agent/main_test.go b/agent/cmd/agent/main_test.go index 186c2d7..54155fd 100644 --- a/agent/cmd/agent/main_test.go +++ b/agent/cmd/agent/main_test.go @@ -15,6 +15,7 @@ import ( "path/filepath" "strings" "sync" + "syscall" "testing" "time" @@ -123,16 +124,9 @@ func startAgent(t *testing.T, extra ...string) *agent { // started after the probe, it would be the nearest contender for the // port the probe has just given back. docker := fakeDocker(t) - probe, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - listen := probe.Addr().String() - probe.Close() - a := &agent{t: t, log: &syncBuf{}, done: make(chan error, 1), env: map[string]string{ + a := &agent{t: t, log: &syncBuf{}, env: map[string]string{ "AGENT_DATA": dataDir, - "AGENT_LISTEN": listen, "AGENT_ADVERTISE": "127.0.0.1", "AGENT_NAME": "test agent", "DOCKER_HOST": "tcp://" + docker.Listener.Addr().String(), @@ -140,30 +134,66 @@ func startAgent(t *testing.T, extra ...string) *agent { for i := 0; i+1 < len(extra); i += 2 { a.env[extra[i]] = extra[i+1] } - cfg, err := config.Load(a.getenv, false) + // An address the caller names is the one to use, and no other. + _, named := a.env["AGENT_LISTEN"] + for try := 1; ; try++ { + if !named { + a.env["AGENT_LISTEN"] = freeAddress(t) + } + cfg, err := config.Load(a.getenv, false) + if err != nil { + t.Fatalf("config: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + // Whatever happens below, the agent is told to stop when the test + // is over: one that never reported ready would otherwise keep its + // port, its folder and its goroutine. + t.Cleanup(cancel) + ready, done := make(chan net.Addr, 1), make(chan error, 1) + a.cancel, a.done = cancel, done + go func() { + done <- serve(ctx, cfg, slog.New(slog.NewTextHandler(a.log, nil)), func(addr net.Addr) { ready <- addr }) + }() + select { + case addr := <-ready: + a.addr = addr.String() + t.Cleanup(func() { a.stop() }) + return a + case err := <-done: + // A port that was free when it was looked for can be someone + // else's by the time the agent asks for it. Then another one is + // looked for, a few times at most. Whatever else ends the agent + // at once is a failure. + if named || try == startTries || !addressInUse(err) { + t.Fatalf("serve ended at once: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the agent did not start") + } + } +} + +// startTries is how often startAgent looks for a port before it gives up. +const startTries = 5 + +// freeAddress returns an address on this machine that nothing listens on at +// this moment. It is not kept: whoever wants it has to take it, and may find +// it taken. +func freeAddress(t *testing.T) string { + t.Helper() + probe, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { - t.Fatalf("config: %v", err) - } - ctx, cancel := context.WithCancel(context.Background()) - // Whatever happens below, the agent is told to stop when the test is - // over: one that never reported ready would otherwise keep its port, its - // folder and its goroutine. - t.Cleanup(cancel) - a.cancel = cancel - ready := make(chan net.Addr, 1) - go func() { - a.done <- serve(ctx, cfg, slog.New(slog.NewTextHandler(a.log, nil)), func(addr net.Addr) { ready <- addr }) - }() - select { - case addr := <-ready: - a.addr = addr.String() - case err := <-a.done: - t.Fatalf("serve ended at once: %v", err) - case <-time.After(5 * time.Second): - t.Fatal("the agent did not start") + t.Fatal(err) } - t.Cleanup(func() { a.stop() }) - return a + defer probe.Close() + return probe.Addr().String() +} + +// addressInUse reports whether err says that the address to listen on is +// taken. Windows has a number of its own for that. +func addressInUse(err error) bool { + const windowsAddressInUse = syscall.Errno(10048) // WSAEADDRINUSE + return errors.Is(err, syscall.EADDRINUSE) || errors.Is(err, windowsAddressInUse) } // stop ends the agent and returns what serve returned. It may be called @@ -203,10 +233,55 @@ type phone struct { t *testing.T scheme string addr string - pin *tlsid.Fingerprint // nil until the phone trusts a certificate - seen tlsid.Fingerprint // what the last handshake presented token string client *http.Client + + // mu guards pin and seen. A handshake reads and writes them on a + // goroutine of the transport, and that goroutine can still be running + // when the request it was started for has returned: a request that ends + // with its context leaves its dial behind. Nothing touches the two + // fields but the four methods below. + mu sync.Mutex + // pin is the key the phone holds its connections to. It is nil until the + // phone trusts a certificate. For the length of a pairing attempt it is + // what the first connection of that attempt presented, and it stays + // after the attempt only if the phone was paired. + pin *tlsid.Fingerprint + // seen is what the last handshake presented. + seen tlsid.Fingerprint +} + +// present records what a handshake presented and reports whether the phone +// takes it: any key while it holds its connections to none, and after that +// the pinned key and no other. +func (p *phone) present(fp tlsid.Fingerprint) bool { + p.mu.Lock() + defer p.mu.Unlock() + p.seen = fp + return p.pin == nil || fp == *p.pin +} + +// presented returns what the last handshake presented. +func (p *phone) presented() tlsid.Fingerprint { + p.mu.Lock() + defer p.mu.Unlock() + return p.seen +} + +// trusted returns the key the phone holds its connections to, nil when it +// holds them to none. What it points to is never written again. +func (p *phone) trusted() *tlsid.Fingerprint { + p.mu.Lock() + defer p.mu.Unlock() + return p.pin +} + +// trust makes pin the key the phone holds its connections to; nil lifts +// that. The caller must not write to what pin points to afterwards. +func (p *phone) trust(pin *tlsid.Fingerprint) { + p.mu.Lock() + defer p.mu.Unlock() + p.pin = pin } func newPhone(t *testing.T, scheme, addr string) *phone { @@ -223,8 +298,7 @@ func newPhone(t *testing.T, scheme, addr string) *phone { if err != nil { return err } - p.seen = fp - if p.pin != nil && fp != *p.pin { + if !p.present(fp) { return errors.New("server identity changed") } return nil @@ -238,7 +312,8 @@ func newPhone(t *testing.T, scheme, addr string) *phone { func (a *agent) pinned(token string) *phone { p := newPhone(a.t, "https", a.addr) fp := a.fingerprint() - p.pin, p.token = &fp, token + p.trust(&fp) + p.token = token return p } @@ -249,6 +324,15 @@ func (p *phone) do(method, path string, body []byte) (*http.Response, error) { // doWithin is do for a request that ends with ctx, the reading of its answer // included. func (p *phone) doWithin(ctx context.Context, method, path string, body []byte) (*http.Response, error) { + req, err := p.request(ctx, method, path, body) + if err != nil { + return nil, err + } + return p.client.Do(req) +} + +// request builds a request of the phone, with its token when it has one. +func (p *phone) request(ctx context.Context, method, path string, body []byte) (*http.Request, error) { req, err := http.NewRequestWithContext(ctx, method, p.scheme+"://"+p.addr+path, bytes.NewReader(body)) if err != nil { return nil, err @@ -256,7 +340,7 @@ func (p *phone) doWithin(ctx context.Context, method, path string, body []byte) if p.token != "" { req.Header.Set("Authorization", "Bearer "+p.token) } - return p.client.Do(req) + return req, nil } func (p *phone) status(method, path string) int { @@ -393,8 +477,8 @@ func TestTheFingerprintCommandPrintsWhatThePortPresents(t *testing.T) { p := newPhone(t, "https", a.addr) p.status("GET", "/healthz") code, out, errOut := a.command("fingerprint") - if code != 0 || strings.TrimSpace(out) != p.seen.Display() { - t.Fatalf("fingerprint: exit %d, %q (stderr %q); the port presents %q", code, out, errOut, p.seen.Display()) + if code != 0 || strings.TrimSpace(out) != p.presented().Display() { + t.Fatalf("fingerprint: exit %d, %q (stderr %q); the port presents %q", code, out, errOut, p.presented().Display()) } } diff --git a/agent/cmd/agent/pair_test.go b/agent/cmd/agent/pair_test.go index f67d140..4b8e68b 100644 --- a/agent/cmd/agent/pair_test.go +++ b/agent/cmd/agent/pair_test.go @@ -68,12 +68,18 @@ func exited(t *testing.T, exit <-chan int) int { // test guesses of the code against, and must not get to choose how long. const pairTimeout = 5 * time.Second -// pair runs the proof exchange with a typed code. +// maxPairAnswer is the most the phone reads of an answer to its pairing +// request. What an agent answers is a few hundred bytes. +const maxPairAnswer = 4 << 10 + +// pair runs the proof exchange with a typed code, and gives it pairTimeout. func (p *phone) pair(code, name string) (status int, err error) { - return p.pairWithin(pairTimeout, code, name) + ctx, cancel := context.WithTimeout(context.Background(), pairTimeout) + defer cancel() + return p.pairContext(ctx, code, name) } -// pairWithin is pair with the time the whole attempt may take. +// pairContext is one pairing attempt. It is over when ctx is. // // A proof is good for one certificate. It must therefore travel on a // connection that presented that certificate and no other: a proof made for @@ -85,34 +91,39 @@ func (p *phone) pair(code, name string) (status int, err error) { // its handshake before anything is sent on it. // // Nothing is kept unless the answer proves that the server holds the code -// too. Whenever the attempt does not end that way the phone is left as it -// was: without a token, and with the pin it had before or none. -func (p *phone) pairWithin(limit time.Duration, code, name string) (status int, err error) { +// too, and brings a token. Whenever the attempt does not end that way the +// phone is left as it was: without a token, and with the pin it had before +// or none. +// +// The phone goes where it was sent and takes what it asked for, no more: it +// follows no redirect, and it reads no answer that is larger than a pairing +// answer can be. +func (p *phone) pairContext(ctx context.Context, code, name string) (status int, err error) { canonical, ok := pairing.Normalize(code) if !ok { return 0, fmt.Errorf("bad code %q", code) } - ctx, cancel := context.WithTimeout(context.Background(), limit) - defer cancel() - - before, paired := p.pin, false + before, paired := p.trusted(), false defer func() { if !paired { - p.pin = before + p.trust(before) } }() var fp []byte if p.scheme == "https" { - probe, err := p.doWithin(ctx, http.MethodGet, "/healthz", nil) + probe, err := p.ask(ctx, http.MethodGet, "/healthz", nil) if err != nil { return 0, err } probe.Body.Close() - // A copy: every later handshake writes to p.seen, also one that the - // pin then refuses. - presented := p.seen - p.pin = &presented - fp = presented[:] + if isRedirect(probe.StatusCode) { + return 0, fmt.Errorf("the server answered the first request of the pairing with a redirect (%d)", probe.StatusCode) + } + // A copy of its own: every later handshake changes what the phone + // has seen last, also one that the pin then refuses. + first := p.presented() + p.trust(&first) + fp = first[:] } nonce := make([]byte, pairing.NonceLen) rand.Read(nonce) @@ -122,18 +133,26 @@ func (p *phone) pairWithin(limit time.Duration, code, name string) (status int, "proof": base64.RawURLEncoding.EncodeToString(pairing.PhoneProof(canonical, fp, nonce)), "name": name, }) - resp, err := p.doWithin(ctx, http.MethodPost, "/agent/v1/pair", body) + resp, err := p.ask(ctx, http.MethodPost, "/agent/v1/pair", body) if err != nil { return 0, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { + // A redirect is among these, and ends the attempt like the others. return resp.StatusCode, nil } + raw, err := io.ReadAll(io.LimitReader(resp.Body, maxPairAnswer+1)) + if err != nil { + return 0, err + } + if len(raw) > maxPairAnswer { + return 0, fmt.Errorf("the server's answer is too large for a pairing answer: more than %d bytes", maxPairAnswer) + } var got struct { Nonce, Proof, Token string } - if err := json.NewDecoder(resp.Body).Decode(&got); err != nil { + if err := json.Unmarshal(raw, &got); err != nil { return 0, err } // The lengths come first: the proof is computed over the two nonces one @@ -144,6 +163,9 @@ func (p *phone) pairWithin(limit time.Duration, code, name string) (status int, if errNonce != nil || errProof != nil || len(agentNonce) != pairing.NonceLen || len(proof) != sha256.Size { return 0, errors.New("the server's answer is malformed: its nonce or its proof is not 32 bytes") } + if got.Token == "" { + return 0, errors.New("the server's answer is malformed: it holds no token") + } if !hmac.Equal(proof, pairing.AgentProof(canonical, fp, nonce, agentNonce)) { return 0, errors.New("the server could not prove it holds the code") } @@ -153,6 +175,27 @@ func (p *phone) pairWithin(limit time.Duration, code, name string) (status int, return http.StatusOK, nil } +// ask sends one request of a pairing attempt. It is the phone's ordinary +// request but for one thing: it follows no redirect, and hands back the +// answer that asks for one as it is. Where a phone takes its proof is for +// its owner to say, who typed or scanned the address, and not for whoever +// answers there. +func (p *phone) ask(ctx context.Context, method, path string, body []byte) (*http.Response, error) { + req, err := p.request(ctx, method, path, body) + if err != nil { + return nil, err + } + straight := &http.Client{ + Transport: p.client.Transport, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + return straight.Do(req) +} + +// isRedirect reports whether status is one of those that send the asker +// somewhere else. +func isRedirect(status int) bool { return status >= 300 && status < 400 } + // pairWithLink is the QR path: the fingerprint comes from the link, and the // phone refuses any other certificate from the first byte on. A pin from a // link is kept only together with the pairing it was for. @@ -162,7 +205,7 @@ func (p *phone) pairWithLink(link, name string) (int, error) { return 0, err } q := u.Query() - before := p.pin + before := p.trusted() if f := q.Get("f"); f != "" { raw, err := base64.RawURLEncoding.DecodeString(f) if err != nil || len(raw) != 32 { @@ -170,11 +213,11 @@ func (p *phone) pairWithLink(link, name string) (int, error) { } var pin tlsid.Fingerprint copy(pin[:], raw) - p.pin = &pin + p.trust(&pin) } status, err := p.pair(q.Get("c"), name) if err != nil || status != http.StatusOK { - p.pin = before + p.trust(before) } return status, err } @@ -221,7 +264,7 @@ func TestPairUseAndRevokeOverTLS(t *testing.T) { if !strings.Contains(out2.String(), "Paired: kitchen tablet") || !strings.Contains(out2.String(), "full control") { t.Fatalf("pair output: %s", out2.String()) } - if *full.pin != a.fingerprint() { + if *full.trusted() != a.fingerprint() { t.Fatal("the phone pinned something other than the agent's fingerprint") } if got := full.status("POST", "/containers/x/start"); got != http.StatusOK { @@ -322,7 +365,7 @@ func TestSomeoneInTheMiddleCannotPair(t *testing.T) { if status != http.StatusForbidden { t.Fatalf("the agent answered %d to a relayed proof, want 403", status) } - if victim.token != "" || victim.pin != nil { + if victim.token != "" || victim.trusted() != nil { t.Fatal("the phone trusted the attacker") } if _, list, _ := a.command("devices"); !strings.Contains(list, "No phone is paired") { @@ -425,7 +468,7 @@ func TestARelayThatOnlyTerminatesTheProofConnectionGetsNothing(t *testing.T) { if status, err := victim.pair(code, "Pixel 8"); err == nil || !strings.Contains(err.Error(), "server identity changed") { t.Errorf("status %d, err = %v, want the phone to refuse the connection that presents another certificate", status, err) } - if victim.token != "" || victim.pin != nil { + if victim.token != "" || victim.trusted() != nil { t.Error("the phone kept a token or a pin from the attempt through the relay") } if got := reached.String(); got != "" { @@ -448,42 +491,89 @@ func TestARelayThatOnlyTerminatesTheProofConnectionGetsNothing(t *testing.T) { } } -// impostor is a server with a certificate of its own that answers a pairing -// request itself, with the nonce and the proof that answer returns for the -// phone's nonce and the fingerprint of the impostor's own certificate. It -// returns the address it listens on. -func impostor(t *testing.T, answer func(phoneNonce, fingerprint []byte) (nonce, proof []byte)) string { +// serveTLS serves handler over TLS with cert until the test ends and returns +// the address. It reports nothing: a handshake that a phone refuses is what +// some of the tests are about. +func serveTLS(t *testing.T, cert tls.Certificate, handler http.Handler) string { + t.Helper() + ln, err := tls.Listen("tcp", "127.0.0.1:0", tlsid.ServerConfig(cert)) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: handler, ErrorLog: log.New(io.Discard, "", 0)} + go srv.Serve(ln) + t.Cleanup(func() { srv.Close() }) + return ln.Addr().String() +} + +// fingerprintOf is the fingerprint a phone sees when a server presents cert. +func fingerprintOf(t *testing.T, cert tls.Certificate) []byte { t.Helper() - cert := strangerCert(t) fp, err := tlsid.FingerprintOf(cert) if err != nil { t.Fatal(err) } - mux := http.NewServeMux() - mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) }) - mux.HandleFunc("POST /agent/v1/pair", func(w http.ResponseWriter, r *http.Request) { + return fp[:] +} + +// healthy answers the probe the way an agent does. +func healthy(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) } + +// madeUpToken has the form of a device token and belongs to no device. +var madeUpToken = "dm1.0badc0de." + strings.Repeat("A", 43) + +// reply is what a server that is not the agent answers a pairing request +// with. +type reply struct { + nonce, proof []byte + token string + padding int // the size of a field no pairing answer has, in bytes +} + +// rightReply is the answer of a server that holds code: its proof is good +// for the phone's nonce, for the nonce in the answer and for the certificate +// that has fingerprint. +func rightReply(code string, phoneNonce, fingerprint []byte) reply { + nonce := make([]byte, pairing.NonceLen) + rand.Read(nonce) + return reply{nonce: nonce, proof: pairing.AgentProof(code, fingerprint, phoneNonce, nonce), token: madeUpToken} +} + +// answerPairing answers a pairing request with what answer returns for the +// phone's nonce and fingerprint, the fingerprint of the server's own +// certificate. +func answerPairing(fingerprint []byte, answer func(phoneNonce, fingerprint []byte) reply) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { var req struct{ Nonce string } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "malformed", http.StatusBadRequest) return } phoneNonce, _ := base64.RawURLEncoding.DecodeString(req.Nonce) - nonce, proof := answer(phoneNonce, fp[:]) + a := answer(phoneNonce, fingerprint) + fields := map[string]string{ + "nonce": base64.RawURLEncoding.EncodeToString(a.nonce), + "proof": base64.RawURLEncoding.EncodeToString(a.proof), + "token": a.token, + } + if a.padding > 0 { + fields["padding"] = strings.Repeat("x", a.padding) + } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]string{ - "nonce": base64.RawURLEncoding.EncodeToString(nonce), - "proof": base64.RawURLEncoding.EncodeToString(proof), - "token": "dm1.0badc0de." + strings.Repeat("A", 43), - }) - }) - ln, err := tls.Listen("tcp", "127.0.0.1:0", tlsid.ServerConfig(cert)) - if err != nil { - t.Fatal(err) + json.NewEncoder(w).Encode(fields) } - srv := &http.Server{Handler: mux, ErrorLog: log.New(io.Discard, "", 0)} - go srv.Serve(ln) - t.Cleanup(func() { srv.Close() }) - return ln.Addr().String() +} + +// impostor is a server with a certificate of its own that answers the probe +// as an agent does and a pairing request itself, with what answer returns. +// It returns the address it listens on. +func impostor(t *testing.T, answer func(phoneNonce, fingerprint []byte) reply) string { + t.Helper() + cert := strangerCert(t) + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", healthy) + mux.HandleFunc("POST /agent/v1/pair", answerPairing(fingerprintOf(t, cert), answer)) + return serveTLS(t, cert, mux) } // someCode is a pairing code that no agent has issued. @@ -499,17 +589,17 @@ func someCode(t *testing.T) string { func TestAPhoneRefusesAnAnswerItCannotVerify(t *testing.T) { // Whoever terminates the phone's connection can answer the pairing // request with anything. Without the code it cannot make the proof. - addr := impostor(t, func(_, _ []byte) (nonce, proof []byte) { - nonce, proof = make([]byte, pairing.NonceLen), make([]byte, sha256.Size) + addr := impostor(t, func(_, _ []byte) reply { + nonce, proof := make([]byte, pairing.NonceLen), make([]byte, sha256.Size) rand.Read(nonce) rand.Read(proof) - return nonce, proof + return reply{nonce: nonce, proof: proof, token: madeUpToken} }) p := newPhone(t, "https", addr) if status, err := p.pair(someCode(t), "Pixel 8"); err == nil || !strings.Contains(err.Error(), "could not prove it holds the code") { t.Fatalf("status %d, err = %v, want the phone to refuse an answer it cannot verify", status, err) } - if p.token != "" || p.pin != nil { + if p.token != "" || p.trusted() != nil { t.Fatal("the phone kept a token or a pin from an answer it could not verify") } } @@ -532,15 +622,15 @@ func TestAPhoneRefusesAnAgentNonceOrProofOfTheWrongLength(t *testing.T) { {"a proof one byte short", pairing.NonceLen, func(right []byte) []byte { return right[:len(right)-1] }, false}, {"a proof one byte long", pairing.NonceLen, func(right []byte) []byte { return append(right, 0) }, false}, } { - addr := impostor(t, func(phoneNonce, fingerprint []byte) (nonce, proof []byte) { - nonce = make([]byte, c.nonceLen) + addr := impostor(t, func(phoneNonce, fingerprint []byte) reply { + nonce := make([]byte, c.nonceLen) rand.Read(nonce) - return nonce, c.proof(pairing.AgentProof(code, fingerprint, phoneNonce, nonce)) + return reply{nonce: nonce, proof: c.proof(pairing.AgentProof(code, fingerprint, phoneNonce, nonce)), token: madeUpToken} }) p := newPhone(t, "https", addr) status, err := p.pair(code, "Pixel 8") if c.accepted { - if err != nil || status != http.StatusOK || p.token == "" || p.pin == nil { + if err != nil || status != http.StatusOK || p.token == "" || p.trusted() == nil { t.Errorf("%s: the phone did not pair: %d, %v", c.name, status, err) } continue @@ -548,54 +638,144 @@ func TestAPhoneRefusesAnAgentNonceOrProofOfTheWrongLength(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "not 32 bytes") { t.Errorf("%s: status %d, err = %v, want the phone to refuse the answer for its form", c.name, status, err) } - if p.token != "" || p.pin != nil { + if p.token != "" || p.trusted() != nil { t.Errorf("%s: the phone kept a token or a pin", c.name) } } } +func TestAPhoneRefusesAnAnswerThatIsTooLarge(t *testing.T) { + // The server holds the code and every field of its answer is right. The + // answer only carries far more than a pairing answer has to. + code := someCode(t) + addr := impostor(t, func(phoneNonce, fingerprint []byte) reply { + r := rightReply(code, phoneNonce, fingerprint) + r.padding = 2 * maxPairAnswer + return r + }) + p := newPhone(t, "https", addr) + if status, err := p.pair(code, "Pixel 8"); err == nil || !strings.Contains(err.Error(), "too large") { + t.Fatalf("status %d, err = %v, want the phone to refuse an answer of that size", status, err) + } + if p.token != "" || p.trusted() != nil { + t.Fatal("the phone kept a token or a pin from an answer that was too large") + } +} + +func TestAPhoneRefusesAnAnswerWithoutAToken(t *testing.T) { + // The server holds the code and proves it. It only gives the phone + // nothing to come back with. + code := someCode(t) + addr := impostor(t, func(phoneNonce, fingerprint []byte) reply { + r := rightReply(code, phoneNonce, fingerprint) + r.token = "" + return r + }) + p := newPhone(t, "https", addr) + if status, err := p.pair(code, "Pixel 8"); err == nil || !strings.Contains(err.Error(), "no token") { + t.Fatalf("status %d, err = %v, want the phone to refuse an answer without a token", status, err) + } + if p.token != "" || p.trusted() != nil { + t.Fatal("the phone kept a pin from an answer without a token") + } +} + +func TestAPhoneFollowsNoRedirectWhilePairing(t *testing.T) { + // The server holds the code, and where it sends the phone the answers + // are the right ones: a phone that followed would end up paired. + code := someCode(t) + for _, c := range []struct { + name string + redirected string // the request that is answered with a redirect + asked string // all that the phone may ask of the server + status int // how the attempt ends: with this status, + fails string // or with an error that says this + }{ + {"the probe", "GET /healthz", "GET /healthz\n", 0, "redirect"}, + {"the pairing request", "POST /agent/v1/pair", "GET /healthz\nPOST /agent/v1/pair\n", http.StatusTemporaryRedirect, ""}, + } { + cert := strangerCert(t) + right := answerPairing(fingerprintOf(t, cert), func(phoneNonce, fingerprint []byte) reply { + return rightReply(code, phoneNonce, fingerprint) + }) + // A 307 keeps method and body: whoever follows it sends the proof a + // second time, to where the answer points. + moved := func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/moved"+r.URL.Path, http.StatusTemporaryRedirect) + } + var asked syncBuf + mux := http.NewServeMux() + for pattern, handler := range map[string]http.HandlerFunc{ + "GET /healthz": healthy, + "POST /agent/v1/pair": right, + "GET /moved/healthz": healthy, + "POST /moved/agent/v1/pair": right, + } { + if pattern == c.redirected { + handler = moved + } + mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(&asked, r.Method, r.URL.Path) + handler(w, r) + }) + } + p := newPhone(t, "https", serveTLS(t, cert, mux)) + status, err := p.pair(code, "Pixel 8") + if c.fails == "" && (err != nil || status != c.status) { + t.Errorf("%s was answered with a redirect, and the attempt ended with %d, %v, want the redirect's status %d", c.name, status, err, c.status) + } + if c.fails != "" && (err == nil || !strings.Contains(err.Error(), c.fails)) { + t.Errorf("%s was answered with a redirect, and the attempt ended with %d, %v, want an error about the %s", c.name, status, err, c.fails) + } + if p.token != "" || p.trusted() != nil { + t.Errorf("%s was answered with a redirect, and the phone kept a token or a pin", c.name) + } + if got := asked.String(); got != c.asked { + t.Errorf("%s was answered with a redirect, and the phone asked:\n%swant only:\n%s", c.name, got, c.asked) + } + } +} + func TestAPhoneDoesNotWaitForEverForTheAnswer(t *testing.T) { // A server that takes the pairing request and then says nothing, for as // long as the phone stays. arrived := make(chan struct{}) mux := http.NewServeMux() - mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) }) + mux.HandleFunc("GET /healthz", healthy) mux.HandleFunc("POST /agent/v1/pair", func(_ http.ResponseWriter, r *http.Request) { close(arrived) <-r.Context().Done() }) - ln, err := tls.Listen("tcp", "127.0.0.1:0", tlsid.ServerConfig(strangerCert(t))) - if err != nil { - t.Fatal(err) - } - srv := &http.Server{Handler: mux, ErrorLog: log.New(io.Discard, "", 0)} - go srv.Serve(ln) - t.Cleanup(func() { srv.Close() }) - - p := newPhone(t, "https", ln.Addr().String()) + p := newPhone(t, "https", serveTLS(t, strangerCert(t), mux)) code := someCode(t) + // When the phone's time is up is for the test to say, and it says so the + // moment the request is with the server: never while a connection is + // still being set up, however slow the machine. + ctx, timeIsUp := context.WithCancel(context.Background()) + defer timeIsUp() ended := make(chan error, 1) go func() { - // A shorter limit than a phone sets, so that the test is quick, and - // still many times what it takes to get the request to the server. - _, err := p.pairWithin(time.Second, code, "Pixel 8") + _, err := p.pairContext(ctx, code, "Pixel 8") ended <- err }() select { + case <-arrived: case err := <-ended: - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("err = %v, want the attempt to run out of time", err) - } + t.Fatalf("the attempt ended before its request was with the server: %v", err) case <-time.After(5 * time.Second): - t.Fatal("the phone still waits for an answer") + t.Fatal("the pairing request did not reach the server") } + timeIsUp() select { - case <-arrived: - default: - t.Fatal("the attempt ran out of time before its request was with the server") + case err := <-ended: + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want the attempt to end because its time is up", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the phone still waits for an answer") } - if p.token != "" || p.pin != nil { - t.Fatal("the phone kept a token or a pin from an attempt that ran out of time") + if p.token != "" || p.trusted() != nil { + t.Fatal("the phone kept a token or a pin from an attempt that ended without an answer") } } @@ -866,6 +1046,57 @@ func TestPairReportsHowThePairingEnded(t *testing.T) { } } +func TestWhatPairSaysWhenItIsOver(t *testing.T) { + const ( + paired = "Paired: Pixel 8 (id 0a1b2c3d, read-only)\n" + cancelled = `pairing cancelled; the code no longer works. If a phone used it in the same moment it is paired: check with "docker-mobile-agent devices"` + stopped = `the agent stopped before the pairing ended; the code no longer works. If a phone used it in the same moment it is paired, and still is when the agent runs again: check then with "docker-mobile-agent devices"` + ) + pixel := &admin.DeviceInfo{ID: "0a1b2c3d", Name: "Pixel 8", Role: "readonly"} + ended := func(event string) *admin.Event { return &admin.Event{Event: event} } + // What the client returns when the command is interrupted while it + // connects, and what it returns for a line that is not an event. + whileConnecting := fmt.Errorf(`Post "http://agent/pair": %w`, context.Canceled) + unreadable := errors.New("unreadable answer from the agent: unexpected end of JSON input") + for _, c := range []struct { + name string + end *admin.Event // the event that ended the pairing, if any + err error // what the client returned + shown bool // whether a code had been shown + stdout string + fails string // what the command ends with; empty when it succeeds + }{ + {"paired", &admin.Event{Event: "paired", Device: pixel}, nil, true, paired, ""}, + {"paired, and interrupted in the same moment", &admin.Event{Event: "paired", Device: pixel}, context.Canceled, true, paired, ""}, + {"paired, and the agent stopped in the same moment", &admin.Event{Event: "paired", Device: pixel}, admin.ErrStopped, true, paired, ""}, + {"paired, without the device", ended("paired"), nil, true, "", + `the agent says a phone was paired, but not which one: look at "docker-mobile-agent devices"`}, + {"expired", ended("expired"), nil, true, "", "the code expired before a phone used it; run pair again"}, + {"expired, and interrupted in the same moment", ended("expired"), context.Canceled, true, "", "the code expired before a phone used it; run pair again"}, + {"replaced", ended("replaced"), nil, true, "", "another pair command replaced this code"}, + {"voided", ended("voided"), nil, true, "", "too many wrong attempts: the code was voided; run pair again"}, + {"failed", &admin.Event{Event: "failed", Error: "write devices.json: no space left on device"}, nil, true, "", + "the phone proved the code but the agent could not store it: write devices.json: no space left on device"}, + {"an event the command does not know", ended("exploded"), nil, true, "", `pairing ended as "exploded"`}, + {"interrupted while it waited for the phone", nil, context.Canceled, true, "", cancelled}, + {"interrupted before it had shown a code", nil, context.Canceled, false, "", "pairing cancelled before a code was shown"}, + {"interrupted while it connected", nil, whileConnecting, false, "", "pairing cancelled before a code was shown"}, + {"the agent stopped while the command waited for the phone", nil, admin.ErrStopped, true, "", stopped}, + {"the agent stopped before the command had shown a code", nil, admin.ErrStopped, false, "", "the agent stopped before the pairing ended"}, + {"no agent", nil, admin.ErrNotRunning, false, "", "the agent is not running on this state folder"}, + {"an answer that cannot be read", nil, unreadable, true, "", "unreadable answer from the agent: unexpected end of JSON input"}, + } { + stdout, err := pairEnding(c.end, c.err, c.shown) + fails := "" + if err != nil { + fails = err.Error() + } + if stdout != c.stdout || fails != c.fails { + t.Errorf("%s:\n stdout %q\n fails with %q\nwant\n stdout %q\n fails with %q", c.name, stdout, fails, c.stdout, c.fails) + } + } +} + func TestAPairingThatEndedIsReportedThoughTheCommandWasInterrupted(t *testing.T) { // The whole pairing, its good end included, is in the agent's answer // before the command has printed the code, and the command is interrupted @@ -896,7 +1127,13 @@ func TestAnInterruptedPairClaimsOnlyWhatItKnows(t *testing.T) { w.(http.Flusher).Flush() <-r.Context().Done() }) - ctx, cancel := context.WithCancel(context.Background()) + // The interrupt comes when the command prints the words it is known to + // print. Should it ever print others, the command and the agent would + // wait for each other for good: so the command's time is limited, and + // the check below then fails on what it said. + limited, stop := context.WithTimeout(context.Background(), 5*time.Second) + defer stop() + ctx, cancel := context.WithCancel(limited) defer cancel() out := &interrupted{interrupt: cancel} var errOut bytes.Buffer diff --git a/agent/internal/admin/admin.go b/agent/internal/admin/admin.go index 9d7a984..7b8bda4 100644 --- a/agent/internal/admin/admin.go +++ b/agent/internal/admin/admin.go @@ -59,7 +59,9 @@ type PairRequest struct { } // Event names. A pairing stream is one "started" event followed by exactly -// one of the others. +// one of the others. When the request ends before its pairing does, the +// stream breaks off after "started", unless a phone was paired in that very +// moment: then "paired" still follows. const ( EventStarted = "started" ) @@ -293,9 +295,10 @@ func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) { s.Pairing.Expire(p.ID) result = <-done case <-r.Context().Done(): - // The command line went away: the code must not stay usable. The - // pairing may have ended a moment before, even with a device stored, - // and Cancel then changes nothing. So the result is read, not assumed. + // The request is over: the command line went away, or the agent is + // stopping. Either way the code must not stay usable. The pairing may + // have ended a moment before, even with a device stored, and Cancel + // then changes nothing. So the result is read, not assumed. s.Pairing.Cancel(p.ID) result = <-done left = true @@ -305,11 +308,15 @@ func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) { } else { s.logf("pairing ended", "outcome", string(result.Outcome)) } - if left { + if left && result.Outcome != pairing.Paired { // No ending event: the request is over, so the stream just breaks // off after "started". return } + // A phone that was paired is reported also when the request is over. A + // command line that waits while the agent stops is still reading, and + // has to learn that a phone holds a token now. To one that has gone + // away the write fails, and nothing is lost by that. e := Event{Event: string(result.Outcome), Error: result.Err} if result.Outcome == pairing.Paired { info := infoOf(result.Device) @@ -353,7 +360,12 @@ func (s *Server) handleRevoke(w http.ResponseWriter, r *http.Request) { if err != nil { // The device is back in the list and none of its requests was // closed. The answer says that first: the cause alone names a file, - // and reads as if the phone were gone. + // and reads as if the phone were gone. The log gets a warning with + // the device and the cause: a pairing that could not be stored has + // its line there too. + if s.Log != nil { + s.Log.Warn("device not revoked", "device", id, "error", err.Error()) + } writeJSON(w, http.StatusInternalServerError, errorResponse{"the device is still paired and its connections stay open: the removal could not be stored: " + err.Error()}) return } diff --git a/agent/internal/admin/admin_test.go b/agent/internal/admin/admin_test.go index 302e699..221f145 100644 --- a/agent/internal/admin/admin_test.go +++ b/agent/internal/admin/admin_test.go @@ -13,6 +13,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "regexp" "runtime" "strconv" "strings" @@ -474,6 +475,12 @@ func TestRevokeSaysTheDeviceIsStillPairedWhenTheRemovalCannotBeStored(t *testing t.Errorf("the error does not say %q: %v", want, err) } } + // The agent's log has it too: one warning, with the device and the + // cause and nothing else. + warning := regexp.MustCompile(`(?m)^time=\S+ level=WARN msg="device not revoked" device=` + dev.ID + ` error="write devices\.json: .*"$`) + if log := f.log.String(); strings.Count(log, "level=WARN") != 1 || !warning.MatchString(log) { + t.Errorf("the log does not have the one warning that the device was not revoked:\n%s", log) + } // And so it is: the device works as before and its request is open. if _, ok := devices.Authenticate(token); !ok { t.Fatal("the device no longer authenticates") @@ -926,6 +933,20 @@ func TestTheLogSaysPairedWhenTheCommandLeavesWhileThePhoneRedeems(t *testing.T) if list := f.devices.List(); len(list) != 1 || list[0].ID != got.device.ID { t.Fatalf("devices = %+v, want the one that was paired", list) } + // The answer says so as well. A command that is still there to read it, + // as it is when the agent is the one that stops, learns of the phone. + select { + case line := <-w.lines: + var last Event + if err := json.Unmarshal(line, &last); err != nil { + t.Fatalf("the last line of the answer is not an event: %v", err) + } + if last.Event != "paired" || last.Device == nil || last.Device.ID != got.device.ID { + t.Fatalf("the answer ends with the event %q, want paired with device %s", last.Event, got.device.ID) + } + default: + t.Fatal("the answer ends without saying that a phone was paired") + } log := f.log.String() if strings.Contains(log, "outcome=cancelled") { t.Fatalf("the log calls a pairing that stored a device cancelled:\n%s", log) diff --git a/agent/internal/admin/client.go b/agent/internal/admin/client.go index 8f6fc02..4f14273 100644 --- a/agent/internal/admin/client.go +++ b/agent/internal/admin/client.go @@ -104,9 +104,11 @@ func (c *Client) do(ctx context.Context, method, path string, body any) (*http.R // Once the event that ends the pairing has been handed to onEvent, Pair // returns nil, whatever has become of ctx by then: how the pairing ended is // known, and a phone that was paired stays paired. An error therefore means -// that the pairing did not begin, or that the caller did not see it end: -// then it is the error of ctx when ctx ended first, and ErrStopped when the -// stream broke off. +// that the pairing did not begin, or that the caller did not see it end. +// Where it began, that is the error of ctx when ctx ended first, ErrStopped +// when the stream broke off, and an error of its own, "unreadable answer +// from the agent", when a line of the stream is not JSON that reads as an +// event. func (c *Client) Pair(ctx context.Context, req PairRequest, onEvent func(Event)) error { resp, err := c.do(ctx, http.MethodPost, "/pair", req) if err != nil { From 64f9d8c974a39ec69ff11ed853938d95c56d1c5d Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 23:10:48 +0530 Subject: [PATCH 25/32] fix(agent): bound how long a caller without credentials may take to send its request --- agent/internal/server/handler.go | 18 ++- agent/internal/server/handler_test.go | 222 +++++++++++++++++++++++++- agent/internal/server/middleware.go | 37 +++++ agent/internal/server/pair.go | 12 +- 4 files changed, 274 insertions(+), 15 deletions(-) diff --git a/agent/internal/server/handler.go b/agent/internal/server/handler.go index 186b30d..8606dac 100644 --- a/agent/internal/server/handler.go +++ b/agent/internal/server/handler.go @@ -42,6 +42,10 @@ type Options struct { Conns *conns.Registry // Version is what whoami and a pairing report; it may be empty. Version string + // RequestTimeout is how long a caller that has not been authenticated may + // take to send the rest of its request once the headers are in. Zero + // means 10 seconds; tests shorten it. + RequestTimeout time.Duration // Log receives the access log; nil discards it. Log *slog.Logger // Now is the clock; nil means time.Now. @@ -66,6 +70,9 @@ func New(o Options) (http.Handler, error) { if o.Now == nil { o.Now = time.Now } + if o.RequestTimeout == 0 { + o.RequestTimeout = defaultRequestTimeout + } dockerProxy, err := proxy.New(o.DockerHost) if err != nil { return nil, err @@ -90,15 +97,18 @@ func New(o Options) (http.Handler, error) { w.Write([]byte("ok")) }) mux.HandleFunc("POST /agent/v1/pair", s.handlePair) - mux.Handle("GET /agent/v1/whoami", authn.Require(http.HandlerFunc(s.handleWhoami))) + // Every request starts under a read deadline (see the last line). On the + // three routes that need a credential it is lifted as soon as the caller + // is known. + mux.Handle("GET /agent/v1/whoami", authn.Require(liftReadDeadline(http.HandlerFunc(s.handleWhoami)))) // Nothing else under /agent/ exists; it must not fall through to Docker. mux.HandleFunc("/agent/", func(w http.ResponseWriter, _ *http.Request) { auth.WriteError(w, http.StatusNotFound, "not found") }) - mux.Handle("GET /exec/{id}/ws", authn.Require(fullOnly(execHandler))) - mux.Handle("/", authn.Require(roleGate(limitBody(dockerProxy)))) + mux.Handle("GET /exec/{id}/ws", authn.Require(liftReadDeadline(fullOnly(execHandler)))) + mux.Handle("/", authn.Require(liftReadDeadline(roleGate(limitBody(dockerProxy))))) - return accessLog(o.Log, o.Now, rejectBrowsers(mux)), nil + return readDeadline(o.RequestTimeout, accessLog(o.Log, o.Now, rejectBrowsers(mux))), nil } type server struct { diff --git a/agent/internal/server/handler_test.go b/agent/internal/server/handler_test.go index 2435dfe..47e120c 100644 --- a/agent/internal/server/handler_test.go +++ b/agent/internal/server/handler_test.go @@ -1,20 +1,24 @@ package server import ( + "bufio" "bytes" "crypto/rand" "encoding/base64" "encoding/json" "io" "log/slog" + "net" "net/http" "net/http/httptest" "path/filepath" + "strconv" "strings" "sync" "testing" "time" + "github.com/gorilla/websocket" "github.com/retransmit/docker-mobile/agent/internal/conns" "github.com/retransmit/docker-mobile/agent/internal/pairing" "github.com/retransmit/docker-mobile/agent/internal/state" @@ -79,7 +83,9 @@ type fixture struct { fp []byte } -func newFixture(t *testing.T, legacyToken string, fingerprint []byte) *fixture { +// newFixture builds a handler over a fresh state folder and a fake daemon. +// configure changes the options the handler is built with. +func newFixture(t *testing.T, legacyToken string, fingerprint []byte, configure ...func(*Options)) *fixture { t.Helper() dir, err := state.Open(filepath.Join(t.TempDir(), "data")) if err != nil { @@ -99,7 +105,7 @@ func newFixture(t *testing.T, legacyToken string, fingerprint []byte) *fixture { log: &bytes.Buffer{}, fp: fingerprint, } - f.handler, err = New(Options{ + o := Options{ DockerHost: "tcp://" + f.daemon.Listener.Addr().String(), Devices: devices, LegacyToken: legacyToken, @@ -110,7 +116,11 @@ func newFixture(t *testing.T, legacyToken string, fingerprint []byte) *fixture { Version: "1.2.3", Log: slog.New(slog.NewTextHandler(f.log, nil)), Now: c.now, - }) + } + for _, change := range configure { + change(&o) + } + f.handler, err = New(o) if err != nil { t.Fatalf("New: %v", err) } @@ -645,3 +655,209 @@ func TestTheFailureWarningNamesTheAddressItself(t *testing.T) { t.Fatalf("a warning names a network instead of an address: %s", f.log.String()) } } + +// requestTimeout is the read deadline in the tests below: more than a +// request that is sent at once needs, and short enough to wait out. +const requestTimeout = 250 * time.Millisecond + +// patience is how long these tests wait for something that is due. It is far +// more than anything here takes, also on a slow machine, and it is what ends +// a test that would otherwise wait for ever. +const patience = 5 * time.Second + +// hurried gives a fixture requestTimeout as its read deadline. +func hurried(o *Options) { o.RequestTimeout = requestTimeout } + +// listen serves the fixture's handler on a real listener, as the agent does, +// and returns the address. A read deadline is set on a connection, and the +// recorder of the other tests has none. +func (f *fixture) listen(t *testing.T) string { + t.Helper() + srv := httptest.NewServer(f.handler) + t.Cleanup(srv.Close) + return srv.Listener.Addr().String() +} + +// dial opens a raw connection to the agent at addr. What is read or written +// on it fails once wait is over: an agent that does not answer then fails a +// check instead of hanging the test. +func dial(t *testing.T, addr string, wait time.Duration) net.Conn { + t.Helper() + conn, err := net.DialTimeout("tcp", addr, patience) + if err != nil { + t.Fatal(err) + } + // This runs before the cleanup of the server it connects to, which was + // registered earlier: a server that closes waits for its connections. + t.Cleanup(func() { conn.Close() }) + conn.SetDeadline(time.Now().Add(wait)) + return conn +} + +// bodyNeverComes sends the head of a POST for path that announces a body, +// and then nothing more. It returns the status of the answer. That the +// answer comes, and that the agent closes the connection after it, is +// checked here: both within the read deadline and a margin. +func bodyNeverComes(t *testing.T, addr, path string) int { + t.Helper() + conn := dial(t, addr, requestTimeout+patience) + began := time.Now() + head := "POST " + path + " HTTP/1.1\r\nHost: agent\r\nContent-Type: application/json\r\nContent-Length: 17\r\n\r\n" + if _, err := io.WriteString(conn, head); err != nil { + t.Fatal(err) + } + br := bufio.NewReader(conn) + resp, err := http.ReadResponse(br, nil) + if err != nil { + t.Fatalf("POST %s without its body: no answer after %v: %v", path, time.Since(began).Round(time.Millisecond), err) + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + if _, err := br.ReadByte(); err != io.EOF { + t.Fatalf("POST %s without its body: the connection is still open after %v: %v", path, time.Since(began).Round(time.Millisecond), err) + } + return resp.StatusCode +} + +func TestACallerWithoutCredentialsIsAnsweredThoughItsBodyNeverComes(t *testing.T) { + f := newFixture(t, legacy, agentFP, hurried) + if status := bodyNeverComes(t, f.listen(t), "/containers/create"); status != http.StatusUnauthorized { + t.Fatalf("code = %d, want 401", status) + } + if n := len(f.daemon.requests()); n != 0 { + t.Fatalf("%d requests reached the daemon", n) + } +} + +func TestAPairingRequestIsAnsweredThoughItsBodyNeverComes(t *testing.T) { + f := newFixture(t, "", agentFP, hurried) + if status := bodyNeverComes(t, f.listen(t), "/agent/v1/pair"); status != http.StatusBadRequest { + t.Fatalf("code = %d, want 400", status) + } +} + +func TestACallerWithCredentialsMayTakeItsTimeOverTheBody(t *testing.T) { + f := newFixture(t, legacy, agentFP, hurried) + const body = `{"Image":"nginx"}` + conn := dial(t, f.listen(t), 2*requestTimeout+patience) + head := "POST /containers/create HTTP/1.1\r\nHost: agent\r\nAuthorization: Bearer " + legacy + + "\r\nContent-Type: application/json\r\nContent-Length: " + strconv.Itoa(len(body)) + "\r\n\r\n" + if _, err := io.WriteString(conn, head); err != nil { + t.Fatal(err) + } + time.Sleep(2 * requestTimeout) + if _, err := io.WriteString(conn, body); err != nil { + t.Fatalf("sending the body after twice the read deadline: %v", err) + } + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) + if err != nil { + t.Fatalf("no answer to a body sent after twice the read deadline: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("code = %d, want 200", resp.StatusCode) + } + if seen := f.daemon.requests(); len(seen) != 1 || !strings.HasSuffix(seen[0], " "+body) { + t.Fatalf("the daemon saw %q, want the one request with its body", seen) + } +} + +// eventLine is what liveDaemon sends on a stream. +const eventLine = "{\"Type\":\"container\"}\n" + +// liveDaemon is a fake Docker daemon for requests that stay open. It starts +// a terminal the way the daemon does: POST /exec//start is answered with +// 101 on a connection it takes over, and from then on it sends back whatever +// it is sent. Every other request is a stream: it gets eventLine at once, and +// again for every value on more, until the caller goes away. +type liveDaemon struct { + *httptest.Server + more chan struct{} +} + +func newLiveDaemon(t *testing.T) *liveDaemon { + t.Helper() + // Room for one value, so that asking for a line never blocks, also when + // the stream it is meant for has ended. + d := &liveDaemon{more: make(chan struct{}, 1)} + d.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/exec/") { + io.Copy(io.Discard, r.Body) + conn, rw, err := w.(http.Hijacker).Hijack() + if err != nil { + return + } + defer conn.Close() + rw.WriteString("HTTP/1.1 101 UPGRADED\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n") + rw.Flush() + io.Copy(conn, rw) + return + } + w.Header().Set("Content-Type", "application/json") + for { + w.Write([]byte(eventLine)) + w.(http.Flusher).Flush() + select { + case <-d.more: + case <-r.Context().Done(): + return + } + } + })) + t.Cleanup(d.Close) + return d +} + +func TestAStreamAndATerminalOutliveTheReadDeadline(t *testing.T) { + d := newLiveDaemon(t) + f := newFixture(t, legacy, agentFP, hurried, func(o *Options) { + o.DockerHost = "tcp://" + d.Listener.Addr().String() + }) + addr := f.listen(t) + const wait = 3 * requestTimeout + + // A stream. Its answer is never closed here: closing it would read the + // stream to its end. Closing the connection, when the test is over, ends it. + conn := dial(t, addr, wait+patience) + if _, err := io.WriteString(conn, "GET /events HTTP/1.1\r\nHost: agent\r\nAuthorization: Bearer "+legacy+"\r\n\r\n"); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) + if err != nil { + t.Fatalf("open the stream: %v", err) + } + stream := bufio.NewReader(resp.Body) + if line, err := stream.ReadString('\n'); err != nil || line != eventLine { + t.Fatalf("the stream did not start: %q, %v", line, err) + } + + // A terminal: what is typed into it comes back from the daemon. + dialer := websocket.Dialer{HandshakeTimeout: patience} + ws, _, err := dialer.Dial("ws://"+addr+"/exec/abc123/ws", http.Header{"Authorization": {"Bearer " + legacy}}) + if err != nil { + t.Fatalf("open the terminal: %v", err) + } + t.Cleanup(func() { ws.Close() }) + typed := func(text string) (string, error) { + ws.SetWriteDeadline(time.Now().Add(patience)) + if err := ws.WriteMessage(websocket.BinaryMessage, []byte(text)); err != nil { + return "", err + } + ws.SetReadDeadline(time.Now().Add(patience)) + _, back, err := ws.ReadMessage() + return string(back), err + } + if back, err := typed("before"); err != nil || back != "before" { + t.Fatalf("the terminal is not through to the daemon: %q, %v", back, err) + } + + time.Sleep(wait) + + d.more <- struct{}{} + if line, err := stream.ReadString('\n'); err != nil || line != eventLine { + t.Errorf("the stream did not outlive the read deadline: %q, %v", line, err) + } + if back, err := typed("after"); err != nil || back != "after" { + t.Errorf("the terminal did not outlive the read deadline: %q, %v", back, err) + } +} diff --git a/agent/internal/server/middleware.go b/agent/internal/server/middleware.go index 71fb8f2..a5b3ba0 100644 --- a/agent/internal/server/middleware.go +++ b/agent/internal/server/middleware.go @@ -28,6 +28,43 @@ const maxBody = 16 << 20 // loads and file uploads into a container. var uploads = regexp.MustCompile(`^(/v[0-9]+\.[0-9]+)?(/build|/images/load|/containers/[^/]+/archive)$`) +// defaultRequestTimeout is how long a caller that has not been authenticated +// gets to send the rest of its request once the headers are in. +const defaultRequestTimeout = 10 * time.Second + +// readDeadline puts every request under a read deadline, d from now, before +// anything else looks at it. net/http reads the rest of a request's body +// before it sends the answer, and the agent's server bounds only how long the +// headers may take. Without this deadline a request that announces a body and +// never sends it would get no answer and keep its connection for good. +// +// A writer that cannot set a deadline is not an error, so what +// SetReadDeadline returns is ignored: the recorder of a test has no +// connection that could be kept. +func readDeadline(d time.Duration, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NewResponseController(w).SetReadDeadline(time.Now().Add(d)) + next.ServeHTTP(w, r) + }) +} + +// liftReadDeadline takes the read deadline off again. It stands directly +// behind authentication: a paired device uploads build contexts and images +// and holds streams and terminals open, and none of that may be cut. +// +// A request without a body needs this as much as an upload. The deadline +// belongs to the connection, and net/http keeps a read pending on the +// connection while a handler runs: that is how it notices a client that went +// away. A deadline that passes fails that read, and the request's context +// ends with it. A stream left under the deadline would end when the time is +// up. +func liftReadDeadline(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NewResponseController(w).SetReadDeadline(time.Time{}) + next.ServeHTTP(w, r) + }) +} + // rejectBrowsers refuses anything a web page sent. The app never sends an // Origin header; a browser always does on a cross-site request. func rejectBrowsers(next http.Handler) http.Handler { diff --git a/agent/internal/server/pair.go b/agent/internal/server/pair.go index 54cc6a0..fed66b5 100644 --- a/agent/internal/server/pair.go +++ b/agent/internal/server/pair.go @@ -9,7 +9,6 @@ import ( "math" "net/http" "strconv" - "time" "github.com/retransmit/docker-mobile/agent/internal/auth" "github.com/retransmit/docker-mobile/agent/internal/pairing" @@ -19,8 +18,6 @@ import ( const ( // maxPairBody is far more than a pairing request needs. maxPairBody = 4 << 10 - // pairBodyTimeout is how long a pairing request may take to arrive. - pairBodyTimeout = 10 * time.Second // proofLen is the length of a proof: one HMAC-SHA256 output. proofLen = sha256.Size ) @@ -65,13 +62,12 @@ func (s *server) handlePair(w http.ResponseWriter, r *http.Request) { auth.WriteError(w, http.StatusTooManyRequests, "Too many failed attempts from this address") return } - // A stranger may call this, so the body must arrive promptly: without a - // deadline a slow sender could hold the connection open for ever. - rc := http.NewResponseController(w) - rc.SetReadDeadline(time.Now().Add(pairBodyTimeout)) + // A stranger may call this, so the body must arrive promptly. The read + // deadline that every request starts under sees to that, and nothing + // here lifts it: it has to hold until the answer is written, because + // net/http reads the rest of the body before it sends the answer. var req pairRequest body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxPairBody)) - rc.SetReadDeadline(time.Time{}) if err != nil || json.Unmarshal(body, &req) != nil || req.V != 1 { auth.WriteError(w, http.StatusBadRequest, "malformed pairing request") return From 45595d7425f2bacfafecedf9237e880304337767 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 23:12:21 +0530 Subject: [PATCH 26/32] fix(agent): a request that carries no token is not a failed attempt --- agent/internal/auth/authenticator.go | 12 ++++-- agent/internal/auth/authenticator_test.go | 46 ++++++++++++++++++----- agent/internal/server/handler_test.go | 15 ++++++++ 3 files changed, 60 insertions(+), 13 deletions(-) diff --git a/agent/internal/auth/authenticator.go b/agent/internal/auth/authenticator.go index 4f5b836..06300f2 100644 --- a/agent/internal/auth/authenticator.go +++ b/agent/internal/auth/authenticator.go @@ -54,8 +54,14 @@ type Authenticator struct { // whatever its address has done before: the failures of others behind the // same address must not lock it out. Any other request from an address that // has failed too often is answered with 429; the shared token is not compared -// then, so it cannot be guessed at speed. A request that fails is counted -// against its address, except while that address is blocked. +// then, so it cannot be guessed at speed. +// +// A request that fails is answered with 401 and reported to OnFailure. It is +// counted against its address only when it presented a bearer token, and not +// while that address is blocked. A request without a token tests no guess, +// so counting it would buy nothing and cost a lot: a browser tab left on the +// port, a monitor or a scanner seen through a proxy would lock out the +// phones behind the same address. func (a *Authenticator) Require(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { bearer, hasBearer := bearerToken(r) @@ -78,7 +84,7 @@ func (a *Authenticator) Require(next http.Handler) http.Handler { a.serve(w, r, state.Device{ID: LegacyDeviceID, Name: "env-token", Role: state.RoleFull}, "", next) return } - if a.Limiter != nil { + if hasBearer && a.Limiter != nil { a.Limiter.Fail(key) } if a.OnFailure != nil { diff --git a/agent/internal/auth/authenticator_test.go b/agent/internal/auth/authenticator_test.go index 93b7705..06fbbd4 100644 --- a/agent/internal/auth/authenticator_test.go +++ b/agent/internal/auth/authenticator_test.go @@ -209,20 +209,27 @@ func TestTenFailuresBlockTheAddressButNotItsPairedDevices(t *testing.T) { } } -func TestEveryKindOfFailureIsCountedOnce(t *testing.T) { +func TestAFailureIsCountedOnceWithATokenAndNotAtAllWithout(t *testing.T) { f := newFixture(t, legacy) known, _, _ := f.devices.Add("phone", state.RoleFull) gone, goneToken, _ := f.devices.Add("old phone", state.RoleFull) if _, ok, err := f.devices.Remove(gone.ID); !ok || err != nil { t.Fatalf("remove: ok = %v, err = %v", ok, err) } - cases := []struct{ name, bearer string }{ - {"no header", ""}, - {"a wrong scheme", "Basic " + legacy}, - {"a malformed device token", "Bearer dm1.no-second-dot"}, - {"an unknown device", "Bearer " + noDevice}, - {"a wrong secret for a known device", "Bearer dm1." + known.ID + "." + strings.Repeat("A", 43)}, - {"a removed device", "Bearer " + goneToken}, + cases := []struct { + name, bearer string + counted int // how often the failure counts against the address + }{ + // No bearer token, so no guess that could be counted. + {"no header", "", 0}, + {"a wrong scheme", "Basic " + legacy, 0}, + {"a bearer scheme without a token", "Bearer ", 0}, + // A token that was tested and found wrong. + {"a wrong shared token", "Bearer nope", 1}, + {"a malformed device token", "Bearer dm1.no-second-dot", 1}, + {"an unknown device", "Bearer " + noDevice, 1}, + {"a wrong secret for a known device", "Bearer dm1." + known.ID + "." + strings.Repeat("A", 43), 1}, + {"a removed device", "Bearer " + goneToken, 1}, } for i, c := range cases { remote := fmt.Sprintf("198.51.100.%d:1000", i+1) @@ -230,11 +237,12 @@ func TestEveryKindOfFailureIsCountedOnce(t *testing.T) { if rec := f.do(c.bearer, remote); rec.Code != http.StatusUnauthorized { t.Errorf("%s: code = %d, want 401", c.name, rec.Code) } + // Counted or not, every one of them is reported. if got := f.failed[before:]; len(got) != 1 || got[0] != remote { t.Errorf("%s: failures reported = %q, want one from %s", c.name, got, remote) } - if got := f.counted(remote); got != 1 { - t.Errorf("%s: %d failures counted, want 1", c.name, got) + if got := f.counted(remote); got != c.counted { + t.Errorf("%s: %d failures counted, want %d", c.name, got, c.counted) } } if len(f.seen) != 0 { @@ -242,6 +250,24 @@ func TestEveryKindOfFailureIsCountedOnce(t *testing.T) { } } +func TestRequestsWithoutATokenDoNotBlockTheAddress(t *testing.T) { + f := newFixture(t, legacy) + const remote = "203.0.113.7:40000" + // Twice as many as wrong tokens it takes to block an address. + const requests = 2 * throttle.Threshold + for i := 0; i < requests; i++ { + if rec := f.do("", remote); rec.Code != http.StatusUnauthorized { + t.Fatalf("request %d without a token: code = %d, want 401", i+1, rec.Code) + } + } + if len(f.failed) != requests { + t.Fatalf("%d failures reported, want %d", len(f.failed), requests) + } + if rec := f.do("Bearer "+legacy, remote); rec.Code != http.StatusOK { + t.Fatalf("the shared token from that address: code = %d, want 200", rec.Code) + } +} + func TestASuccessIsNeverCounted(t *testing.T) { f := newFixture(t, legacy) _, token, _ := f.devices.Add("phone", state.RoleFull) diff --git a/agent/internal/server/handler_test.go b/agent/internal/server/handler_test.go index 47e120c..dc7184f 100644 --- a/agent/internal/server/handler_test.go +++ b/agent/internal/server/handler_test.go @@ -484,6 +484,21 @@ func TestAskingWhileNothingIsPendingCountsAgainstTheAddress(t *testing.T) { } } +func TestRequestsWithoutATokenDoNotKeepTheirAddressFromPairing(t *testing.T) { + f := newFixture(t, "", agentFP) + // What a browser tab left on the port sends, twice as often as wrong + // tokens it takes to block an address. + for i := 0; i < 2*throttle.Threshold; i++ { + if rec := f.do("GET", "/favicon.ico", "", nil); rec.Code != http.StatusUnauthorized { + t.Fatalf("request %d without a token: code = %d, want 401", i+1, rec.Code) + } + } + p, _, _ := f.pairing.Start(state.RoleFull, "") + if rec, _ := f.pair(t, p.Code, agentFP, "Pixel 8"); rec.Code != http.StatusOK { + t.Fatalf("a correct proof from that address: code = %d, want 200", rec.Code) + } +} + func TestARequestThatIsCutOffStillGetsItsAccessLine(t *testing.T) { var log bytes.Buffer c := &clock{t: time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)} From abd09312b55edcef36ee89370d51b5f4bcb89722 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 23:32:38 +0530 Subject: [PATCH 27/32] fix(agent): the state folder must belong to the agent and hold nothing else --- agent/cmd/agent/main_test.go | 29 ++++ agent/internal/state/dir.go | 135 ++++++++++++++++-- agent/internal/state/os_unix.go | 20 +++ agent/internal/state/os_unix_test.go | 40 ++++++ agent/internal/state/os_windows.go | 9 ++ agent/internal/state/state_test.go | 205 +++++++++++++++++++++++++++ 6 files changed, 430 insertions(+), 8 deletions(-) create mode 100644 agent/internal/state/os_unix.go create mode 100644 agent/internal/state/os_unix_test.go create mode 100644 agent/internal/state/os_windows.go diff --git a/agent/cmd/agent/main_test.go b/agent/cmd/agent/main_test.go index 54155fd..793a1e5 100644 --- a/agent/cmd/agent/main_test.go +++ b/agent/cmd/agent/main_test.go @@ -751,6 +751,35 @@ func TestAnUnusableStateFolderIsAClearError(t *testing.T) { } } +func TestAnAgentStartsAgainOnTheFolderItHasUsed(t *testing.T) { + a := startAgent(t) + link, _, _, exit := a.startPair() + p := newPhone(t, "https", a.addr) + if status, err := p.pairWithLink(link, "Pixel 8"); err != nil || status != http.StatusOK { + t.Fatalf("pairing by link: %d, %v", status, err) + } + if got := exited(t, exit); got != 0 { + t.Fatalf("pair exited %d", got) + } + if err := a.stop(); err != nil { + t.Fatalf("serve returned %v", err) + } + // The folder holds what an agent leaves in it: the device list, the key, + // the certificate and the lock file. A folder is taken only when all that + // is in it is the agent's own, and all of this is. + dataDir := a.env["AGENT_DATA"] + for _, name := range []string{"devices.json", "tls.key", "tls.crt", "agent.lock"} { + if _, err := os.Stat(filepath.Join(dataDir, name)); err != nil { + t.Fatalf("the folder the agent has used lacks %s: %v", name, err) + } + } + again := startAgent(t, "AGENT_DATA", dataDir) + p.addr = again.addr + if got := p.status("GET", "/containers/json"); got != http.StatusOK { + t.Fatalf("the paired phone after the agent started again: %d, want 200", got) + } +} + // commandCase is one command line and what it must produce. type commandCase struct { name string diff --git a/agent/internal/state/dir.go b/agent/internal/state/dir.go index 2754b09..9277c92 100644 --- a/agent/internal/state/dir.go +++ b/agent/internal/state/dir.go @@ -3,37 +3,156 @@ package state import ( + "crypto/rand" "errors" "fmt" + "io/fs" "os" "path/filepath" "runtime" + "strings" "syscall" ) // Dir is the state folder. Only the user the agent runs as may enter it. type Dir struct{ path string } -// Open creates the folder if needed (mode 0700) and checks it is writable. +// probePrefix is how the name of a probe begins: the file that Open writes +// and removes again to find out whether the folder can store one. A random +// part follows it, so every call tries the folder with a file of its own. An +// agent that is already running on the folder loses nothing by that, and two +// agents that are started in the same moment do not get at each other's file: +// on Windows, a name they shared would fail one of them, renaming onto what +// the other is just removing. +const probePrefix = "probe." + +// ownFiles are the names of the files the agent keeps in its state folder, +// each with who writes it. Open takes a folder that was there before only if +// it holds nothing else, apart from probes. The other packages cannot be +// asked for their names, because they import this one: a file that gets +// another name there needs it here as well. +var ownFiles = []string{ + devicesFile, // the paired devices: this package + "tls.key", // the key of the agent's certificate: package tlsid + "tls.crt", // the certificate: package tlsid + "admin.sock", // the socket the command line talks to: package admin + "agent.lock", // the lock that keeps a second agent off the folder: package admin +} + +// Open returns the state folder at path, which must be the agent's own. A +// folder that is not there is created with mode 0700. A folder that is there +// is taken only if it belongs to the user the agent runs as (on Unix; on +// Windows the owner is not looked at) and holds nothing but the agent's own +// files; its mode is then set to 0700. Any other folder is refused and left +// exactly as it was: a folder that others use, such as a home folder or /tmp, +// must not be made private, and the agent's files must not lie where another +// user can replace them. +// +// A folder that cannot store a file is refused too, so that a full disk or a +// file system that cannot sync stops the agent when it starts and not at the +// first pairing. func Open(path string) (*Dir, error) { if path == "" { return nil, errors.New("state folder path is empty") } - if err := os.MkdirAll(path, 0o700); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return nil, fmt.Errorf("state folder %s: %w", path, err) } + // Mkdir says whether the folder is new, and not a look beforehand: a + // folder that someone else makes in this very moment is then checked like + // any other that was there. When Mkdir fails and nothing is at the path, + // its error is the one to report. + if mkdirErr := os.Mkdir(path, 0o700); mkdirErr != nil { + info, err := os.Stat(path) + if err != nil { + return nil, fmt.Errorf("state folder %s: %w", path, mkdirErr) + } + if err := checkExisting(path, info); err != nil { + return nil, err + } + } if err := os.Chmod(path, 0o700); err != nil { return nil, fmt.Errorf("state folder %s: %w", path, err) } - probe, err := os.CreateTemp(path, ".probe-*") + d := &Dir{path: path} + if err := d.probe(probePrefix + rand.Text()); err != nil { + return nil, err + } + return d, nil +} + +// probe finds out whether the folder can store a file. It writes one called +// name the way every file of the agent is written, synced and renamed into +// place, and removes it again. +func (d *Dir) probe(name string) error { + err := d.WriteFile(name, []byte("probe\n")) + os.Remove(d.Path(name)) + if err != nil { + return fmt.Errorf("state folder %s cannot store a file: %w", d.path, err) + } + return nil +} + +// checkExisting decides whether what was at path before Open may be the +// state folder. info is what Stat says about it. Nothing is changed here. +func checkExisting(path string, info fs.FileInfo) error { + if !info.IsDir() { + return fmt.Errorf("state folder %s is not a folder", path) + } + if err := checkOwner(path, info); err != nil { + return err + } + entries, err := os.ReadDir(path) if err != nil { - return nil, fmt.Errorf("state folder %s is not writable: %w", path, err) + return fmt.Errorf("state folder %s: %w", path, err) } - probe.Close() - os.Remove(probe.Name()) - return &Dir{path: path}, nil + for _, e := range entries { + if !isOwn(e) { + return fmt.Errorf("state folder %s holds other files (%q is one): the agent needs a folder of its own, set AGENT_DATA to one that is empty or does not exist yet", path, e.Name()) + } + } + return nil } +// sameUser refuses a folder whose owner is not the user the agent runs as: +// owner is the user id the folder belongs to, user the effective one of the +// agent. Whoever owns the folder can replace what is in it, the device list +// and the key included. +func sameUser(path string, owner, user uint32) error { + if owner != user { + return fmt.Errorf("state folder %s belongs to another user (uid %d, and the agent runs as uid %d): run the agent as that user, or set AGENT_DATA to a folder of the agent's own", path, owner, user) + } + return nil +} + +// isOwn reports whether an entry of the state folder is the agent's own: one +// of ownFiles, a probe, or a temporary file that WriteFile made for one of +// those. An agent may be writing such a file right now, or have left it +// behind when it died. A folder named lost+found passes as well: a freshly +// formatted disk that is mounted at the path comes with one. +func isOwn(e fs.DirEntry) bool { + name := e.Name() + if name == "lost+found" { + return e.IsDir() + } + for _, own := range ownFiles { + if name == own || begins(name, tempPrefix(own)) { + return true + } + } + // The temporary file of a probe begins with a dot, like every other. + return begins(name, probePrefix) || begins(name, "."+probePrefix) +} + +// begins reports whether name starts with prefix and goes on after it. +func begins(name, prefix string) bool { + return len(name) > len(prefix) && strings.HasPrefix(name, prefix) +} + +// tempPrefix is how the name of the temporary file begins that WriteFile +// makes on the way to name. A random part follows it. +func tempPrefix(name string) string { return "." + name + "." } + // Path returns the full path of a file in the folder. func (d *Dir) Path(name string) string { return filepath.Join(d.path, name) } @@ -46,7 +165,7 @@ func (d *Dir) ReadFile(name string) ([]byte, error) { return os.ReadFile(d.Path( // last step fails the target has already been replaced: the error then means // "replaced, but not known to be durable". func (d *Dir) WriteFile(name string, data []byte) error { - tmp, err := os.CreateTemp(d.path, "."+name+".*") + tmp, err := os.CreateTemp(d.path, tempPrefix(name)+"*") if err != nil { return fmt.Errorf("write %s: %w", name, err) } diff --git a/agent/internal/state/os_unix.go b/agent/internal/state/os_unix.go new file mode 100644 index 0000000..43193f6 --- /dev/null +++ b/agent/internal/state/os_unix.go @@ -0,0 +1,20 @@ +//go:build unix + +package state + +import ( + "fmt" + "io/fs" + "os" + "syscall" +) + +// checkOwner refuses a folder that belongs to someone other than the user +// the agent runs as. info is what Stat says about the folder at path. +func checkOwner(path string, info fs.FileInfo) error { + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return fmt.Errorf("state folder %s: the system does not say who it belongs to", path) + } + return sameUser(path, stat.Uid, uint32(os.Geteuid())) +} diff --git a/agent/internal/state/os_unix_test.go b/agent/internal/state/os_unix_test.go new file mode 100644 index 0000000..1b829cf --- /dev/null +++ b/agent/internal/state/os_unix_test.go @@ -0,0 +1,40 @@ +//go:build unix + +package state + +import ( + "os" + "strings" + "syscall" + "testing" +) + +func TestAFolderOfAnotherUserIsRefusedBeforeItIsLookedInto(t *testing.T) { + // The root folder belongs to root, and it holds a good deal that is not + // the agent's. It is only looked at here: checkExisting changes nothing. + const root = "/" + info, err := os.Stat(root) + if err != nil { + t.Fatal(err) + } + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok || stat.Uid == uint32(os.Geteuid()) { + t.Skip("needs a folder of another user, and the root folder belongs to the user who runs the test") + } + err = checkExisting(root, info) + if err == nil { + t.Fatal("the root folder was taken for the agent's own") + } + if !strings.Contains(err.Error(), "another user") { + t.Fatalf("the root folder was refused for something other than its owner: %v", err) + } + + // A folder of the user who runs the test passes. + mine := t.TempDir() + if info, err = os.Stat(mine); err != nil { + t.Fatal(err) + } + if err := checkExisting(mine, info); err != nil { + t.Fatalf("a folder of the user who runs the test was refused: %v", err) + } +} diff --git a/agent/internal/state/os_windows.go b/agent/internal/state/os_windows.go new file mode 100644 index 0000000..781da40 --- /dev/null +++ b/agent/internal/state/os_windows.go @@ -0,0 +1,9 @@ +//go:build windows + +package state + +import "io/fs" + +// checkOwner accepts every folder: Windows has no user id that the owner of +// a folder could be compared with. +func checkOwner(string, fs.FileInfo) error { return nil } diff --git a/agent/internal/state/state_test.go b/agent/internal/state/state_test.go index a0fb9ba..dcfb32d 100644 --- a/agent/internal/state/state_test.go +++ b/agent/internal/state/state_test.go @@ -66,6 +66,211 @@ func TestOpenRejectsAnEmptyPathAndAFile(t *testing.T) { } } +// folderWith makes a folder with mode 0755 that holds a file for every name +// and returns its path. A name that ends in a slash becomes a folder. The +// folder says it was last written to long ago: whatever is written into it +// afterwards moves that time, also a file that is made there and removed +// again. +func folderWith(t *testing.T, names ...string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "data") + if err := os.Mkdir(path, 0o755); err != nil { + t.Fatal(err) + } + // Whatever the umask made of it. + if err := os.Chmod(path, 0o755); err != nil { + t.Fatal(err) + } + for _, name := range names { + var err error + if dir, isDir := strings.CutSuffix(name, "/"); isDir { + err = os.Mkdir(filepath.Join(path, dir), 0o700) + } else { + err = os.WriteFile(filepath.Join(path, name), []byte(name), 0o600) + } + if err != nil { + t.Fatal(err) + } + } + longAgo := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC) + if err := os.Chtimes(path, longAgo, longAgo); err != nil { + t.Fatal(err) + } + return path +} + +// holds returns the names of what is in the folder at path, sorted. +func holds(t *testing.T, path string) []string { + t.Helper() + entries, err := os.ReadDir(path) + if err != nil { + t.Fatal(err) + } + names := make([]string, 0, len(entries)) + for _, e := range entries { + names = append(names, e.Name()) + } + return names +} + +// statFolder returns what the system says about the folder at path. +func statFolder(t *testing.T, path string) os.FileInfo { + t.Helper() + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + return info +} + +func TestOpenTakesAnEmptyFolderThatWasThereAndMakesItPrivate(t *testing.T) { + path := folderWith(t) + before := statFolder(t, path) + if _, err := Open(path); err != nil { + t.Fatalf("Open: %v", err) + } + after := statFolder(t, path) + if runtime.GOOS != "windows" && after.Mode().Perm() != 0o700 { + t.Fatalf("mode = %v, want 0700", after.Mode().Perm()) + } + // Open has tried the folder with a file, and removed it again. + if after.ModTime().Equal(before.ModTime()) { + t.Fatal("nothing was written into the folder to try it") + } + if left := holds(t, path); len(left) != 0 { + t.Fatalf("Open left something in the folder: %v", left) + } +} + +func TestOpenTakesAFolderThatHoldsOnlyTheAgentsFiles(t *testing.T) { + // What an agent keeps in its folder, what it leaves there when it dies + // while it writes one of its files or tries the folder, and what a + // freshly formatted disk comes with. + path := folderWith(t, + "admin.sock", "agent.lock", "devices.json", "tls.crt", "tls.key", + ".devices.json.1234567890", ".tls.crt.42", ".tls.key.42", + "probe.LEFTBEHIND", ".probe.LEFTBEHIND.7", + "lost+found/", + ) + held := holds(t, path) + if _, err := Open(path); err != nil { + t.Fatalf("Open: %v", err) + } + if after := statFolder(t, path); runtime.GOOS != "windows" && after.Mode().Perm() != 0o700 { + t.Fatalf("mode = %v, want 0700", after.Mode().Perm()) + } + // Everything in it is as it was, and nothing was added. + if now := holds(t, path); strings.Join(now, "\n") != strings.Join(held, "\n") { + t.Fatalf("the folder holds %v after Open, it held %v", now, held) + } + for _, name := range held { + if name == "lost+found" { + continue + } + if got, err := os.ReadFile(filepath.Join(path, name)); err != nil || string(got) != name { + t.Errorf("%s was changed: %q, %v", name, got, err) + } + } +} + +func TestOpenRefusesAFolderThatHoldsAnotherFileAndLeavesItAlone(t *testing.T) { + others := []string{ + "notes.txt", + ".bashrc", + "devices.json.bak", // the name of a file of the agent with something after it + ".notes.txt.42", // a temporary file for a file that is not the agent's + "probe", // what the name of a probe begins with, without its random part + "lost+found", // a file, where only a folder of that name is let pass + "sub/", + } + if runtime.GOOS != "windows" { + // What a temporary file begins with, and nothing after it. Windows + // drops a dot at the end of a name, so the file cannot be made there. + others = append(others, ".devices.json.") + } + for _, other := range others { + // The one file that is not the agent's lies among files that are. + path := folderWith(t, "devices.json", other, "tls.key") + held, before := holds(t, path), statFolder(t, path) + _, err := Open(path) + if err == nil { + t.Errorf("a folder that holds %s was accepted", other) + continue + } + name := strings.TrimSuffix(other, "/") + for _, want := range []string{path, `"` + name + `"`, "folder of its own"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("%s: the error does not say %s: %v", other, want, err) + } + } + if strings.Contains(err.Error(), "\n") { + t.Errorf("%s: the error is more than one line: %q", other, err) + } + // The folder is as it was: its mode, what it holds, and when it was + // last written to. + after := statFolder(t, path) + if runtime.GOOS != "windows" && after.Mode().Perm() != 0o755 { + t.Errorf("%s: the mode of the refused folder is now %v, it was 0755", other, after.Mode().Perm()) + } + if now := holds(t, path); strings.Join(now, "\n") != strings.Join(held, "\n") { + t.Errorf("%s: the refused folder holds %v, it held %v", other, now, held) + } + if !after.ModTime().Equal(before.ModTime()) { + t.Errorf("%s: something was written into the refused folder", other) + } + } +} + +func TestAFolderMustBelongToTheUserTheAgentRunsAs(t *testing.T) { + for _, same := range []uint32{0, 1000} { + if err := sameUser("/srv/agent", same, same); err != nil { + t.Errorf("a folder of uid %d was refused to an agent that runs as uid %d: %v", same, same, err) + } + } + for _, c := range []struct{ owner, user uint32 }{ + {1000, 0}, // root must not take a folder that another user can fill + {0, 1000}, + {1000, 1001}, + } { + err := sameUser("/srv/agent", c.owner, c.user) + if err == nil { + t.Errorf("a folder of uid %d was given to an agent that runs as uid %d", c.owner, c.user) + continue + } + for _, want := range []string{"/srv/agent", "another user", "AGENT_DATA"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("owner %d, agent %d: the error does not say %q: %v", c.owner, c.user, want, err) + } + } + } +} + +func TestAFolderThatCannotStoreTheProbeIsAClearError(t *testing.T) { + d := openTemp(t) + // Where the probe goes there is a folder that is not empty, so the probe + // cannot be renamed into place: the folder takes no file of that name. + const name = "probe.x" + if err := os.Mkdir(d.Path(name), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(d.Path(name), "x"), nil, 0o600); err != nil { + t.Fatal(err) + } + err := d.probe(name) + if err == nil { + t.Fatal("the probe reported success although it could not be stored") + } + for _, want := range []string{d.Path(""), "cannot store a file"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("the error does not say %q: %v", want, err) + } + } + // Nothing of the attempt is left behind. + if left := holds(t, d.Path("")); len(left) != 1 || left[0] != name { + t.Fatalf("the folder holds %v, want only what was in the way", left) + } +} + func TestWriteFileIsAtomicAndPrivate(t *testing.T) { d := openTemp(t) if err := d.WriteFile("x.json", []byte("one")); err != nil { From f6ddb1b189bb6c70b05cf4ce4e1bf39a4fd91f7c Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 23:39:11 +0530 Subject: [PATCH 28/32] fix(agent): no upgrade for read-only devices, stricter handler options, a health check that ignores dates --- agent/cmd/agent/main_test.go | 13 ++- agent/internal/server/handler.go | 37 +++++-- agent/internal/server/handler_test.go | 134 +++++++++++++++++++++++++- agent/internal/server/middleware.go | 37 ++++++- agent/internal/state/devices.go | 8 +- agent/internal/tlsid/tlsid.go | 26 ++++- agent/internal/tlsid/tlsid_test.go | 84 +++++++++++----- 7 files changed, 293 insertions(+), 46 deletions(-) diff --git a/agent/cmd/agent/main_test.go b/agent/cmd/agent/main_test.go index 793a1e5..cfbfe15 100644 --- a/agent/cmd/agent/main_test.go +++ b/agent/cmd/agent/main_test.go @@ -596,6 +596,11 @@ func TestStoppingTheAgentEndsAnOpenTerminal(t *testing.T) { } } +// secondAgentTimeout is how long a second agent on a folder that is in use +// may take to be refused. It is refused at once. One that was let in would +// serve until its context ends: the timeout ends it, and with it the test. +const secondAgentTimeout = 3 * time.Second + func TestASecondAgentOnTheSameFolderIsRefused(t *testing.T) { a := startAgent(t) env := func(k string) string { @@ -604,8 +609,10 @@ func TestASecondAgentOnTheSameFolderIsRefused(t *testing.T) { } return a.env[k] } + ctx, cancel := context.WithTimeout(context.Background(), secondAgentTimeout) + defer cancel() var errOut bytes.Buffer - if code := run(context.Background(), []string{"serve"}, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "already running") { + if code := run(ctx, []string{"serve"}, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "already running") { t.Fatalf("a second agent: exit %d, %s", code, errOut.String()) } } @@ -629,8 +636,10 @@ func TestASecondAgentIsRefusedBeforeItTouchesTheState(t *testing.T) { } return a.env[k] } + ctx, cancel := context.WithTimeout(context.Background(), secondAgentTimeout) + defer cancel() var errOut bytes.Buffer - if code := run(context.Background(), []string{"serve"}, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "already running") { + if code := run(ctx, []string{"serve"}, env, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "already running") { t.Fatalf("a second agent: exit %d, %s", code, errOut.String()) } if _, err := os.Stat(certificate); !os.IsNotExist(err) { diff --git a/agent/internal/server/handler.go b/agent/internal/server/handler.go index 8606dac..10acf8c 100644 --- a/agent/internal/server/handler.go +++ b/agent/internal/server/handler.go @@ -4,7 +4,9 @@ package server import ( + "crypto/sha256" "errors" + "fmt" "io" "log/slog" "net/http" @@ -22,9 +24,17 @@ import ( // APILevel is the version of the agent's own API, reported by whoami. const APILevel = 1 -// Options is everything the handler needs. Devices, Pairing and Limiter are -// required, and DockerHost must name the daemon: without them New returns an -// error. Everything else may be left out, with the effect noted at the field. +// fingerprintLen is the length of a certificate fingerprint: one SHA-256 +// digest. +const fingerprintLen = sha256.Size + +// Options is everything the handler needs. Devices, Pairing, Limiter and +// Conns are required, and Fingerprint must be empty or 32 bytes: otherwise +// New returns an error that names the option. DockerHost must name the +// daemon as well; when it is missing or cannot be used, the error is the +// dialer's and names the environment variable DOCKER_HOST instead of the +// option. Everything else may be left out, with the effect noted at the +// field. type Options struct { // DockerHost is where the Docker daemon listens (unix:// or tcp://). DockerHost string @@ -33,12 +43,13 @@ type Options struct { LegacyToken string Pairing *pairing.Manager // Fingerprint is the agent's certificate fingerprint (32 bytes), or empty - // when it serves plain HTTP behind a proxy. + // when it serves plain HTTP behind a proxy. No proof of a phone could + // match a fingerprint of another length. Fingerprint []byte Limiter *throttle.Limiter - // Conns tracks the requests that are open so that they can be ended. Nil - // means none is tracked: removing a device or stopping the agent then - // ends nothing that is open. + // Conns tracks the requests that are open, so that removing a device ends + // its requests and stopping the agent ends them all. Without it both + // would end nothing, and nobody would be told. Conns *conns.Registry // Version is what whoami and a pairing report; it may be empty. Version string @@ -53,16 +64,24 @@ type Options struct { } // New builds the agent's HTTP handler. It returns an error that names the -// first required option that is missing. +// first option that is missing or cannot be used. For DockerHost that error +// comes from the dialer and names DOCKER_HOST. func New(o Options) (http.Handler, error) { - // A request goes through each of these; without one it would panic. switch { + // A request goes through each of these; without one it would panic. case o.Devices == nil: return nil, errors.New("server: the option Devices is required") case o.Pairing == nil: return nil, errors.New("server: the option Pairing is required") case o.Limiter == nil: return nil, errors.New("server: the option Limiter is required") + // Without these nothing panics, and the handler does not keep what it + // promises either: a removed device would keep its open streams, stopping + // the agent would end none of them, and no phone could pair. + case o.Conns == nil: + return nil, errors.New("server: the option Conns is required") + case len(o.Fingerprint) != 0 && len(o.Fingerprint) != fingerprintLen: + return nil, fmt.Errorf("server: the option Fingerprint must be empty or %d bytes long, not %d", fingerprintLen, len(o.Fingerprint)) } if o.Log == nil { o.Log = slog.New(slog.NewTextHandler(io.Discard, nil)) diff --git a/agent/internal/server/handler_test.go b/agent/internal/server/handler_test.go index dc7184f..090ef59 100644 --- a/agent/internal/server/handler_test.go +++ b/agent/internal/server/handler_test.go @@ -11,6 +11,7 @@ import ( "net" "net/http" "net/http/httptest" + "os" "path/filepath" "strconv" "strings" @@ -47,8 +48,9 @@ func (c *clock) advance(d time.Duration) { // daemon is a fake Docker daemon that records what reaches it. type daemon struct { *httptest.Server - mu sync.Mutex - seen []string + mu sync.Mutex + seen []string + headers http.Header // of the request that came last } func newDaemon(t *testing.T) *daemon { @@ -58,6 +60,7 @@ func newDaemon(t *testing.T) *daemon { body, _ := io.ReadAll(r.Body) d.mu.Lock() d.seen = append(d.seen, r.Method+" "+r.URL.EscapedPath()+" "+r.Header.Get("Authorization")+" "+string(body)) + d.headers = r.Header.Clone() d.mu.Unlock() w.Header().Set("Content-Type", "application/json") w.Write([]byte(`[{"Id":"x"}]`)) @@ -72,8 +75,17 @@ func (d *daemon) requests() []string { return append([]string(nil), d.seen...) } +// lastHeaders returns the headers of the request that reached the daemon +// last. +func (d *daemon) lastHeaders() http.Header { + d.mu.Lock() + defer d.mu.Unlock() + return d.headers.Clone() +} + type fixture struct { handler http.Handler + dir *state.Dir devices *state.Devices pairing *pairing.Manager conns *conns.Registry @@ -97,6 +109,7 @@ func newFixture(t *testing.T, legacyToken string, fingerprint []byte, configure t.Fatal(err) } f := &fixture{ + dir: dir, devices: devices, pairing: pairing.NewManager(c.now, rand.Reader), conns: conns.New(), @@ -215,6 +228,41 @@ func TestAReadOnlyDeviceReadsButCannotChangeAnything(t *testing.T) { } } +func TestAReadOnlyDeviceGetsNoProtocolUpgrade(t *testing.T) { + f := newFixture(t, "", agentFP) + _, viewer, _ := f.devices.Add("viewer", state.RoleReadOnly) + _, owner, _ := f.devices.Add("owner", state.RoleFull) + // A read that a read-only device may send, with a request for an upgrade. + // It returns the headers the daemon got. + read := func(token string) http.Header { + t.Helper() + rec := f.do("GET", "/containers/abc/logs", token, nil, "Connection", "Upgrade", "Upgrade", "tcp") + if rec.Code != http.StatusOK { + t.Fatalf("code = %d, want 200", rec.Code) + } + return f.daemon.lastHeaders() + } + if got := read(viewer); len(got.Values("Upgrade")) != 0 { + t.Errorf("the read of a read-only device reached the daemon with Upgrade: %q", got.Values("Upgrade")) + } + if got := read(owner); got.Get("Upgrade") != "tcp" { + t.Errorf("the upgrade a full device asked for did not reach the daemon: Upgrade is %q", got.Get("Upgrade")) + } + + // With the header goes the token that announces it, and nothing else that + // Connection names. + h := http.Header{"Connection": {"keep-alive, Upgrade", "upgrade"}, "Upgrade": {"tcp"}} + dropUpgrade(h) + if len(h) != 1 || strings.Join(h.Values("Connection"), "|") != "keep-alive" { + t.Errorf("after the upgrade was dropped the headers are %v, want only Connection: keep-alive", h) + } + h = http.Header{"Connection": {"Upgrade"}, "Upgrade": {"websocket"}, "Accept": {"*/*"}} + dropUpgrade(h) + if len(h) != 1 || h.Get("Accept") != "*/*" { + t.Errorf("after the upgrade was dropped the headers are %v, want only Accept", h) + } +} + func TestWhoami(t *testing.T) { f := newFixture(t, legacy, agentFP) dev, token, _ := f.devices.Add("Pixel 8", state.RoleReadOnly) @@ -451,6 +499,56 @@ func TestPairingWithoutACertificateBindsToAnEmptyFingerprint(t *testing.T) { } } +func TestAPairingThatCannotBeStoredIsAnsweredWithoutTheCause(t *testing.T) { + f := newFixture(t, "", agentFP) + p, done, _ := f.pairing.Start(state.RoleFull, "") + // The folder disappears: nothing can be written any more. + folder := f.dir.Path("") + if err := os.RemoveAll(folder); err != nil { + t.Fatal(err) + } + nonce := bytes.Repeat([]byte{5}, pairing.NonceLen) + body, _ := json.Marshal(pairRequest{ + V: 1, + Nonce: base64.RawURLEncoding.EncodeToString(nonce), + Proof: base64.RawURLEncoding.EncodeToString(pairing.PhoneProof(p.Code, agentFP, nonce)), + Name: "Pixel 8", + }) + rec := f.do("POST", "/agent/v1/pair", "", bytes.NewReader(body)) + if rec.Code != http.StatusInternalServerError { + t.Fatalf("a correct proof whose device could not be stored: code = %d, want 500", rec.Code) + } + // The cause names a file in the state folder. It is for the log and for + // whoever runs the pair command, not for a stranger on the network: the + // answer is a fixed text and nothing besides. + answer := rec.Body.String() + if answer != `{"message":"The agent could not store the new device"}`+"\n" { + t.Errorf("the answer is %q, want the fixed message alone", answer) + } + inJSON, _ := json.Marshal(folder) + for what, never := range map[string]string{ + "the state folder": folder, + "the state folder, as JSON has it": strings.Trim(string(inJSON), `"`), + "the name of the device list": "devices.json", + "what a device token begins with": "dm1.", + "the field that carries the token": `"token"`, + } { + if strings.Contains(answer, never) { + t.Errorf("the answer holds %s: %q", what, answer) + } + } + if len(f.devices.List()) != 0 { + t.Error("a device exists although it could not be stored") + } + if r := <-done; r.Outcome != pairing.Failed { + t.Errorf("the pairing ended as %q, want %q", r.Outcome, pairing.Failed) + } + // The pairing is over: the same proof finds nothing to redeem. + if rec := f.do("POST", "/agent/v1/pair", "", bytes.NewReader(body)); rec.Code != http.StatusNotFound { + t.Errorf("the same proof again: code = %d, want 404", rec.Code) + } +} + func TestAskingWhileNothingIsPendingCountsAgainstTheAddress(t *testing.T) { f := newFixture(t, "", agentFP) // A well-formed request with a proof that fits no code. @@ -589,6 +687,7 @@ func requiredOptions(t *testing.T) Options { Devices: devices, Pairing: pairing.NewManager(time.Now, rand.Reader), Limiter: throttle.New(time.Now), + Conns: conns.New(), } } @@ -597,6 +696,7 @@ func TestNewNamesTheRequiredOptionThatIsMissing(t *testing.T) { "Devices": func(o *Options) { o.Devices = nil }, "Pairing": func(o *Options) { o.Pairing = nil }, "Limiter": func(o *Options) { o.Limiter = nil }, + "Conns": func(o *Options) { o.Conns = nil }, } { o := requiredOptions(t) without(&o) @@ -613,6 +713,36 @@ func TestNewNamesTheRequiredOptionThatIsMissing(t *testing.T) { if _, err := New(Options{DockerHost: "tcp://127.0.0.1:1"}); err == nil || !strings.Contains(err.Error(), "Devices") { t.Errorf("New with nothing but a Docker host: error = %v, want one that names Devices", err) } + // Without a Docker host the error is the dialer's. It names the + // environment variable the host comes from, not the option. + o := requiredOptions(t) + o.DockerHost = "" + if _, err := New(o); err == nil || !strings.Contains(err.Error(), "DOCKER_HOST") { + t.Errorf("New without a Docker host: error = %v, want one that names DOCKER_HOST", err) + } +} + +func TestNewRefusesAFingerprintThatIsNotOne(t *testing.T) { + for _, n := range []int{1, 31, 33, 64} { + o := requiredOptions(t) + o.Fingerprint = bytes.Repeat([]byte{7}, n) + h, err := New(o) + if err == nil || h != nil { + t.Errorf("New with a fingerprint of %d bytes built a handler", n) + continue + } + if !strings.Contains(err.Error(), "Fingerprint") || !strings.Contains(err.Error(), strconv.Itoa(n)) { + t.Errorf("a fingerprint of %d bytes: the error does not name the option and the length: %v", n, err) + } + } + // No fingerprint, as behind a proxy, and one of the right length. + for _, fingerprint := range [][]byte{nil, {}, agentFP} { + o := requiredOptions(t) + o.Fingerprint = fingerprint + if _, err := New(o); err != nil { + t.Errorf("New with a fingerprint of %d bytes: %v", len(fingerprint), err) + } + } } func TestAHandlerWorksWithTheRequiredOptionsAlone(t *testing.T) { diff --git a/agent/internal/server/middleware.go b/agent/internal/server/middleware.go index a5b3ba0..2dd3332 100644 --- a/agent/internal/server/middleware.go +++ b/agent/internal/server/middleware.go @@ -8,6 +8,7 @@ import ( "net" "net/http" "regexp" + "strings" "sync" "time" @@ -77,18 +78,46 @@ func rejectBrowsers(next http.Handler) http.Handler { }) } -// roleGate lets a read-only device through only for the reads on the list. +// roleGate lets a read-only device through only for the reads on the list, +// and never with a request for a protocol upgrade. func roleGate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { dev, _ := auth.Caller(r.Context()) - if dev.Role != state.RoleFull && !policy.AllowedReadOnly(r.Method, r.URL.EscapedPath()) { - auth.WriteError(w, http.StatusForbidden, ReadOnlyMessage) - return + if dev.Role != state.RoleFull { + if !policy.AllowedReadOnly(r.Method, r.URL.EscapedPath()) { + auth.WriteError(w, http.StatusForbidden, ReadOnlyMessage) + return + } + dropUpgrade(r.Header) } next.ServeHTTP(w, r) }) } +// dropUpgrade takes the request for a protocol upgrade out of a request's +// headers: the Upgrade header, and the upgrade token in Connection that goes +// with it. Once a backend answers such a request with 101, the proxy passes +// bytes both ways without looking at them, and whatever the caller then +// sends, a request that changes something included, reaches the backend +// unchecked. The daemon answers none of the listed reads with 101; the agent +// does not rely on that. +func dropUpgrade(h http.Header) { + h.Del("Upgrade") + var kept []string + for _, value := range h.Values("Connection") { + for _, token := range strings.Split(value, ",") { + if token = strings.TrimSpace(token); token != "" && !strings.EqualFold(token, "upgrade") { + kept = append(kept, token) + } + } + } + if len(kept) == 0 { + h.Del("Connection") + return + } + h.Set("Connection", strings.Join(kept, ", ")) +} + // fullOnly refuses read-only devices outright. func fullOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/agent/internal/state/devices.go b/agent/internal/state/devices.go index da4ae15..2744d21 100644 --- a/agent/internal/state/devices.go +++ b/agent/internal/state/devices.go @@ -192,9 +192,11 @@ func (s *Devices) List() []Device { return out } -// Remove deletes a device. Check the error first: when it is set the removal -// was not stored and the device is still paired, whatever the bool says. -// Without an error the bool is false when no device has that id. +// Remove deletes a device. Check the error first: when it is set the device +// is still paired in the running agent, whatever the bool says, and whether +// the file on disk still lists it is not known. The write may have failed +// before the file was replaced, or only afterwards, when the folder was +// synced. Without an error the bool is false when no device has that id. func (s *Devices) Remove(id string) (Device, bool, error) { s.mu.Lock() defer s.mu.Unlock() diff --git a/agent/internal/tlsid/tlsid.go b/agent/internal/tlsid/tlsid.go index 8467b03..c65a8e2 100644 --- a/agent/internal/tlsid/tlsid.go +++ b/agent/internal/tlsid/tlsid.go @@ -166,17 +166,35 @@ func ReadFingerprint(dataDir string) (Fingerprint, error) { // LocalClientConfig is for a client on the same machine, such as the health // check: it trusts exactly the certificate stored in the state folder -// dataDir, and nothing else. +// dataDir, and nothing else, whatever the dates of that certificate say. func LocalClientConfig(dataDir string) (*tls.Config, error) { certPEM, err := os.ReadFile(filepath.Join(dataDir, certFile)) if err != nil { return nil, err } - pool := x509.NewCertPool() - if !pool.AppendCertsFromPEM(certPEM) { + block, _ := pem.Decode(certPEM) + if block == nil || block.Type != "CERTIFICATE" { return nil, fmt.Errorf("%s is not a certificate in PEM form", certFile) } - return &tls.Config{RootCAs: pool, ServerName: ServerName, MinVersion: tls.VersionTLS13}, nil + stored, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, fmt.Errorf("%s: %w", certFile, err) + } + pool := x509.NewCertPool() + pool.AddCert(stored) + return &tls.Config{ + RootCAs: pool, + ServerName: ServerName, + MinVersion: tls.VersionTLS13, + // The health check knows the agent by its certificate, as a phone + // does, and the dates of a certificate that is pinned mean nothing. + // Checked against the clock they would only do harm: a certificate + // issued while the clock was ahead is "not yet valid", the health + // check would fail while every phone works, and a restart would not + // help. So the certificate is checked at a moment at which it is + // valid, and everything else about the check stays as it is. + Time: func() time.Time { return stored.NotBefore }, + }, nil } // ServerConfig is the TLS configuration the agent listens with: its single diff --git a/agent/internal/tlsid/tlsid_test.go b/agent/internal/tlsid/tlsid_test.go index 38e2d9b..845d87b 100644 --- a/agent/internal/tlsid/tlsid_test.go +++ b/agent/internal/tlsid/tlsid_test.go @@ -246,27 +246,31 @@ func TestReadFingerprintReadsWithoutCreating(t *testing.T) { } } -func TestLocalClientConfigTrustsOnlyTheStoredCertificate(t *testing.T) { - serve := func(cert tls.Certificate) string { - ln, err := tls.Listen("tcp", "127.0.0.1:0", ServerConfig(cert)) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { ln.Close() }) - go func() { - for { - c, err := ln.Accept() - if err != nil { - return - } - go func() { - c.(*tls.Conn).Handshake() - c.Close() - }() - } - }() - return ln.Addr().String() +// serve answers TLS handshakes with cert until the test ends and returns the +// address it listens on. +func serve(t *testing.T, cert tls.Certificate) string { + t.Helper() + ln, err := tls.Listen("tcp", "127.0.0.1:0", ServerConfig(cert)) + if err != nil { + t.Fatal(err) } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func() { + c.(*tls.Conn).Handshake() + c.Close() + }() + } + }() + return ln.Addr().String() +} + +func TestLocalClientConfigTrustsOnlyTheStoredCertificate(t *testing.T) { mine := openTemp(t) myCert, _ := LoadOrCreate(mine, time.Now()) otherCert, _ := LoadOrCreate(openTemp(t), time.Now()) @@ -276,12 +280,12 @@ func TestLocalClientConfigTrustsOnlyTheStoredCertificate(t *testing.T) { t.Fatalf("LocalClientConfig: %v", err) } dialer := &net.Dialer{Timeout: 3 * time.Second} - conn, err := tls.DialWithDialer(dialer, "tcp", serve(myCert), cfg) + conn, err := tls.DialWithDialer(dialer, "tcp", serve(t, myCert), cfg) if err != nil { t.Fatalf("the agent's own certificate was refused: %v", err) } conn.Close() - if c, err := tls.DialWithDialer(dialer, "tcp", serve(otherCert), cfg); err == nil { + if c, err := tls.DialWithDialer(dialer, "tcp", serve(t, otherCert), cfg); err == nil { c.Close() t.Fatal("another agent's certificate was accepted") } @@ -289,3 +293,39 @@ func TestLocalClientConfigTrustsOnlyTheStoredCertificate(t *testing.T) { t.Fatal("a folder without a certificate was accepted") } } + +func TestLocalClientConfigDoesNotMindTheDatesOfTheCertificate(t *testing.T) { + dialer := &net.Dialer{Timeout: 3 * time.Second} + for name, issued := range map[string]time.Time{ + // The clock was four years ahead when the agent first ran. + "a certificate that is not valid yet": time.Now().AddDate(4, 0, 0), + // The agent has run without a restart for longer than its + // certificate lasts. + "a certificate that has run out": time.Now().Add(-validity - 24*time.Hour), + } { + mine := openTemp(t) + myCert, err := LoadOrCreate(mine, issued) + if err != nil { + t.Fatalf("%s: LoadOrCreate: %v", name, err) + } + cfg, err := LocalClientConfig(mine.Path("")) + if err != nil { + t.Fatalf("%s: LocalClientConfig: %v", name, err) + } + conn, err := tls.DialWithDialer(dialer, "tcp", serve(t, myCert), cfg) + if err != nil { + t.Errorf("%s was refused although it is the stored one: %v", name, err) + continue + } + conn.Close() + // A certificate with another key and the same dates is still refused. + otherCert, err := LoadOrCreate(openTemp(t), issued) + if err != nil { + t.Fatalf("%s: LoadOrCreate: %v", name, err) + } + if c, err := tls.DialWithDialer(dialer, "tcp", serve(t, otherCert), cfg); err == nil { + c.Close() + t.Errorf("%s: a certificate with another key was accepted", name) + } + } +} From 70c5cbff0ed5df8b2ccb85804c81297e8dfc5bf7 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 23:41:59 +0530 Subject: [PATCH 29/32] test(agent): the test phone sends no token while pairing, and two more link vectors --- agent/cmd/agent/pair_test.go | 63 +++++++++++++++++--- agent/internal/pairing/testdata/vectors.json | 20 ++++++- 2 files changed, 75 insertions(+), 8 deletions(-) diff --git a/agent/cmd/agent/pair_test.go b/agent/cmd/agent/pair_test.go index 4b8e68b..71e4d8f 100644 --- a/agent/cmd/agent/pair_test.go +++ b/agent/cmd/agent/pair_test.go @@ -97,7 +97,8 @@ func (p *phone) pair(code, name string) (status int, err error) { // // The phone goes where it was sent and takes what it asked for, no more: it // follows no redirect, and it reads no answer that is larger than a pairing -// answer can be. +// answer can be. And it shows nothing it holds: a token from an earlier +// pairing is in neither request of the attempt. func (p *phone) pairContext(ctx context.Context, code, name string) (status int, err error) { canonical, ok := pairing.Normalize(code) if !ok { @@ -175,13 +176,19 @@ func (p *phone) pairContext(ctx context.Context, code, name string) (status int, return http.StatusOK, nil } -// ask sends one request of a pairing attempt. It is the phone's ordinary -// request but for one thing: it follows no redirect, and hands back the -// answer that asks for one as it is. Where a phone takes its proof is for -// its owner to say, who typed or scanned the address, and not for whoever -// answers there. +// ask sends one request of a pairing attempt. It differs from the phone's +// ordinary request in two things. +// +// It follows no redirect, and hands back the answer that asks for one as it +// is. Where a phone takes its proof is for its owner to say, who typed or +// scanned the address, and not for whoever answers there. +// +// And it carries no token, also when the phone holds one from an earlier +// pairing. A token is for the agent that issued it, and who answers a pairing +// attempt is not known to be that agent: when the code was typed, it may be +// a relay. func (p *phone) ask(ctx context.Context, method, path string, body []byte) (*http.Response, error) { - req, err := p.request(ctx, method, path, body) + req, err := http.NewRequestWithContext(ctx, method, p.scheme+"://"+p.addr+path, bytes.NewReader(body)) if err != nil { return nil, err } @@ -736,6 +743,48 @@ func TestAPhoneFollowsNoRedirectWhilePairing(t *testing.T) { } } +// earlierToken is what a phone holds that has been paired before, with this +// server or with another. It has the form of a device token, and it is not +// the token that a pairing in these tests hands out. +var earlierToken = "dm1.feedface." + strings.Repeat("B", 43) + +func TestAPhoneSendsNoTokenWhilePairing(t *testing.T) { + // The server holds the code and answers as an agent does. It notes what + // every request brings in its Authorization header. + code := someCode(t) + cert := strangerCert(t) + right := answerPairing(fingerprintOf(t, cert), func(phoneNonce, fingerprint []byte) reply { + return rightReply(code, phoneNonce, fingerprint) + }) + var asked syncBuf + noting := func(handler http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(&asked, "%s %s %q\n", r.Method, r.URL.Path, r.Header.Values("Authorization")) + handler(w, r) + } + } + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", noting(healthy)) + mux.HandleFunc("POST /agent/v1/pair", noting(right)) + p := newPhone(t, "https", serveTLS(t, cert, mux)) + p.token = earlierToken + + if status, err := p.pair(code, "Pixel 8"); err != nil || status != http.StatusOK { + t.Fatalf("pairing: %d, %v", status, err) + } + whilePairing := "GET /healthz []\nPOST /agent/v1/pair []\n" + if got := asked.String(); got != whilePairing { + t.Fatalf("while it paired the phone sent:\n%swant, with no token in either request:\n%s", got, whilePairing) + } + // The server does note a token that is sent: the phone's next request is + // an ordinary one and comes with the token the pairing gave it. + p.status("GET", "/healthz") + afterwards := whilePairing + "GET /healthz [\"Bearer " + madeUpToken + "\"]\n" + if got := asked.String(); got != afterwards { + t.Fatalf("with its ordinary request the phone has sent:\n%swant:\n%s", got, afterwards) + } +} + func TestAPhoneDoesNotWaitForEverForTheAnswer(t *testing.T) { // A server that takes the pairing request and then says nothing, for as // long as the phone stays. diff --git a/agent/internal/pairing/testdata/vectors.json b/agent/internal/pairing/testdata/vectors.json index e3ec02d..395a5a0 100644 --- a/agent/internal/pairing/testdata/vectors.json +++ b/agent/internal/pairing/testdata/vectors.json @@ -1,5 +1,5 @@ { - "note": "Shared with the app. key: PBKDF2-HMAC-SHA256(password = the 12 ASCII bytes of the code, salt = 'docker-mobile pair v1' 00 phoneNonce, rounds = 100000, length = 32 bytes); the salt is the context string, one zero byte, then the phone nonce, 54 bytes in all, so both proofs of one attempt have the same key and no other attempt has it. proofs: HMAC-SHA256 keyed with that key over 'docker-mobile pair v1' 00 'phone'|'agent' 00 len(fingerprint) as one byte, fingerprint, phoneNonce, [agentNonce]. typed (in proofs): one way a person might enter that code; it is normalized first, and what is stretched is the result, code. normalization: what a typed code becomes (null = rejected). links: the link the agent shows for the six fields; an empty host, port, fingerprint, scheme or name is left out, and values are form-encoded (a space is '+', a reserved or non-ASCII character is %XX for each UTF-8 byte).", + "note": "Shared with the app. key: PBKDF2-HMAC-SHA256(password = the 12 ASCII bytes of the code, salt = 'docker-mobile pair v1' 00 phoneNonce, rounds = 100000, length = 32 bytes); the salt is the context string, one zero byte, then the phone nonce, 54 bytes in all, so both proofs of one attempt have the same key and no other attempt has it. proofs: HMAC-SHA256 keyed with that key over 'docker-mobile pair v1' 00 'phone'|'agent' 00 len(fingerprint) as one byte, fingerprint, phoneNonce, [agentNonce]. typed (in proofs): one way a person might enter that code; it is normalized first, and what is stretched is the result, code. normalization: what a typed code becomes (null = rejected). links: the link the agent shows for the six fields; an empty host, port, fingerprint, scheme or name is left out, and values are form-encoded (a space is '+', a reserved or non-ASCII character is %XX for each UTF-8 byte). A link has neither host nor port when the agent knows no address to advertise; the app then asks for the address. A host that is an IPv6 address is the address alone, without brackets, each colon encoded as %3A, and the port stays a field of its own.", "proofs": [ { "name": "pinned certificate", @@ -173,6 +173,24 @@ "code": "K7QM2XPA9TRC", "name": "", "link": "dockermobile://pair?c=K7QM2XPA9TRC&f=AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8&h=10.0.0.7&p=8443&v=1" + }, + { + "host": "", + "port": "", + "fingerprint": "OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI", + "scheme": "", + "code": "K7QM2XPA9TRC", + "name": "home lab", + "link": "dockermobile://pair?c=K7QM2XPA9TRC&f=OfCPv7Bu5FeqspEEZcUtbwd9RqmtauCT2Hr78uU9WwI&n=home+lab&v=1" + }, + { + "host": "fd12:3456:789a:1::20", + "port": "8443", + "fingerprint": "A6IxeSNJQk3GXxtfnKg77_KClmoC-1d0G7icg8JlERk", + "scheme": "", + "code": "0123456789AB", + "name": "nas", + "link": "dockermobile://pair?c=0123456789AB&f=A6IxeSNJQk3GXxtfnKg77_KClmoC-1d0G7icg8JlERk&h=fd12%3A3456%3A789a%3A1%3A%3A20&n=nas&p=8443&v=1" } ] } From d99b27481e087d2f0db29d6c3b649a1e1ede7f4e Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 7 Oct 2026 23:43:26 +0530 Subject: [PATCH 30/32] chore: tell people who come from an earlier agent what changed --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index b3153a4..6ace561 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,28 @@ in a container: A container's main process writes to that container's log, and the pairing code would be readable there for as long as it is valid. +### Coming from an earlier version of the agent + +- The agent serves TLS with its own certificate on port 8443 by default. + The app in this repository cannot use that yet: start the agent with + `--insecure-http` (plain HTTP on port 8080, as before) until it can. +- `AGENT_TOKEN` is optional now. When it is set it must be at least 16 + characters, with no spaces around it; the old example value + `dev-secret` is refused. +- The agent keeps a state folder (`AGENT_DATA`, by default + `/var/lib/docker-mobile-agent`), also in plain HTTP mode. It must belong + to the user the agent runs as and hold nothing else. One agent uses one + folder, and `pair`, `devices` and `revoke` need the same user and the + same `AGENT_DATA`. +- Ten wrong tokens or pairing attempts within ten minutes from one address + block that address for 1 to 15 minutes. Behind a reverse proxy every + client shares the proxy's address. +- Requests with an `Origin` header are refused, request bodies are limited + to 16 MiB except for builds, image loads and uploads into a container, + and errors are answered as JSON. +- Stopping the agent can take up to five seconds while open streams are + ended. + ## Run the app (dev) ``` cd app From 5d7eb65f5b5a7759e1262cb789a432a84dd23801 Mon Sep 17 00:00:00 2001 From: retransmit Date: Thu, 8 Oct 2026 01:09:14 +0530 Subject: [PATCH 31/32] fix(agent): the read limit reaches every request and leaves requests without a body alone --- agent/cmd/agent/main_test.go | 41 +++++++++++++++++++++++++++ agent/cmd/agent/serve.go | 31 ++++++++++++++------ agent/internal/server/handler.go | 24 +++++++++------- agent/internal/server/handler_test.go | 39 +++++++++++++++++++++++-- agent/internal/server/middleware.go | 34 ++++++++++++---------- 5 files changed, 133 insertions(+), 36 deletions(-) diff --git a/agent/cmd/agent/main_test.go b/agent/cmd/agent/main_test.go index cfbfe15..4641047 100644 --- a/agent/cmd/agent/main_test.go +++ b/agent/cmd/agent/main_test.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "bytes" "context" "crypto/tls" @@ -472,6 +473,46 @@ func TestGarbageOnTheTLSPortLeavesNoLineAndTheAgentKeepsServing(t *testing.T) { } } +func TestOptionsForTheWholeServerIsAnsweredByTheHandlerAndItsConnectionClosed(t *testing.T) { + // This test waits until the limit on a body has passed, so it is short. + old := requestTimeout + requestTimeout = 250 * time.Millisecond + t.Cleanup(func() { requestTimeout = old }) + + a := startAgent(t) + pinned := a.pinned("").client.Transport.(*http.Transport).TLSClientConfig + conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", a.addr, pinned) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + // An agent that does not answer, or keeps the connection, fails a check + // below instead of hanging the test. + conn.SetDeadline(time.Now().Add(5 * time.Second)) + began := time.Now() + // OPTIONS * asks about the server as a whole, and net/http would answer + // it without asking the handler. This one announces a body and sends none. + if _, err := io.WriteString(conn, "OPTIONS * HTTP/1.1\r\nHost: agent\r\nContent-Length: 17\r\n\r\n"); err != nil { + t.Fatal(err) + } + answers := bufio.NewReader(conn) + resp, err := http.ReadResponse(answers, nil) + if err != nil { + t.Fatalf("no answer after %v: %v", time.Since(began).Round(time.Millisecond), err) + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + // The answer of the agent's router. net/http by itself says 200. + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("code = %d, want 400", resp.StatusCode) + } + if _, err := answers.ReadByte(); err != io.EOF { + t.Fatalf("the connection is still open after %v: %v", time.Since(began).Round(time.Millisecond), err) + } + // The request went the way every request goes: the access log has it. + waitFor(t, "the request in the access log", func() bool { return strings.Contains(a.log.String(), "method=OPTIONS") }) +} + func TestTheFingerprintCommandPrintsWhatThePortPresents(t *testing.T) { a := startAgent(t) p := newPhone(t, "https", a.addr) diff --git a/agent/cmd/agent/serve.go b/agent/cmd/agent/serve.go index 49b13d7..4c9c048 100644 --- a/agent/cmd/agent/serve.go +++ b/agent/cmd/agent/serve.go @@ -34,6 +34,11 @@ import ( // that tests can shorten it. var shutdownGrace = 5 * time.Second +// requestTimeout is how long a caller without credentials may take over the +// body of a request. Zero leaves it at the handler's own 10 seconds. It is a +// variable so that tests can shorten it. +var requestTimeout time.Duration + // serverLog hands what net/http reports to the agent's log, except failed // TLS handshakes: on an open port those are mostly scanners. type serverLog struct{ log *slog.Logger } @@ -112,15 +117,16 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu registry := conns.New() manager := pairing.NewManager(time.Now, rand.Reader) handler, err := server.New(server.Options{ - DockerHost: cfg.DockerHost, - Devices: devices, - LegacyToken: cfg.LegacyToken, - Pairing: manager, - Fingerprint: fingerprint, - Limiter: throttle.New(time.Now), - Conns: registry, - Version: version, - Log: logger, + DockerHost: cfg.DockerHost, + Devices: devices, + LegacyToken: cfg.LegacyToken, + Pairing: manager, + Fingerprint: fingerprint, + Limiter: throttle.New(time.Now), + Conns: registry, + Version: version, + RequestTimeout: requestTimeout, + Log: logger, }) if err != nil { return err @@ -154,6 +160,11 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu IdleTimeout: 120 * time.Second, MaxHeaderBytes: 64 << 10, ErrorLog: errorLog, + // net/http would answer OPTIONS * itself, before the handler and + // without the handler's limit on how long a body may take: such a + // request could announce a body, never send it, and keep its + // connection. Here every request goes through the handler. + DisableGeneralOptionsHandler: true, } // Requests on the admin socket end when the agent begins to stop. The // socket itself stays to the end, and with it the lock on the folder. @@ -164,6 +175,8 @@ func serve(ctx context.Context, cfg config.Config, logger *slog.Logger, ready fu ReadHeaderTimeout: 10 * time.Second, ErrorLog: errorLog, BaseContext: func(net.Listener) context.Context { return adminCtx }, + // Here too every request goes through the handler. + DisableGeneralOptionsHandler: true, } logger.Info("docker-mobile-agent started", "version", version, "listen", ln.Addr().String(), "docker", cfg.DockerHost, "data", cfg.DataDir) diff --git a/agent/internal/server/handler.go b/agent/internal/server/handler.go index 10acf8c..aa6f3f4 100644 --- a/agent/internal/server/handler.go +++ b/agent/internal/server/handler.go @@ -29,12 +29,12 @@ const APILevel = 1 const fingerprintLen = sha256.Size // Options is everything the handler needs. Devices, Pairing, Limiter and -// Conns are required, and Fingerprint must be empty or 32 bytes: otherwise -// New returns an error that names the option. DockerHost must name the -// daemon as well; when it is missing or cannot be used, the error is the -// dialer's and names the environment variable DOCKER_HOST instead of the -// option. Everything else may be left out, with the effect noted at the -// field. +// Conns are required, Fingerprint must be empty or 32 bytes, and +// RequestTimeout must not be negative: otherwise New returns an error that +// names the option. DockerHost must name the daemon as well; when it is +// missing or cannot be used, the error is the dialer's and names the +// environment variable DOCKER_HOST instead of the option. Everything else +// may be left out, with the effect noted at the field. type Options struct { // DockerHost is where the Docker daemon listens (unix:// or tcp://). DockerHost string @@ -55,7 +55,7 @@ type Options struct { Version string // RequestTimeout is how long a caller that has not been authenticated may // take to send the rest of its request once the headers are in. Zero - // means 10 seconds; tests shorten it. + // means 10 seconds; tests shorten it. It must not be negative. RequestTimeout time.Duration // Log receives the access log; nil discards it. Log *slog.Logger @@ -82,6 +82,10 @@ func New(o Options) (http.Handler, error) { return nil, errors.New("server: the option Conns is required") case len(o.Fingerprint) != 0 && len(o.Fingerprint) != fingerprintLen: return nil, fmt.Errorf("server: the option Fingerprint must be empty or %d bytes long, not %d", fingerprintLen, len(o.Fingerprint)) + // A limit below zero has passed before it begins. No caller without + // credentials could send a body then, a phone that pairs included. + case o.RequestTimeout < 0: + return nil, fmt.Errorf("server: the option RequestTimeout must not be negative, and is %v", o.RequestTimeout) } if o.Log == nil { o.Log = slog.New(slog.NewTextHandler(io.Discard, nil)) @@ -116,9 +120,9 @@ func New(o Options) (http.Handler, error) { w.Write([]byte("ok")) }) mux.HandleFunc("POST /agent/v1/pair", s.handlePair) - // Every request starts under a read deadline (see the last line). On the - // three routes that need a credential it is lifted as soon as the caller - // is known. + // A request that announces a body starts under a read deadline (see the + // last line). On the three routes that need a credential it is lifted as + // soon as the caller is known. mux.Handle("GET /agent/v1/whoami", authn.Require(liftReadDeadline(http.HandlerFunc(s.handleWhoami)))) // Nothing else under /agent/ exists; it must not fall through to Docker. mux.HandleFunc("/agent/", func(w http.ResponseWriter, _ *http.Request) { diff --git a/agent/internal/server/handler_test.go b/agent/internal/server/handler_test.go index 090ef59..f4b9b77 100644 --- a/agent/internal/server/handler_test.go +++ b/agent/internal/server/handler_test.go @@ -697,16 +697,18 @@ func TestNewNamesTheRequiredOptionThatIsMissing(t *testing.T) { "Pairing": func(o *Options) { o.Pairing = nil }, "Limiter": func(o *Options) { o.Limiter = nil }, "Conns": func(o *Options) { o.Conns = nil }, + // Not missing, but of no use: a limit that has passed before it begins. + "RequestTimeout": func(o *Options) { o.RequestTimeout = -time.Second }, } { o := requiredOptions(t) without(&o) h, err := New(o) if err == nil || h != nil { - t.Errorf("New without %s built a handler", name) + t.Errorf("New without a usable %s built a handler", name) continue } if !strings.Contains(err.Error(), name) { - t.Errorf("New without %s: the error does not name it: %v", name, err) + t.Errorf("New without a usable %s: the error does not name it: %v", name, err) } } // With several missing, the first one is named. @@ -907,6 +909,39 @@ func TestACallerWithCredentialsMayTakeItsTimeOverTheBody(t *testing.T) { } } +func TestARequestWithoutABodyIsNotPutUnderTheReadDeadline(t *testing.T) { + // What stands behind the deadline takes longer than the limit before it + // answers, as an authentication does that has to wait for the disk or for + // a pairing. It answers 200 when the context of its request is still + // alive by then. + slow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(2 * requestTimeout) + if err := r.Context().Err(); err != nil { + http.Error(w, "the context of the request has ended: "+err.Error(), http.StatusInternalServerError) + return + } + w.Write([]byte("alive")) + }) + srv := httptest.NewServer(readDeadline(requestTimeout, slow)) + t.Cleanup(srv.Close) + conn := dial(t, srv.Listener.Addr().String(), 4*requestTimeout+patience) + answers := bufio.NewReader(conn) + for _, which := range []string{"a request without a body", "a second one on the same connection"} { + if _, err := io.WriteString(conn, "GET /containers/json HTTP/1.1\r\nHost: agent\r\n\r\n"); err != nil { + t.Fatalf("%s: %v", which, err) + } + resp, err := http.ReadResponse(answers, nil) + if err != nil { + t.Fatalf("%s: no answer: %v", which, err) + } + body, err := io.ReadAll(resp.Body) + resp.Body.Close() + if err != nil || resp.StatusCode != http.StatusOK || string(body) != "alive" { + t.Errorf("%s: %d %q, %v, want 200 from a handler whose context is alive", which, resp.StatusCode, strings.TrimSpace(string(body)), err) + } + } +} + // eventLine is what liveDaemon sends on a stream. const eventLine = "{\"Type\":\"container\"}\n" diff --git a/agent/internal/server/middleware.go b/agent/internal/server/middleware.go index 2dd3332..458602b 100644 --- a/agent/internal/server/middleware.go +++ b/agent/internal/server/middleware.go @@ -33,32 +33,36 @@ var uploads = regexp.MustCompile(`^(/v[0-9]+\.[0-9]+)?(/build|/images/load|/cont // gets to send the rest of its request once the headers are in. const defaultRequestTimeout = 10 * time.Second -// readDeadline puts every request under a read deadline, d from now, before -// anything else looks at it. net/http reads the rest of a request's body -// before it sends the answer, and the agent's server bounds only how long the -// headers may take. Without this deadline a request that announces a body and -// never sends it would get no answer and keep its connection for good. +// readDeadline puts a request that announces a body under a read deadline, d +// from now, before anything else looks at it. net/http reads the rest of a +// request's body before it sends the answer, and the agent's server bounds +// only how long the headers may take. Without this deadline a request that +// announces a body and never sends it would get no answer and keep its +// connection for good. A body of unknown length is announced as well. +// +// A request without a body is left alone: nothing of it is still to come, +// and the deadline would only do harm. It belongs to the connection, and +// while the handler of such a request runs, net/http keeps a read pending on +// the connection: that is how it notices a client that went away. A deadline +// that passes fails that read, and the context of the connection ends with +// it, for this request and for every later one on the connection. That would +// hit a caller whose credentials merely take longer than d to check. // // A writer that cannot set a deadline is not an error, so what // SetReadDeadline returns is ignored: the recorder of a test has no // connection that could be kept. func readDeadline(d time.Duration, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.NewResponseController(w).SetReadDeadline(time.Now().Add(d)) + if r.ContentLength != 0 { + http.NewResponseController(w).SetReadDeadline(time.Now().Add(d)) + } next.ServeHTTP(w, r) }) } // liftReadDeadline takes the read deadline off again. It stands directly -// behind authentication: a paired device uploads build contexts and images -// and holds streams and terminals open, and none of that may be cut. -// -// A request without a body needs this as much as an upload. The deadline -// belongs to the connection, and net/http keeps a read pending on the -// connection while a handler runs: that is how it notices a client that went -// away. A deadline that passes fails that read, and the request's context -// ends with it. A stream left under the deadline would end when the time is -// up. +// behind authentication: a paired device uploads build contexts and images, +// and a body of that kind takes as long as it takes. func liftReadDeadline(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.NewResponseController(w).SetReadDeadline(time.Time{}) From 6aa2783e07c38d8b1ff036740feefaeb7467f1a7 Mon Sep 17 00:00:00 2001 From: retransmit Date: Thu, 8 Oct 2026 01:18:32 +0530 Subject: [PATCH 32/32] fix(agent): a state folder others could write to is not trusted with contents --- agent/internal/state/dir.go | 142 +++++++++++++++++++-------- agent/internal/state/os_unix.go | 6 ++ agent/internal/state/os_unix_test.go | 90 +++++++++++++++++ agent/internal/state/os_windows.go | 4 + agent/internal/state/state_test.go | 82 +++++++++++++--- 5 files changed, 269 insertions(+), 55 deletions(-) diff --git a/agent/internal/state/dir.go b/agent/internal/state/dir.go index 9277c92..26d6b26 100644 --- a/agent/internal/state/dir.go +++ b/agent/internal/state/dir.go @@ -3,7 +3,6 @@ package state import ( - "crypto/rand" "errors" "fmt" "io/fs" @@ -17,20 +16,19 @@ import ( // Dir is the state folder. Only the user the agent runs as may enter it. type Dir struct{ path string } -// probePrefix is how the name of a probe begins: the file that Open writes -// and removes again to find out whether the folder can store one. A random -// part follows it, so every call tries the folder with a file of its own. An -// agent that is already running on the folder loses nothing by that, and two -// agents that are started in the same moment do not get at each other's file: -// on Windows, a name they shared would fail one of them, renaming onto what -// the other is just removing. +// probePrefix is how the name of a probe begins: the empty file that Open +// makes and removes again to find out whether the folder takes a file. A +// random part follows it, so every call tries the folder with a file of its +// own. An agent that is already running on the folder loses nothing by that, +// and two agents that are started in the same moment do not get at each +// other's file. const probePrefix = "probe." // ownFiles are the names of the files the agent keeps in its state folder, -// each with who writes it. Open takes a folder that was there before only if -// it holds nothing else, apart from probes. The other packages cannot be -// asked for their names, because they import this one: a file that gets -// another name there needs it here as well. +// each with who writes it. A folder that was there before Open may hold +// these and probes, and nothing else. The other packages cannot be asked for +// their names, because they import this one: a file that gets another name +// there needs it here as well. var ownFiles = []string{ devicesFile, // the paired devices: this package "tls.key", // the key of the agent's certificate: package tlsid @@ -39,22 +37,39 @@ var ownFiles = []string{ "agent.lock", // the lock that keeps a second agent off the folder: package admin } -// Open returns the state folder at path, which must be the agent's own. A -// folder that is not there is created with mode 0700. A folder that is there -// is taken only if it belongs to the user the agent runs as (on Unix; on -// Windows the owner is not looked at) and holds nothing but the agent's own -// files; its mode is then set to 0700. Any other folder is refused and left -// exactly as it was: a folder that others use, such as a home folder or /tmp, -// must not be made private, and the agent's files must not lie where another -// user can replace them. +// Open returns the state folder at path, which must be the agent's own. The +// path is cleaned first, so that nothing is made on a detour through ".." to +// a folder that is then refused. // -// A folder that cannot store a file is refused too, so that a full disk or a -// file system that cannot sync stops the agent when it starts and not at the -// first pairing. +// A folder that is not there is created with mode 0700. +// +// A folder that is there must belong to the user the agent runs as. What it +// may hold depends on who could write to it: +// +// - Neither its group nor others could: it may hold the agent's own files +// (see isOwn) and nothing else. +// - Its group or others could: whatever is in it, someone else may have put +// there, a device list or a key included. It must be empty, a folder +// named lost+found aside. It is then made private and looked at again, +// and it must still be empty. +// +// A folder that fails one of these checks is refused and left exactly as it +// was. The one exception is a folder that others could write to and that was +// empty at the first look only: it has been made private by the second, and +// stays so. +// +// On Windows neither the owner nor the mode is looked at, only what the +// folder holds. +// +// A folder that passes is given mode 0700. Last, an empty file is made in it +// and removed again, and a folder that takes none is refused. Whether a +// file's content can be stored is not tried: an agent has to start on a full +// disk as well, and pairing and revoking say so when they cannot write. func Open(path string) (*Dir, error) { if path == "" { return nil, errors.New("state folder path is empty") } + path = filepath.Clean(path) if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return nil, fmt.Errorf("state folder %s: %w", path, err) } @@ -70,31 +85,45 @@ func Open(path string) (*Dir, error) { if err := checkExisting(path, info); err != nil { return nil, err } + if othersCanWrite(info) { + // checkExisting found the folder empty, and others could write to + // it until now. It is closed first and then looked at again: what + // got into it in between is not the agent's either. + if err := os.Chmod(path, 0o700); err != nil { + return nil, fmt.Errorf("state folder %s: %w", path, err) + } + if err := checkStillEmpty(path); err != nil { + return nil, err + } + } } if err := os.Chmod(path, 0o700); err != nil { return nil, fmt.Errorf("state folder %s: %w", path, err) } d := &Dir{path: path} - if err := d.probe(probePrefix + rand.Text()); err != nil { + if err := d.probe(); err != nil { return nil, err } return d, nil } -// probe finds out whether the folder can store a file. It writes one called -// name the way every file of the agent is written, synced and renamed into -// place, and removes it again. -func (d *Dir) probe(name string) error { - err := d.WriteFile(name, []byte("probe\n")) - os.Remove(d.Path(name)) +// probe finds out whether a file can be made in the folder: it makes an +// empty one and removes it again. +func (d *Dir) probe() error { + probe, err := os.CreateTemp(d.path, probePrefix+"*") if err != nil { - return fmt.Errorf("state folder %s cannot store a file: %w", d.path, err) + return fmt.Errorf("state folder %s is not writable: %w", d.path, err) } + probe.Close() + os.Remove(probe.Name()) return nil } // checkExisting decides whether what was at path before Open may be the // state folder. info is what Stat says about it. Nothing is changed here. +// +// For a folder that others could write to, a nil error means that it was +// empty at this look; the caller closes it and looks again. func checkExisting(path string, info fs.FileInfo) error { if !info.IsDir() { return fmt.Errorf("state folder %s is not a folder", path) @@ -106,6 +135,12 @@ func checkExisting(path string, info fs.FileInfo) error { if err != nil { return fmt.Errorf("state folder %s: %w", path, err) } + if othersCanWrite(info) { + if e := firstEntry(entries); e != nil { + return fmt.Errorf("state folder %s: other users could write to it (mode %04o), so what it holds cannot be trusted (%q is in it): empty the folder, or set AGENT_DATA to one that does not exist yet", path, info.Mode().Perm(), e.Name()) + } + return nil + } for _, e := range entries { if !isOwn(e) { return fmt.Errorf("state folder %s holds other files (%q is one): the agent needs a folder of its own, set AGENT_DATA to one that is empty or does not exist yet", path, e.Name()) @@ -114,6 +149,35 @@ func checkExisting(path string, info fs.FileInfo) error { return nil } +// checkStillEmpty looks a second time at a folder that others could write +// to, once it has been made private. It was empty at the first look, and +// what is in it now was put there before it was closed. +func checkStillEmpty(path string) error { + entries, err := os.ReadDir(path) + if err != nil { + return fmt.Errorf("state folder %s: %w", path, err) + } + if e := firstEntry(entries); e != nil { + return fmt.Errorf("state folder %s: other users could write to it, and %q was put into it while the agent was taking it: empty the folder, or set AGENT_DATA to one that does not exist yet", path, e.Name()) + } + return nil +} + +// firstEntry returns the first entry that keeps a folder from being empty, +// or nil: every entry does but a folder named lost+found. +func firstEntry(entries []fs.DirEntry) fs.DirEntry { + for _, e := range entries { + if !isLostAndFound(e) { + return e + } + } + return nil +} + +// isLostAndFound reports whether an entry is the folder that a freshly +// formatted disk comes with when it is mounted at the path. +func isLostAndFound(e fs.DirEntry) bool { return e.Name() == "lost+found" && e.IsDir() } + // sameUser refuses a folder whose owner is not the user the agent runs as: // owner is the user id the folder belongs to, user the effective one of the // agent. Whoever owns the folder can replace what is in it, the device list @@ -126,22 +190,20 @@ func sameUser(path string, owner, user uint32) error { } // isOwn reports whether an entry of the state folder is the agent's own: one -// of ownFiles, a probe, or a temporary file that WriteFile made for one of -// those. An agent may be writing such a file right now, or have left it -// behind when it died. A folder named lost+found passes as well: a freshly -// formatted disk that is mounted at the path comes with one. +// of ownFiles, a temporary file that WriteFile made for one of them, or a +// probe. An agent may be writing such a file right now, or have left it +// behind when it died. A folder named lost+found passes as well. func isOwn(e fs.DirEntry) bool { - name := e.Name() - if name == "lost+found" { - return e.IsDir() + if isLostAndFound(e) { + return true } + name := e.Name() for _, own := range ownFiles { if name == own || begins(name, tempPrefix(own)) { return true } } - // The temporary file of a probe begins with a dot, like every other. - return begins(name, probePrefix) || begins(name, "."+probePrefix) + return begins(name, probePrefix) } // begins reports whether name starts with prefix and goes on after it. diff --git a/agent/internal/state/os_unix.go b/agent/internal/state/os_unix.go index 43193f6..6e7210c 100644 --- a/agent/internal/state/os_unix.go +++ b/agent/internal/state/os_unix.go @@ -18,3 +18,9 @@ func checkOwner(path string, info fs.FileInfo) error { } return sameUser(path, stat.Uid, uint32(os.Geteuid())) } + +// othersCanWrite reports whether the mode of a folder lets its group or +// everyone else write to it. +func othersCanWrite(info fs.FileInfo) bool { + return info.Mode().Perm()&0o022 != 0 +} diff --git a/agent/internal/state/os_unix_test.go b/agent/internal/state/os_unix_test.go index 1b829cf..9e1e99f 100644 --- a/agent/internal/state/os_unix_test.go +++ b/agent/internal/state/os_unix_test.go @@ -4,6 +4,7 @@ package state import ( "os" + "path/filepath" "strings" "syscall" "testing" @@ -38,3 +39,92 @@ func TestAFolderOfAnotherUserIsRefusedBeforeItIsLookedInto(t *testing.T) { t.Fatalf("a folder of the user who runs the test was refused: %v", err) } } + +func TestOpenTrustsWhatAFolderHoldsOnlyIfOthersCouldNotWriteToIt(t *testing.T) { + for _, c := range []struct { + mode os.FileMode + trusted bool + }{ + {0o755, true}, + {0o750, true}, + {0o700, true}, + {0o777, false}, + {0o775, false}, // the group could write + {0o757, false}, // everyone else could + {0o770, false}, + {0o777 | os.ModeSticky, false}, // as /tmp is + } { + // A device list: what an agent leaves in its folder, and what someone + // else puts there to be taken for a paired phone. + path := folderWith(t, "devices.json") + if err := os.Chmod(path, c.mode); err != nil { + t.Fatal(err) + } + held, before := holds(t, path), statFolder(t, path) + _, err := Open(path) + after := statFolder(t, path) + if c.trusted { + if err != nil { + t.Errorf("%v: a folder that only its owner could write to was refused: %v", before.Mode(), err) + } else if after.Mode().Perm() != 0o700 { + t.Errorf("%v: the mode is %v afterwards, want 0700", before.Mode(), after.Mode().Perm()) + } + continue + } + if err == nil { + t.Errorf("%v: a folder that others could write to was accepted with the device list in it", before.Mode()) + continue + } + for _, want := range []string{path, "other users could write", `"devices.json"`, "empty the folder", "AGENT_DATA"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("%v: the error does not say %s: %v", before.Mode(), want, err) + } + } + if strings.Contains(err.Error(), "\n") { + t.Errorf("%v: the error is more than one line: %q", before.Mode(), err) + } + // The folder is as it was: its mode, what it holds, and when it was + // last written to. + if after.Mode() != before.Mode() { + t.Errorf("the mode of the refused folder is now %v, it was %v", after.Mode(), before.Mode()) + } + if now := holds(t, path); strings.Join(now, "\n") != strings.Join(held, "\n") { + t.Errorf("%v: the refused folder holds %v, it held %v", before.Mode(), now, held) + } + if got, err := os.ReadFile(filepath.Join(path, "devices.json")); err != nil || string(got) != "devices.json" { + t.Errorf("%v: the device list in the refused folder was changed: %q, %v", before.Mode(), got, err) + } + if !after.ModTime().Equal(before.ModTime()) { + t.Errorf("%v: something was written into the refused folder", before.Mode()) + } + } +} + +func TestOpenTakesAnEmptyFolderThatOthersCouldWriteToAndMakesItPrivate(t *testing.T) { + for _, c := range []struct { + mode os.FileMode + holds []string + }{ + {0o777, nil}, + {0o775, nil}, + {0o777 | os.ModeSticky, nil}, + // What a freshly formatted disk comes with does not count. + {0o777, []string{"lost+found/"}}, + } { + path := folderWith(t, c.holds...) + if err := os.Chmod(path, c.mode); err != nil { + t.Fatal(err) + } + held, before := holds(t, path), statFolder(t, path) + if _, err := Open(path); err != nil { + t.Errorf("%v, holding %v: refused: %v", before.Mode(), held, err) + continue + } + if after := statFolder(t, path); after.Mode().Perm() != 0o700 || after.Mode()&os.ModeSticky != 0 { + t.Errorf("%v: the mode is %v afterwards, want drwx------", before.Mode(), after.Mode()) + } + if now := holds(t, path); strings.Join(now, "\n") != strings.Join(held, "\n") { + t.Errorf("%v: the folder holds %v afterwards, it held %v", before.Mode(), now, held) + } + } +} diff --git a/agent/internal/state/os_windows.go b/agent/internal/state/os_windows.go index 781da40..3903894 100644 --- a/agent/internal/state/os_windows.go +++ b/agent/internal/state/os_windows.go @@ -7,3 +7,7 @@ import "io/fs" // checkOwner accepts every folder: Windows has no user id that the owner of // a folder could be compared with. func checkOwner(string, fs.FileInfo) error { return nil } + +// othersCanWrite always says no: the mode that Windows reports for a folder +// says nothing about who may write to it. +func othersCanWrite(fs.FileInfo) bool { return false } diff --git a/agent/internal/state/state_test.go b/agent/internal/state/state_test.go index dcfb32d..12f898d 100644 --- a/agent/internal/state/state_test.go +++ b/agent/internal/state/state_test.go @@ -149,7 +149,7 @@ func TestOpenTakesAFolderThatHoldsOnlyTheAgentsFiles(t *testing.T) { path := folderWith(t, "admin.sock", "agent.lock", "devices.json", "tls.crt", "tls.key", ".devices.json.1234567890", ".tls.crt.42", ".tls.key.42", - "probe.LEFTBEHIND", ".probe.LEFTBEHIND.7", + "probe.1234567890", "lost+found/", ) held := holds(t, path) @@ -221,6 +221,27 @@ func TestOpenRefusesAFolderThatHoldsAnotherFileAndLeavesItAlone(t *testing.T) { } } +func TestOpenMakesNothingOnTheWayToAFolderItRefuses(t *testing.T) { + // The path leads through a folder that is not there and back out of it: + // it names the folder that holds the notes, and that one is refused. + shared := folderWith(t, "notes.txt") + held, before := holds(t, shared), statFolder(t, shared) + separator := string(filepath.Separator) + _, err := Open(shared + separator + "x" + separator + "..") + if err == nil { + t.Fatal("a folder that holds another file was accepted") + } + if !strings.Contains(err.Error(), shared) || strings.Contains(err.Error(), "..") { + t.Errorf("the error does not name the folder as it is called without the detour: %v", err) + } + if now := holds(t, shared); strings.Join(now, "\n") != strings.Join(held, "\n") { + t.Errorf("the refused folder holds %v, it held %v", now, held) + } + if after := statFolder(t, shared); !after.ModTime().Equal(before.ModTime()) { + t.Error("something was written into the refused folder") + } +} + func TestAFolderMustBelongToTheUserTheAgentRunsAs(t *testing.T) { for _, same := range []uint32{0, 1000} { if err := sameUser("/srv/agent", same, same); err != nil { @@ -245,30 +266,61 @@ func TestAFolderMustBelongToTheUserTheAgentRunsAs(t *testing.T) { } } -func TestAFolderThatCannotStoreTheProbeIsAClearError(t *testing.T) { +func TestWhatAppearsInAFolderWhileItIsTakenIsRefused(t *testing.T) { + // The second look at a folder that others could write to, after it was + // found empty and made private. Empty is what it has to be still. + for _, c := range []struct { + holds []string + refused string // the entry the error names; empty when the folder passes + }{ + {nil, ""}, + {[]string{"lost+found/"}, ""}, + // A device list that got in between the two looks. + {[]string{"devices.json"}, "devices.json"}, + {[]string{"lost+found/", "probe.1234567890"}, "probe.1234567890"}, + {[]string{"sub/"}, "sub"}, + } { + path := folderWith(t, c.holds...) + err := checkStillEmpty(path) + if c.refused == "" { + if err != nil { + t.Errorf("holding %v: refused: %v", c.holds, err) + } + continue + } + if err == nil { + t.Errorf("holding %v: accepted", c.holds) + continue + } + for _, want := range []string{path, "other users could write", `"` + c.refused + `"`, "empty the folder", "AGENT_DATA"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("holding %v: the error does not say %s: %v", c.holds, want, err) + } + } + } +} + +func TestAFolderThatTakesNoFileIsAClearError(t *testing.T) { d := openTemp(t) - // Where the probe goes there is a folder that is not empty, so the probe - // cannot be renamed into place: the folder takes no file of that name. - const name = "probe.x" - if err := os.Mkdir(d.Path(name), 0o700); err != nil { - t.Fatal(err) + if err := d.probe(); err != nil { + t.Fatalf("a folder that was just opened: %v", err) } - if err := os.WriteFile(filepath.Join(d.Path(name), "x"), nil, 0o600); err != nil { + if left := holds(t, d.Path("")); len(left) != 0 { + t.Fatalf("the probe left something behind: %v", left) + } + // The folder disappears: no file can be made in it any more. + if err := os.RemoveAll(d.Path("")); err != nil { t.Fatal(err) } - err := d.probe(name) + err := d.probe() if err == nil { - t.Fatal("the probe reported success although it could not be stored") + t.Fatal("the probe reported success although no file could be made") } - for _, want := range []string{d.Path(""), "cannot store a file"} { + for _, want := range []string{d.Path(""), "not writable"} { if !strings.Contains(err.Error(), want) { t.Errorf("the error does not say %q: %v", want, err) } } - // Nothing of the attempt is left behind. - if left := holds(t, d.Path("")); len(left) != 1 || left[0] != name { - t.Fatalf("the folder holds %v, want only what was in the way", left) - } } func TestWriteFileIsAtomicAndPrivate(t *testing.T) {