Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
7292c12
chore(agent): rename the module and tighten CI
retransmit Oct 6, 2026
0a5ac99
feat(agent): state folder and device list with hashed tokens
retransmit Oct 6, 2026
707eb94
feat(agent): TLS identity with a pinnable fingerprint
retransmit Oct 6, 2026
602f59f
feat(agent): pairing codes, proofs and links
retransmit Oct 6, 2026
37e9d92
fix(agent): state writes survive a power cut
retransmit Oct 6, 2026
71a5c68
feat(agent): pending pairing with expiry and a try limit
retransmit Oct 6, 2026
ca7828a
feat(agent): allow list for read-only devices
retransmit Oct 6, 2026
007474e
fix(agent): stretch the pairing code before it keys the proofs
retransmit Oct 6, 2026
0e05cd9
test(agent): pin single use of a pairing under concurrent calls
retransmit Oct 6, 2026
5a04cf0
fix(agent): salt the pairing key with the phone nonce
retransmit Oct 6, 2026
fe9f987
test(agent): pin every rule of the read-only allow list
retransmit Oct 6, 2026
f6027b4
feat(agent): throttle for failed attempts per address
retransmit Oct 6, 2026
4e742c2
feat(agent): per-device authentication and connection tracking
retransmit Oct 6, 2026
188d02c
feat(agent): handler with roles, pairing endpoint and access log
retransmit Oct 6, 2026
79fdc72
fix(agent): a throttle block never shrinks and IPv6 counts per network
retransmit Oct 7, 2026
7c942b7
fix(agent): a device removed mid-request keeps nothing open
retransmit Oct 7, 2026
105a5f7
fix(agent): close gaps in the pairing endpoint, access log and termin…
retransmit Oct 7, 2026
108dcb5
feat(agent): admin socket, advertised address and terminal QR codes
retransmit Oct 7, 2026
d11ffe0
fix(agent): lock the state folder, log how a pairing ended, refuse ba…
retransmit Oct 7, 2026
6bd9ebe
feat(agent): serve TLS by default, with state and graceful shutdown
retransmit Oct 7, 2026
d55ef22
fix(agent): keep server errors in the log and tidy start and stop
retransmit Oct 7, 2026
a9129f0
feat(agent): pair, devices and revoke commands
retransmit Oct 7, 2026
fc7dcf8
fix(agent): honest pair and revoke messages, help flags, a stricter t…
retransmit Oct 7, 2026
0ed3d55
fix(agent): guard the test phone's fields and report a pairing that j…
retransmit Oct 7, 2026
64f9d8c
fix(agent): bound how long a caller without credentials may take to s…
retransmit Oct 7, 2026
45595d7
fix(agent): a request that carries no token is not a failed attempt
retransmit Oct 7, 2026
abd0931
fix(agent): the state folder must belong to the agent and hold nothin…
retransmit Oct 7, 2026
f6ddb1b
fix(agent): no upgrade for read-only devices, stricter handler option…
retransmit Oct 7, 2026
70c5cbf
test(agent): the test phone sends no token while pairing, and two mor…
retransmit Oct 7, 2026
d99b274
chore: tell people who come from an earlier agent what changed
retransmit Oct 7, 2026
5d7eb65
fix(agent): the read limit reaches every request and leaves requests …
retransmit Oct 7, 2026
6aa2783
fix(agent): a state folder others could write to is not trusted with …
retransmit Oct 7, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ app/android/key.properties

# === Go (agent/) ===
agent/bin/
agent/.agent-data/
agent/vendor/
*.test
*.out
Expand Down
61 changes: 58 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,67 @@ 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=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.

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 <id>
```

`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
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 <agent container> 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.

### 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)
```
Expand Down
173 changes: 173 additions & 0 deletions agent/cmd/agent/admin_commands.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
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)
readOnly := fs.Bool("read-only", false, "pair a phone that may look but not change anything")
// 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 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 {
req.Role = "readonly"
}
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()

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)
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)
})
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 {
interrupted := errors.Is(err, context.Canceled)
stopped := err == nil || errors.Is(err, admin.ErrStopped)
if !interrupted && !stopped {
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 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")
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, 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
}
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 {
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, fs.Arg(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
}
105 changes: 105 additions & 0 deletions agent/cmd/agent/commands.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
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(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) {
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, stdout io.Writer) error {
fs := flag.NewFlagSet("healthcheck", flag.ContinueOnError)
insecure := fs.Bool("insecure-http", false, "the agent serves plain HTTP")
if done, err := parseArgs(fs, args, "healthcheck [--insecure-http]", stdout); done || err != nil {
return 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 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 {
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())
}
Loading
Loading