devbox mode (#474): the registrar
The registrar decides who owns a link name. It serves HTTP on a Unix
socket and knows a caller only by the SO_PEERCRED uid ConnContext stamps;
a connection with no uid is refused outright, never given a default.
POST /share/live {name, port} writes a service row to 127.0.0.1:<port>;
POST /share/folder?name= takes a site.tar.gz (Content-Length required,
200 MiB cap, pre-scanned for escapes, entry count and unpacked size
against the spool cap), extracts it to <spool>/<name>/<nanos>/ and swaps
current by symlink plus rename, keeping the previous tree (R7);
POST /unshare {name} is owner-only; GET /list dials live ports
concurrently with a 300 ms timeout. Refusals are JSON codes only (R1).
Rows go through UpsertUnlessRootfs (R2). One mutex covers check and
write; a failure partway through restores the link entry. A registry row
the registrar did not write is not a free name.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/devbox/peer_linux.go+38 −0internal/devbox/peer_other.go+14 −0internal/devbox/registrar.go+684 −0internal/devbox/registrar_linux_test.go+100 −0internal/devbox/registrar_test.go+879 −0
Intent
<task-notification> <task-id>ad69e545586434856</task-id> <tool-use-id>toolu_011VRFB3Kid6C7aa6apcNoP4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/ad69e545586434856.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: names and link store" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE Commit: 9739e9b2 "devbox mode (#474): link names and the durable link store". It isn't pushed. It touches only `internal/devbox`: `names.go`, `links.go` and their two test files. Tests: RED was a build failure with `Link` and `OpenLinks` undefined. GREEN passes all 7 tests (`go test ./internal/devbox -run 'TestValidName|TestNameFromBranch|TestLinks'`). gofmt is clean, and `go vet` is clean on linux, windows and darwin. Concerns, none blocking: - `Put` also refuses an invalid name with `ErrInvalidName`. The brief didn't ask for that. - JSON keys are camelCase (`ownerName`, `ownerUID`). Change them if a later task needs other keys. - Directory fsync errors are tolerated on windows only. - The report is gitignored under `.superpowers`, so it is on disk but not in the commit. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/devbox-mode/.superpowers/sdd/2026-10-30-devbox-mode/task-4-report.md</result> <usage><subagent_tokens>47238</subagent_tokens><tool_uses>6</tool_uses><duration_ms>64859</duration_ms></usage> </task-notification>
<task-notification> <task-id>bmnck9u05</task-id> <tool-use-id>toolu_01QhHpducvibKpEpw6p2nJLP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/bmnck9u05.output</output-file> <status>completed</status> <summary>Background command "Run Astra task review for Task 3" completed (exit code 0)</summary> </task-notification>
diff --git a/internal/devbox/peer_linux.go b/internal/devbox/peer_linux.go| new file mode 100644 |
| index 000000000..1258af90e |
| --- /dev/null |
| +++ b/internal/devbox/peer_linux.go |
| @@ -0,0 +1,38 @@ |
| +//go:build linux |
| + |
| +package devbox |
| + |
| +import ( |
| + "errors" |
| + "net" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// PeerUID returns the uid of the process at the other end of a Unix socket, |
| +// as the kernel recorded it at connect time (SO_PEERCRED). It follows |
| +// instancectl's peerCred. Any other kind of connection is an error. |
| +func PeerUID(c net.Conn) (uint32, error) { |
| + uc, ok := c.(*net.UnixConn) |
| + if !ok { |
| + return 0, errors.New("devbox: not a unix connection") |
| + } |
| + raw, err := uc.SyscallConn() |
| + if err != nil { |
| + return 0, err |
| + } |
| + var cred *unix.Ucred |
| + var cerr error |
| + if err := raw.Control(func(fd uintptr) { |
| + cred, cerr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) |
| + }); err != nil { |
| + return 0, err |
| + } |
| + if cerr != nil { |
| + return 0, cerr |
| + } |
| + if cred == nil { |
| + return 0, errors.New("devbox: no peer credentials") |
| + } |
| + return cred.Uid, nil |
| +} |
diff --git a/internal/devbox/peer_other.go b/internal/devbox/peer_other.go| new file mode 100644 |
| index 000000000..5f36c4f9f |
| --- /dev/null |
| +++ b/internal/devbox/peer_other.go |
| @@ -0,0 +1,14 @@ |
| +//go:build !linux |
| + |
| +package devbox |
| + |
| +import ( |
| + "errors" |
| + "net" |
| +) |
| + |
| +// PeerUID is Linux only: elsewhere there is no SO_PEERCRED, so no caller has |
| +// an identity and the registrar refuses every request. |
| +func PeerUID(c net.Conn) (uint32, error) { |
| + return 0, errors.ErrUnsupported |
| +} |
diff --git a/internal/devbox/registrar.go b/internal/devbox/registrar.go| new file mode 100644 |
| index 000000000..6e266034d |
| --- /dev/null |
| +++ b/internal/devbox/registrar.go |
| @@ -0,0 +1,684 @@ |
| +package devbox |
| + |
| +// The registrar decides who owns a link name on a shared machine (devbox |
| +// mode design §5.3-§5.5, #474). It answers HTTP on a Unix socket any local |
| +// account can reach, and it knows a caller only by the uid the kernel |
| +// reports for the socket's other end (SO_PEERCRED, stamped by ConnContext). |
| +// Nothing a client sends can name another identity: no request field is a |
| +// uid or an owner. |
| +// |
| +// It never returns prose. A refusal is JSON {"code": ..., plus data}; the |
| +// CLI renders every word from the copy deck, so the codes below are a wire |
| +// contract and must stay stable. |
| + |
| +import ( |
| + "archive/tar" |
| + "bytes" |
| + "compress/gzip" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "io/fs" |
| + "log" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Refusal codes. Each maps onto one refusal in the copy deck. |
| +const ( |
| + CodeOwned = "owned" // the name belongs to someone else; carries "owner" |
| + CodeInvalidName = "invalid-name" // not one DNS label |
| + CodeBadPort = "bad-port" // outside 1-65535 |
| + CodeFolderTooBig = "folder-too-big" // upload over MaxFolderBytes, or unpacks past the spool cap |
| + CodeSpoolFull = "spool-full" // the spool has no room for this upload |
| + CodeNotYours = "not-yours" // unshare of someone else's link; carries "owner" |
| + CodeUnknownLink = "unknown-link" // unshare of a name nobody has |
| + CodeBadRequest = "bad-request" // malformed request, or a connection with no identity |
| + // CodeInternal is not a refusal: the registrar failed (a registry or |
| + // disk error) and rolled back. The CLI treats it as an answer it does |
| + // not understand. |
| + CodeInternal = "internal" |
| +) |
| + |
| +const ( |
| + // MaxFolderBytes caps one folder upload, the compressed site.tar.gz. |
| + MaxFolderBytes = 200 << 20 |
| + // AnswerTimeout bounds each /list dial to a live link's port. |
| + AnswerTimeout = 300 * time.Millisecond |
| + |
| + // maxFolderEntries caps the entries in one upload: the spool cap counts |
| + // bytes, so without this a small archive of empty files could use up |
| + // the disk's inodes. |
| + maxFolderEntries = 100_000 |
| + // maxJSONBytes caps the JSON request bodies. |
| + maxJSONBytes = 64 << 10 |
| + // uploadReadTimeout bounds how long one upload may take to arrive, so a |
| + // client that stalls mid-body gives its upload slot back. |
| + uploadReadTimeout = 2 * time.Minute |
| + // maxUploads is how many folder bodies may be held in memory at once. |
| + maxUploads = 2 |
| + |
| + currentLink = "current" |
| + // Names inside <SpoolRoot>/<name>/ that are not a snapshot. Snapshots |
| + // are all digits, so neither prefix can collide with one. |
| + incomingPrefix = ".incoming-" |
| + swapPrefix = ".current-" |
| +) |
| + |
| +// Registrar owns the devbox's link names. The exported fields are its |
| +// configuration; set them before the first request and leave them. |
| +type Registrar struct { |
| + Reg *registry.Registry |
| + Links *Links |
| + Domain string // wildcard parent, e.g. "devbox.example.com" |
| + SpoolRoot string // same root as edge WithLocalStatic |
| + SpoolCap int64 // total bytes the spool may hold, 5 << 30 in production |
| + LookupUser func(uid uint32) string // os/user; "" when unknown |
| + |
| + // mu serialises every mutation, so the registry, Links and the spool |
| + // move together, and an ownership check holds until its write lands. |
| + mu sync.Mutex |
| + once sync.Once |
| + uploads chan struct{} |
| +} |
| + |
| +// WireError is the body of every refusal. |
| +type WireError struct { |
| + Code string `json:"code"` |
| + Owner string `json:"owner,omitempty"` |
| +} |
| + |
| +// ListEntry is one link as share, unshare and /list report it. |
| +type ListEntry struct { |
| + Name string `json:"name"` |
| + Host string `json:"host"` |
| + Owner string `json:"owner"` |
| + OwnerUID uint32 `json:"ownerUID"` |
| + Kind Kind `json:"kind"` |
| + Target string `json:"target"` // live: 127.0.0.1:<port>; folder: "" |
| + Created time.Time `json:"created"` |
| + Updated time.Time `json:"updated"` |
| + // Answering: live, the port took a connection within AnswerTimeout; |
| + // folder, the current snapshot resolves. |
| + Answering bool `json:"answering"` |
| +} |
| + |
| +type peerKey struct{} |
| + |
| +// WithPeerUID returns ctx carrying uid as the caller's identity. |
| +func WithPeerUID(ctx context.Context, uid uint32) context.Context { |
| + return context.WithValue(ctx, peerKey{}, uid) |
| +} |
| + |
| +func peerUIDFrom(ctx context.Context) (uint32, bool) { |
| + uid, ok := ctx.Value(peerKey{}).(uint32) |
| + return uid, ok |
| +} |
| + |
| +// ConnContext is for http.Server.ConnContext. It stamps the connection's |
| +// SO_PEERCRED uid. A connection whose uid cannot be read gets no identity, |
| +// and the handler refuses every request on it. |
| +func ConnContext(ctx context.Context, c net.Conn) context.Context { |
| + uid, err := PeerUID(c) |
| + if err != nil { |
| + return ctx |
| + } |
| + return WithPeerUID(ctx, uid) |
| +} |
| + |
| +// refusal is a decided answer: an HTTP status and the wire body. |
| +type refusal struct { |
| + status int |
| + body WireError |
| +} |
| + |
| +func refuse(status int, code string) *refusal { |
| + return &refusal{status: status, body: WireError{Code: code}} |
| +} |
| + |
| +func internalErr(op string, err error) *refusal { |
| + log.Printf("devbox registrar: %s: %v", op, err) |
| + return refuse(http.StatusInternalServerError, CodeInternal) |
| +} |
| + |
| +// Handler serves the wire API. The caller's uid comes from the request |
| +// context only (WithPeerUID, ConnContext). |
| +func (r *Registrar) Handler() http.Handler { |
| + r.once.Do(func() { r.uploads = make(chan struct{}, maxUploads) }) |
| + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| + uid, ok := peerUIDFrom(req.Context()) |
| + if !ok { |
| + writeJSON(w, http.StatusBadRequest, WireError{Code: CodeBadRequest}) |
| + return |
| + } |
| + if r.Domain == "" || r.SpoolRoot == "" || r.Reg == nil || r.Links == nil { |
| + writeRefusal(w, internalErr("config", errors.New("registrar not configured"))) |
| + return |
| + } |
| + route := req.Method + " " + req.URL.Path |
| + var ( |
| + out any |
| + ref *refusal |
| + ) |
| + switch route { |
| + case "POST /share/live": |
| + out, ref = r.serveShareLive(uid, w, req) |
| + case "POST /share/folder": |
| + out, ref = r.serveShareFolder(uid, w, req) |
| + case "POST /unshare": |
| + out, ref = r.serveUnshare(uid, w, req) |
| + case "GET /list": |
| + out = r.list(req.Context()) |
| + default: |
| + ref = refuse(http.StatusNotFound, CodeBadRequest) |
| + } |
| + if ref != nil { |
| + writeRefusal(w, ref) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| + }) |
| +} |
| + |
| +func writeRefusal(w http.ResponseWriter, ref *refusal) { writeJSON(w, ref.status, ref.body) } |
| + |
| +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 decodeJSON(w http.ResponseWriter, req *http.Request, v any) *refusal { |
| + body := http.MaxBytesReader(w, req.Body, maxJSONBytes) |
| + if err := json.NewDecoder(body).Decode(v); err != nil { |
| + return refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + return nil |
| +} |
| + |
| +func (r *Registrar) host(name string) string { return name + "." + r.Domain } |
| + |
| +// owner is how a uid is shown: its username now, or "uid N" when the |
| +// account is unknown. |
| +func (r *Registrar) owner(uid uint32) string { |
| + if r.LookupUser != nil { |
| + if n := r.LookupUser(uid); n != "" { |
| + return n |
| + } |
| + } |
| + return "uid " + strconv.FormatUint(uint64(uid), 10) |
| +} |
| + |
| +func (r *Registrar) lookupName(uid uint32) string { |
| + if r.LookupUser == nil { |
| + return "" |
| + } |
| + return r.LookupUser(uid) |
| +} |
| + |
| +func (r *Registrar) entry(k Link) ListEntry { |
| + e := ListEntry{Name: k.Name, Host: r.host(k.Name), Owner: r.owner(k.OwnerUID), OwnerUID: k.OwnerUID, |
| + Kind: k.Kind, Created: k.Created, Updated: k.Updated} |
| + if k.Kind == KindLive { |
| + e.Target = liveAddr(k.Port) |
| + } |
| + return e |
| +} |
| + |
| +func liveAddr(port int) string { return "127.0.0.1:" + strconv.Itoa(port) } |
| + |
| +// claim decides whether uid may write name, and returns the link there now. |
| +// The caller holds r.mu and keeps holding it until its write lands. |
| +func (r *Registrar) claim(uid uint32, name string) (prev Link, had bool, ref *refusal) { |
| + prev, had = r.Links.Get(name) |
| + if had && prev.OwnerUID != uid { |
| + return prev, had, &refusal{status: http.StatusConflict, body: WireError{Code: CodeOwned, Owner: r.owner(prev.OwnerUID)}} |
| + } |
| + row, err := r.Reg.Get(r.host(name)) |
| + if err != nil { |
| + return prev, had, internalErr("registry get", err) |
| + } |
| + // A row the registrar did not write (an operator's own route at that |
| + // host) is not a free name. The registrar never leaves a row without a |
| + // link: it writes Links before the row and removes the row before Links. |
| + if !had && row != nil { |
| + return prev, had, refuse(http.StatusConflict, CodeOwned) |
| + } |
| + return prev, had, nil |
| +} |
| + |
| +// restoreLink puts Links back to what claim saw. Share writes the link |
| +// before the row, and its one row write is a single statement, so when a |
| +// share fails the row has not changed and only the link needs undoing. |
| +func (r *Registrar) restoreLink(name string, prev Link, had bool) { |
| + var err error |
| + if had { |
| + err = r.Links.Put(prev) |
| + } else { |
| + err = r.Links.Delete(name) |
| + } |
| + if err != nil { |
| + log.Printf("devbox registrar: rollback link %s: %v", name, err) |
| + } |
| +} |
| + |
| +func (r *Registrar) serveShareLive(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) { |
| + var in struct { |
| + Name string `json:"name"` |
| + Port int `json:"port"` |
| + } |
| + if ref := decodeJSON(w, req, &in); ref != nil { |
| + return nil, ref |
| + } |
| + if ValidName(in.Name) != nil { |
| + return nil, refuse(http.StatusBadRequest, CodeInvalidName) |
| + } |
| + if in.Port < 1 || in.Port > 65535 { |
| + return nil, refuse(http.StatusBadRequest, CodeBadPort) |
| + } |
| + |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + prev, had, ref := r.claim(uid, in.Name) |
| + if ref != nil { |
| + return nil, ref |
| + } |
| + now := time.Now().UTC() |
| + link := Link{Name: in.Name, OwnerName: r.lookupName(uid), OwnerUID: uid, Kind: KindLive, Port: in.Port, Created: now, Updated: now} |
| + if had { |
| + link.Created = prev.Created |
| + } |
| + if err := r.Links.Put(link); err != nil { |
| + return nil, internalErr("links put", err) |
| + } |
| + row := registry.Route{Host: r.host(in.Name), Kind: "service", Addr: liveAddr(in.Port), App: in.Name, Status: "ready"} |
| + if err := r.Reg.UpsertUnlessRootfs(row); err != nil { |
| + r.restoreLink(in.Name, prev, had) |
| + return nil, internalErr("registry upsert", err) |
| + } |
| + if had && prev.Kind == KindFolder { |
| + r.removeSpool(in.Name) |
| + } |
| + return r.entry(link), nil |
| +} |
| + |
| +func (r *Registrar) serveUnshare(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) { |
| + var in struct { |
| + Name string `json:"name"` |
| + } |
| + if ref := decodeJSON(w, req, &in); ref != nil { |
| + return nil, ref |
| + } |
| + if ValidName(in.Name) != nil { |
| + return nil, refuse(http.StatusBadRequest, CodeInvalidName) |
| + } |
| + |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + prev, had := r.Links.Get(in.Name) |
| + if !had { |
| + return nil, refuse(http.StatusNotFound, CodeUnknownLink) |
| + } |
| + if prev.OwnerUID != uid { |
| + return nil, &refusal{status: http.StatusForbidden, body: WireError{Code: CodeNotYours, Owner: r.owner(prev.OwnerUID)}} |
| + } |
| + host := r.host(in.Name) |
| + prevRow, err := r.Reg.Get(host) |
| + if err != nil { |
| + return nil, internalErr("registry get", err) |
| + } |
| + // The row first, then the link: a crash between them leaves a link with |
| + // no row, which its owner can unshare again, never a row with no owner. |
| + if err := r.Reg.Delete(host); err != nil { |
| + return nil, internalErr("registry delete", err) |
| + } |
| + if err := r.Links.Delete(in.Name); err != nil { |
| + if prevRow != nil { |
| + if rerr := r.Reg.UpsertUnlessRootfs(*prevRow); rerr != nil { |
| + log.Printf("devbox registrar: rollback row %s: %v", host, rerr) |
| + } |
| + } |
| + return nil, internalErr("links delete", err) |
| + } |
| + r.removeSpool(in.Name) |
| + return r.entry(prev), nil |
| +} |
| + |
| +func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) { |
| + name := req.URL.Query().Get("name") |
| + if ValidName(name) != nil { |
| + return nil, refuse(http.StatusBadRequest, CodeInvalidName) |
| + } |
| + // The length is decided up front: a body with no declared length is |
| + // refused before a byte is read, and one over the cap is refused on its |
| + // header alone. |
| + if req.ContentLength < 0 { |
| + return nil, refuse(http.StatusLengthRequired, CodeBadRequest) |
| + } |
| + if req.ContentLength > MaxFolderBytes { |
| + return nil, refuse(http.StatusRequestEntityTooLarge, CodeFolderTooBig) |
| + } |
| + // Cheap early refusals before taking an upload slot. claim repeats them |
| + // under the lock. |
| + if k, ok := r.Links.Get(name); ok && k.OwnerUID != uid { |
| + return nil, &refusal{status: http.StatusConflict, body: WireError{Code: CodeOwned, Owner: r.owner(k.OwnerUID)}} |
| + } |
| + |
| + select { |
| + case r.uploads <- struct{}{}: |
| + defer func() { <-r.uploads }() |
| + case <-req.Context().Done(): |
| + return nil, refuse(http.StatusServiceUnavailable, CodeInternal) |
| + } |
| + // Not supported under httptest; the cap below holds either way. |
| + _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(uploadReadTimeout)) |
| + data := make([]byte, req.ContentLength) |
| + body := http.MaxBytesReader(w, req.Body, MaxFolderBytes) |
| + if _, err := io.ReadFull(body, data); err != nil { |
| + var mbe *http.MaxBytesError |
| + if errors.As(err, &mbe) { |
| + return nil, refuse(http.StatusRequestEntityTooLarge, CodeFolderTooBig) |
| + } |
| + return nil, refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + // Anything past the declared length is a lie about it. |
| + var one [1]byte |
| + if n, _ := body.Read(one[:]); n != 0 { |
| + return nil, refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + |
| + unpacked, ref := scanSite(data, r.SpoolCap) |
| + if ref != nil { |
| + return nil, ref |
| + } |
| + |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + prev, had, ref := r.claim(uid, name) |
| + if ref != nil { |
| + return nil, ref |
| + } |
| + used, err := spoolUsage(r.SpoolRoot) |
| + if err != nil { |
| + return nil, internalErr("spool usage", err) |
| + } |
| + need := unpacked |
| + if int64(len(data)) > need { |
| + need = int64(len(data)) |
| + } |
| + if used+need > r.SpoolCap { |
| + return nil, refuse(http.StatusInsufficientStorage, CodeSpoolFull) |
| + } |
| + |
| + dir, err := r.linkDir(name) |
| + if err != nil { |
| + return nil, internalErr("spool dir", err) |
| + } |
| + prevSnap := "" |
| + if had && prev.Kind == KindFolder { |
| + prevSnap = prev.Snapshot |
| + } |
| + // discard undoes this upload's disk writes. With no earlier tree to go |
| + // back to, the whole link dir goes, so a refused first upload leaves |
| + // nothing behind. |
| + discard := func(snapDir string) { |
| + if prevSnap == "" { |
| + r.removeSpool(name) |
| + } else if snapDir != "" { |
| + os.RemoveAll(snapDir) |
| + } |
| + } |
| + snap, ref := extractSnapshot(data, dir) |
| + if ref != nil { |
| + discard("") |
| + return nil, ref |
| + } |
| + snapDir := filepath.Join(dir, snap) |
| + |
| + now := time.Now().UTC() |
| + link := Link{Name: name, OwnerName: r.lookupName(uid), OwnerUID: uid, Kind: KindFolder, Snapshot: snap, Created: now, Updated: now} |
| + if had { |
| + link.Created = prev.Created |
| + } |
| + if err := r.Links.Put(link); err != nil { |
| + discard(snapDir) |
| + return nil, internalErr("links put", err) |
| + } |
| + if err := swapCurrent(dir, snap); err != nil { |
| + r.restoreLink(name, prev, had) |
| + discard(snapDir) |
| + return nil, internalErr("swap current", err) |
| + } |
| + row := registry.Route{Host: r.host(name), Kind: "static", App: name, Status: "ready"} |
| + if err := r.Reg.UpsertUnlessRootfs(row); err != nil { |
| + // Point current back where it was; with no earlier tree, discard |
| + // removes current along with the rest. |
| + if prevSnap != "" { |
| + if serr := swapCurrent(dir, prevSnap); serr != nil { |
| + log.Printf("devbox registrar: rollback current %s: %v", name, serr) |
| + } |
| + } |
| + r.restoreLink(name, prev, had) |
| + discard(snapDir) |
| + return nil, internalErr("registry upsert", err) |
| + } |
| + pruneSnapshots(dir, snap, prevSnap) |
| + return r.entry(link), nil |
| +} |
| + |
| +// linkDir returns <SpoolRoot>/<name>, creating it. Whatever is at that path |
| +// must be a real directory: a symlink there would let a write land outside |
| +// the spool. |
| +func (r *Registrar) linkDir(name string) (string, error) { |
| + if err := os.MkdirAll(r.SpoolRoot, 0o755); err != nil { |
| + return "", err |
| + } |
| + dir := filepath.Join(r.SpoolRoot, name) |
| + if err := os.Mkdir(dir, 0o755); err != nil && !errors.Is(err, fs.ErrExist) { |
| + return "", err |
| + } |
| + fi, err := os.Lstat(dir) |
| + if err != nil { |
| + return "", err |
| + } |
| + if !fi.IsDir() { |
| + return "", fmt.Errorf("%s is not a directory", dir) |
| + } |
| + return dir, nil |
| +} |
| + |
| +// removeSpool deletes a link's spool directory. os.RemoveAll never follows |
| +// a symlink, at the top or below, so a link planted there removes only |
| +// itself. |
| +func (r *Registrar) removeSpool(name string) { |
| + if err := os.RemoveAll(filepath.Join(r.SpoolRoot, name)); err != nil { |
| + log.Printf("devbox registrar: remove spool %s: %v", name, err) |
| + } |
| +} |
| + |
| +// extractSnapshot unpacks data into a fresh directory under dir and renames |
| +// it to a snapshot name (unix nanos), returning that name. |
| +func extractSnapshot(data []byte, dir string) (string, *refusal) { |
| + tmp, err := os.MkdirTemp(dir, incomingPrefix) |
| + if err != nil { |
| + return "", internalErr("mkdir temp", err) |
| + } |
| + if err := os.Chmod(tmp, 0o755); err != nil { |
| + os.RemoveAll(tmp) |
| + return "", internalErr("chmod", err) |
| + } |
| + if err := edge.ExtractSite(data, tmp); err != nil { |
| + os.RemoveAll(tmp) |
| + if errors.Is(err, syscall.ENOSPC) { |
| + return "", refuse(http.StatusInsufficientStorage, CodeSpoolFull) |
| + } |
| + return "", refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + n := time.Now().UnixNano() |
| + for { |
| + snap := strconv.FormatInt(n, 10) |
| + dst := filepath.Join(dir, snap) |
| + if _, err := os.Lstat(dst); errors.Is(err, fs.ErrNotExist) { |
| + if err := os.Rename(tmp, dst); err != nil { |
| + os.RemoveAll(tmp) |
| + return "", internalErr("rename snapshot", err) |
| + } |
| + return snap, nil |
| + } |
| + n++ |
| + } |
| +} |
| + |
| +// swapCurrent points dir/current at snap: a fresh relative symlink renamed |
| +// over the old one, so a reader sees the old tree or the new, never neither. |
| +func swapCurrent(dir, snap string) error { |
| + tmp := filepath.Join(dir, swapPrefix+strconv.FormatInt(time.Now().UnixNano(), 10)) |
| + if err := os.Symlink(snap, tmp); err != nil { |
| + return err |
| + } |
| + if err := os.Rename(tmp, filepath.Join(dir, currentLink)); err != nil { |
| + os.Remove(tmp) |
| + return err |
| + } |
| + return syncDir(dir) |
| +} |
| + |
| +// pruneSnapshots removes everything in dir except current, the new snapshot |
| +// and the one before it (ruling R7: a request that resolved current just |
| +// before the swap may still be reading it). Leftovers of a crashed upload go |
| +// too. |
| +func pruneSnapshots(dir, keep, prev string) { |
| + ents, err := os.ReadDir(dir) |
| + if err != nil { |
| + log.Printf("devbox registrar: prune %s: %v", dir, err) |
| + return |
| + } |
| + for _, e := range ents { |
| + n := e.Name() |
| + if n == currentLink || n == keep || (prev != "" && n == prev) { |
| + continue |
| + } |
| + if err := os.RemoveAll(filepath.Join(dir, n)); err != nil { |
| + log.Printf("devbox registrar: prune %s/%s: %v", dir, n, err) |
| + } |
| + } |
| +} |
| + |
| +// spoolUsage is the bytes of regular files under root. WalkDir does not |
| +// follow symlinks, so a link in the spool counts only itself. |
| +func spoolUsage(root string) (int64, error) { |
| + var total int64 |
| + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { |
| + if err != nil { |
| + if p == root && errors.Is(err, fs.ErrNotExist) { |
| + return filepath.SkipAll |
| + } |
| + return err |
| + } |
| + if d.Type().IsRegular() { |
| + fi, err := d.Info() |
| + if err != nil { |
| + return err |
| + } |
| + total += fi.Size() |
| + } |
| + return nil |
| + }) |
| + return total, err |
| +} |
| + |
| +// scanSite reads a site.tar.gz the way edge.ExtractSite will, without |
| +// writing anything, and returns the bytes it would write. It refuses what |
| +// ExtractSite would refuse (bad-request), and an archive that would unpack |
| +// past limit or hold too many entries (folder-too-big). Decompression stops |
| +// as soon as the declared sizes pass limit, so a gzip bomb costs little. |
| +func scanSite(data []byte, limit int64) (int64, *refusal) { |
| + gz, err := gzip.NewReader(bytes.NewReader(data)) |
| + if err != nil { |
| + return 0, refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + defer gz.Close() |
| + tr := tar.NewReader(gz) |
| + var total int64 |
| + for entries := 0; ; entries++ { |
| + hdr, err := tr.Next() |
| + if err == io.EOF { |
| + return total, nil |
| + } |
| + if err != nil { |
| + return 0, refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + if entries >= maxFolderEntries { |
| + return 0, refuse(http.StatusRequestEntityTooLarge, CodeFolderTooBig) |
| + } |
| + name := filepath.FromSlash(path.Clean(hdr.Name)) |
| + if !filepath.IsLocal(name) || strings.ContainsRune(hdr.Name, 0) { |
| + return 0, refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + switch hdr.Typeflag { |
| + case tar.TypeDir, tar.TypeXGlobalHeader: |
| + case tar.TypeReg: |
| + if hdr.Size < 0 { |
| + return 0, refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + total += hdr.Size |
| + if total > limit { |
| + return 0, refuse(http.StatusRequestEntityTooLarge, CodeFolderTooBig) |
| + } |
| + default: |
| + return 0, refuse(http.StatusBadRequest, CodeBadRequest) |
| + } |
| + } |
| +} |
| + |
| +// list reports every link. It holds no registrar lock: Links.All is a |
| +// consistent copy on its own, and the dials must not stall a share. |
| +func (r *Registrar) list(ctx context.Context) []ListEntry { |
| + links := r.Links.All() |
| + out := make([]ListEntry, len(links)) |
| + var wg sync.WaitGroup |
| + for i, k := range links { |
| + out[i] = r.entry(k) |
| + switch k.Kind { |
| + case KindLive: |
| + wg.Add(1) |
| + go func(i, port int) { |
| + defer wg.Done() |
| + out[i].Answering = dialAnswer(ctx, port) |
| + }(i, k.Port) |
| + case KindFolder: |
| + _, err := filepath.EvalSymlinks(filepath.Join(r.SpoolRoot, k.Name, currentLink)) |
| + out[i].Answering = err == nil |
| + } |
| + } |
| + wg.Wait() |
| + return out |
| +} |
| + |
| +// dialAnswer is answering; a test swaps it for a slow dial. |
| +var dialAnswer = answering |
| + |
| +// answering reports whether 127.0.0.1:port takes a TCP connection within |
| +// AnswerTimeout. |
| +func answering(ctx context.Context, port int) bool { |
| + d := net.Dialer{Timeout: AnswerTimeout} |
| + c, err := d.DialContext(ctx, "tcp", liveAddr(port)) |
| + if err != nil { |
| + return false |
| + } |
| + c.Close() |
| + return true |
| +} |
diff --git a/internal/devbox/registrar_linux_test.go b/internal/devbox/registrar_linux_test.go| new file mode 100644 |
| index 000000000..46fca91e3 |
| --- /dev/null |
| +++ b/internal/devbox/registrar_linux_test.go |
| @@ -0,0 +1,100 @@ |
| +//go:build linux |
| + |
| +package devbox |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// TestSocketCallerIdentity runs the registrar behind a real http.Server on a |
| +// Unix socket: ConnContext stamps the peer's SO_PEERCRED uid, and a request |
| +// from this process is attributed to this process's uid. Needs a short |
| +// TMPDIR (the socket path limit is 108 bytes). |
| +func TestSocketCallerIdentity(t *testing.T) { |
| + f := newFixture(t) |
| + f.r.LookupUser = func(uint32) string { return "" } |
| + sock := filepath.Join(t.TempDir(), "r.sock") |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatalf("listen %s: %v", sock, err) |
| + } |
| + srv := &http.Server{Handler: f.r.Handler(), ConnContext: ConnContext} |
| + go srv.Serve(ln) |
| + t.Cleanup(func() { srv.Close() }) |
| + |
| + client := &http.Client{Transport: &http.Transport{ |
| + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "unix", sock) |
| + }, |
| + }} |
| + t.Cleanup(client.CloseIdleConnections) |
| + |
| + // The body claims another uid; the socket decides. |
| + resp, err := client.Post("http://devbox/share/live", "application/json", |
| + strings.NewReader(`{"name":"shop","port":8080,"ownerUID":0}`)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 { |
| + t.Fatalf("share = %d", resp.StatusCode) |
| + } |
| + me := uint32(os.Getuid()) |
| + k, ok := f.r.Links.Get("shop") |
| + if !ok || k.OwnerUID != me { |
| + t.Fatalf("link = %+v, want owner uid %d", k, me) |
| + } |
| + |
| + resp, err = client.Get("http://devbox/list") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + var got []ListEntry |
| + if err := json.NewDecoder(resp.Body).Decode(&got); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(got) != 1 || got[0].OwnerUID != me { |
| + t.Fatalf("list = %+v", got) |
| + } |
| + |
| + // PeerUID on the server side of a real socket reads this uid too. |
| + a, b, err := unixPair(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer a.Close() |
| + defer b.Close() |
| + uid, err := PeerUID(a) |
| + if err != nil || uid != me { |
| + t.Fatalf("PeerUID = %d, %v; want %d", uid, err, me) |
| + } |
| +} |
| + |
| +// unixPair returns the two ends of a connected Unix socket. |
| +func unixPair(t *testing.T) (net.Conn, net.Conn, error) { |
| + t.Helper() |
| + sock := filepath.Join(t.TempDir(), "p.sock") |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + defer ln.Close() |
| + ch := make(chan net.Conn, 1) |
| + go func() { |
| + c, _ := ln.Accept() |
| + ch <- c |
| + }() |
| + client, err := net.Dial("unix", sock) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + return <-ch, client, nil |
| +} |
diff --git a/internal/devbox/registrar_test.go b/internal/devbox/registrar_test.go| new file mode 100644 |
| index 000000000..8805702e2 |
| --- /dev/null |
| +++ b/internal/devbox/registrar_test.go |
| @@ -0,0 +1,879 @@ |
| +package devbox |
| + |
| +import ( |
| + "archive/tar" |
| + "bytes" |
| + "compress/gzip" |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "sort" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +const testDomain = "devbox.example.com" |
| + |
| +var testUsers = map[uint32]string{1001: "ana", 1002: "ben"} |
| + |
| +type fixture struct { |
| + r *Registrar |
| + reg *registry.Registry |
| + spool string |
| + linksPath string |
| +} |
| + |
| +func newFixture(t *testing.T) *fixture { |
| + t.Helper() |
| + dir := t.TempDir() |
| + reg, err := registry.Open(filepath.Join(dir, "routes.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + linksPath := filepath.Join(dir, "links.json") |
| + links, err := OpenLinks(linksPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + spool := filepath.Join(dir, "spool") |
| + return &fixture{ |
| + r: &Registrar{ |
| + Reg: reg, |
| + Links: links, |
| + Domain: testDomain, |
| + SpoolRoot: spool, |
| + SpoolCap: 5 << 30, |
| + LookupUser: func(uid uint32) string { return testUsers[uid] }, |
| + }, |
| + reg: reg, |
| + spool: spool, |
| + linksPath: linksPath, |
| + } |
| +} |
| + |
| +func (f *fixture) do(t *testing.T, uid uint32, method, target string, body io.Reader) *httptest.ResponseRecorder { |
| + t.Helper() |
| + req := httptest.NewRequest(method, "http://devbox"+target, body) |
| + req = req.WithContext(WithPeerUID(req.Context(), uid)) |
| + rec := httptest.NewRecorder() |
| + f.r.Handler().ServeHTTP(rec, req) |
| + return rec |
| +} |
| + |
| +func (f *fixture) shareLive(t *testing.T, uid uint32, name string, port int) *httptest.ResponseRecorder { |
| + t.Helper() |
| + body, _ := json.Marshal(map[string]any{"name": name, "port": port}) |
| + return f.do(t, uid, "POST", "/share/live", bytes.NewReader(body)) |
| +} |
| + |
| +func (f *fixture) shareFolder(t *testing.T, uid uint32, name string, site []byte) *httptest.ResponseRecorder { |
| + t.Helper() |
| + return f.do(t, uid, "POST", "/share/folder?name="+url.QueryEscape(name), bytes.NewReader(site)) |
| +} |
| + |
| +func (f *fixture) unshare(t *testing.T, uid uint32, name string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + body, _ := json.Marshal(map[string]any{"name": name}) |
| + return f.do(t, uid, "POST", "/unshare", bytes.NewReader(body)) |
| +} |
| + |
| +func (f *fixture) list(t *testing.T, uid uint32) []ListEntry { |
| + t.Helper() |
| + rec := f.do(t, uid, "GET", "/list", nil) |
| + if rec.Code != 200 { |
| + t.Fatalf("list = %d %s", rec.Code, rec.Body) |
| + } |
| + var out []ListEntry |
| + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { |
| + t.Fatalf("list body %q: %v", rec.Body, err) |
| + } |
| + return out |
| +} |
| + |
| +func (f *fixture) row(t *testing.T, name string) *registry.Route { |
| + t.Helper() |
| + rt, err := f.reg.Get(name + "." + testDomain) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return rt |
| +} |
| + |
| +func wantOK(t *testing.T, rec *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if rec.Code != 200 { |
| + t.Fatalf("status %d, body %s; want 200", rec.Code, rec.Body) |
| + } |
| +} |
| + |
| +func wantCode(t *testing.T, rec *httptest.ResponseRecorder, code string) WireError { |
| + t.Helper() |
| + var e WireError |
| + if err := json.Unmarshal(rec.Body.Bytes(), &e); err != nil { |
| + t.Fatalf("status %d, body %q is not a wire error: %v", rec.Code, rec.Body, err) |
| + } |
| + if e.Code != code { |
| + t.Fatalf("status %d, code %q (body %s); want %q", rec.Code, e.Code, rec.Body, code) |
| + } |
| + if rec.Code < 400 { |
| + t.Fatalf("refusal %q answered %d", code, rec.Code) |
| + } |
| + // R1: codes and data only. The body has no field beyond code and owner. |
| + var raw map[string]any |
| + _ = json.Unmarshal(rec.Body.Bytes(), &raw) |
| + for k := range raw { |
| + if k != "code" && k != "owner" { |
| + t.Fatalf("wire error carries %q: %s", k, rec.Body) |
| + } |
| + } |
| + return e |
| +} |
| + |
| +// packSite builds a site.tar.gz in edge.PackDir's format from files. |
| +func packSite(t *testing.T, files map[string]string) []byte { |
| + t.Helper() |
| + dir := t.TempDir() |
| + for name, body := range files { |
| + p := filepath.Join(dir, filepath.FromSlash(name)) |
| + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + data, err := edge.PackDir(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return data |
| +} |
| + |
| +// rawTar builds a site.tar.gz from raw headers, for archives PackDir would |
| +// never emit. |
| +func rawTar(t *testing.T, hdrs ...*tar.Header) []byte { |
| + t.Helper() |
| + var buf bytes.Buffer |
| + gz := gzip.NewWriter(&buf) |
| + tw := tar.NewWriter(gz) |
| + for _, h := range hdrs { |
| + if err := tw.WriteHeader(h); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.Typeflag == tar.TypeReg && h.Size > 0 { |
| + if _, err := tw.Write(bytes.Repeat([]byte("x"), int(h.Size))); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + tw.Close() |
| + gz.Close() |
| + return buf.Bytes() |
| +} |
| + |
| +func readCurrent(t *testing.T, spool, name, file string) string { |
| + t.Helper() |
| + data, err := os.ReadFile(filepath.Join(spool, name, "current", file)) |
| + if err != nil { |
| + t.Fatalf("read %s/current/%s: %v", name, file, err) |
| + } |
| + return string(data) |
| +} |
| + |
| +func dirNames(t *testing.T, dir string) []string { |
| + t.Helper() |
| + ents, err := os.ReadDir(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out []string |
| + for _, e := range ents { |
| + out = append(out, e.Name()) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +func closedPort(t *testing.T) int { |
| + t.Helper() |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + port := ln.Addr().(*net.TCPAddr).Port |
| + ln.Close() |
| + return port |
| +} |
| + |
| +func TestShareLiveWritesServiceRoute(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareLive(t, 1001, "shop", 5173)) |
| + |
| + rt := f.row(t, "shop") |
| + if rt == nil { |
| + t.Fatal("no registry row") |
| + } |
| + got := registry.Route{Host: rt.Host, Kind: rt.Kind, Addr: rt.Addr, App: rt.App, Status: rt.Status} |
| + want := registry.Route{Host: "shop." + testDomain, Kind: "service", Addr: "127.0.0.1:5173", App: "shop", Status: "ready"} |
| + if got != want { |
| + t.Fatalf("row = %+v, want %+v", got, want) |
| + } |
| + if rt.Socket != "" || rt.Addrs != "" || rt.Runtime != "" { |
| + t.Fatalf("row carries extra upstreams: socket %q addrs %q runtime %q", rt.Socket, rt.Addrs, rt.Runtime) |
| + } |
| + k, ok := f.r.Links.Get("shop") |
| + if !ok || k.OwnerUID != 1001 || k.OwnerName != "ana" || k.Name != "shop" || k.Kind != KindLive || k.Port != 5173 { |
| + t.Fatalf("link = %+v, %v", k, ok) |
| + } |
| +} |
| + |
| +func TestShareLiveRefusesBadPort(t *testing.T) { |
| + for _, port := range []int{0, 70000, -1, 65536} { |
| + f := newFixture(t) |
| + wantCode(t, f.shareLive(t, 1001, "shop", port), CodeBadPort) |
| + if rt := f.row(t, "shop"); rt != nil { |
| + t.Fatalf("port %d: row written: %+v", port, rt) |
| + } |
| + if _, ok := f.r.Links.Get("shop"); ok { |
| + t.Fatalf("port %d: link written", port) |
| + } |
| + } |
| + // The wire carries a port, never a host: a host in the body is ignored, |
| + // the upstream is loopback. |
| + f := newFixture(t) |
| + body := `{"name":"shop","port":8080,"host":"10.0.0.5","addr":"10.0.0.5:8080"}` |
| + wantOK(t, f.do(t, 1001, "POST", "/share/live", strings.NewReader(body))) |
| + if rt := f.row(t, "shop"); rt.Addr != "127.0.0.1:8080" { |
| + t.Fatalf("addr = %q", rt.Addr) |
| + } |
| +} |
| + |
| +func TestShareRefusesInvalidName(t *testing.T) { |
| + f := newFixture(t) |
| + for _, name := range []string{"", "..", "../etc", "a/b", "Shop", "-shop", "shop.example", strings.Repeat("a", 64)} { |
| + wantCode(t, f.shareLive(t, 1001, name, 8080), CodeInvalidName) |
| + wantCode(t, f.shareFolder(t, 1001, name, packSite(t, map[string]string{"index.html": "x"})), CodeInvalidName) |
| + wantCode(t, f.unshare(t, 1001, name), CodeInvalidName) |
| + } |
| + if got := f.r.Links.All(); len(got) != 0 { |
| + t.Fatalf("links = %+v", got) |
| + } |
| + if _, err := os.Stat(f.spool); err == nil { |
| + if names := dirNames(t, f.spool); len(names) != 0 { |
| + t.Fatalf("spool has %v", names) |
| + } |
| + } |
| +} |
| + |
| +func TestShareRefusesOtherOwnersName(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareLive(t, 1001, "shop", 5173)) |
| + before, _ := f.r.Links.Get("shop") |
| + rowBefore := f.row(t, "shop") |
| + |
| + e := wantCode(t, f.shareLive(t, 1002, "shop", 9999), CodeOwned) |
| + if e.Owner != "ana" { |
| + t.Fatalf("owner = %q, want ana", e.Owner) |
| + } |
| + e = wantCode(t, f.shareFolder(t, 1002, "shop", packSite(t, map[string]string{"index.html": "ben"})), CodeOwned) |
| + if e.Owner != "ana" { |
| + t.Fatalf("folder owner = %q, want ana", e.Owner) |
| + } |
| + |
| + after, _ := f.r.Links.Get("shop") |
| + if after != before { |
| + t.Fatalf("link changed: %+v -> %+v", before, after) |
| + } |
| + if rowAfter := f.row(t, "shop"); rowAfter.Addr != rowBefore.Addr || rowAfter.Kind != rowBefore.Kind { |
| + t.Fatalf("row changed: %+v -> %+v", rowBefore, rowAfter) |
| + } |
| + if _, err := os.Stat(filepath.Join(f.spool, "shop")); err == nil { |
| + t.Fatal("refused folder upload left a spool dir") |
| + } |
| +} |
| + |
| +// A row at the host that the registrar did not write (an operator's own |
| +// `carlos add`) is not a free name. |
| +func TestShareRefusesForeignRegistryRow(t *testing.T) { |
| + f := newFixture(t) |
| + foreign := registry.Route{Host: "shop." + testDomain, Kind: "service", Addr: "127.0.0.1:1", App: "other", Status: "ready"} |
| + if err := f.reg.UpsertUnlessRootfs(foreign); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantCode(t, f.shareLive(t, 1001, "shop", 8080), CodeOwned) |
| + wantCode(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "x"})), CodeOwned) |
| + if rt := f.row(t, "shop"); rt.Addr != "127.0.0.1:1" || rt.App != "other" { |
| + t.Fatalf("foreign row overwritten: %+v", rt) |
| + } |
| + if _, ok := f.r.Links.Get("shop"); ok { |
| + t.Fatal("link written") |
| + } |
| +} |
| + |
| +// On a registry failure partway through, Links goes back to what it was. |
| +// A rootfs row landing at an owned host makes UpsertUnlessRootfs refuse |
| +// after Links has been written, so the rollback itself runs. |
| +func TestShareRollsBackLinksOnRegistryFailure(t *testing.T) { |
| + g := newFixture(t) |
| + wantOK(t, g.shareFolder(t, 1001, "mock", packSite(t, map[string]string{"index.html": "one"}))) |
| + k0, _ := g.r.Links.Get("mock") |
| + rootfs := registry.Route{Host: "mock." + testDomain, Kind: "instance", Runtime: registry.RuntimeRootfsV1, Hibernate: true, Status: "ready"} |
| + if err := g.reg.Upsert(rootfs); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec := g.shareLive(t, 1001, "mock", 6000); rec.Code != 500 { |
| + t.Fatalf("reshare live over a rootfs row = %d %s", rec.Code, rec.Body) |
| + } |
| + if k, _ := g.r.Links.Get("mock"); k != k0 { |
| + t.Fatalf("live reshare not rolled back: %+v -> %+v", k0, k) |
| + } |
| + if rec := g.shareFolder(t, 1001, "mock", packSite(t, map[string]string{"index.html": "two"})); rec.Code != 500 { |
| + t.Fatalf("reshare folder over a rootfs row = %d %s", rec.Code, rec.Body) |
| + } |
| + if k, _ := g.r.Links.Get("mock"); k != k0 { |
| + t.Fatalf("folder reshare not rolled back: %+v -> %+v", k0, k) |
| + } |
| + if got := readCurrent(t, g.spool, "mock", "index.html"); got != "one" { |
| + t.Fatalf("current after rollback = %q", got) |
| + } |
| + if names := dirNames(t, filepath.Join(g.spool, "mock")); !equal(names, sorted("current", k0.Snapshot)) { |
| + t.Fatalf("spool after rollback: %v", names) |
| + } |
| + if rt := g.row(t, "mock"); rt.Runtime != registry.RuntimeRootfsV1 { |
| + t.Fatalf("rootfs row touched: %+v", rt) |
| + } |
| + if again, err := OpenLinks(g.linksPath); err != nil { |
| + t.Fatal(err) |
| + } else if k, _ := again.Get("mock"); k != k0 { |
| + t.Fatalf("on disk: %+v", k) |
| + } |
| + |
| + // A registry that fails outright: nothing is written anywhere. |
| + f := newFixture(t) |
| + wantOK(t, f.shareLive(t, 1001, "shop", 5173)) |
| + before, _ := f.r.Links.Get("shop") |
| + f.reg.Close() |
| + |
| + rec := f.shareLive(t, 1001, "shop", 6000) |
| + if rec.Code < 500 { |
| + t.Fatalf("share with a closed registry = %d %s", rec.Code, rec.Body) |
| + } |
| + if after, _ := f.r.Links.Get("shop"); after != before { |
| + t.Fatalf("link not rolled back: %+v -> %+v", before, after) |
| + } |
| + rec = f.shareLive(t, 1001, "fresh", 6000) |
| + if rec.Code < 500 { |
| + t.Fatalf("fresh share with a closed registry = %d", rec.Code) |
| + } |
| + if _, ok := f.r.Links.Get("fresh"); ok { |
| + t.Fatal("fresh link not rolled back") |
| + } |
| + rec = f.shareFolder(t, 1001, "site", packSite(t, map[string]string{"index.html": "x"})) |
| + if rec.Code < 500 { |
| + t.Fatalf("folder share with a closed registry = %d", rec.Code) |
| + } |
| + if _, ok := f.r.Links.Get("site"); ok { |
| + t.Fatal("folder link not rolled back") |
| + } |
| + if _, err := os.Lstat(filepath.Join(f.spool, "site", "current")); err == nil { |
| + t.Fatal("folder current left behind") |
| + } |
| + // Reopen the store from disk: the file agrees with memory. |
| + again, err := OpenLinks(f.linksPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _ := again.Get("shop"); got.Port != 5173 { |
| + t.Fatalf("on disk port = %d", got.Port) |
| + } |
| +} |
| + |
| +func TestUnshareRefusesNonOwner(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "ana"}))) |
| + |
| + e := wantCode(t, f.unshare(t, 1002, "shop"), CodeNotYours) |
| + if e.Owner != "ana" { |
| + t.Fatalf("owner = %q", e.Owner) |
| + } |
| + if _, ok := f.r.Links.Get("shop"); !ok { |
| + t.Fatal("link removed") |
| + } |
| + if f.row(t, "shop") == nil { |
| + t.Fatal("row removed") |
| + } |
| + if got := readCurrent(t, f.spool, "shop", "index.html"); got != "ana" { |
| + t.Fatalf("current = %q", got) |
| + } |
| + wantCode(t, f.unshare(t, 1002, "nothing"), CodeUnknownLink) |
| +} |
| + |
| +func TestUnshareRemovesRowLinkAndSpool(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "ana"}))) |
| + wantOK(t, f.unshare(t, 1001, "shop")) |
| + if rt := f.row(t, "shop"); rt != nil { |
| + t.Fatalf("row left: %+v", rt) |
| + } |
| + if _, ok := f.r.Links.Get("shop"); ok { |
| + t.Fatal("link left") |
| + } |
| + if _, err := os.Lstat(filepath.Join(f.spool, "shop")); !os.IsNotExist(err) { |
| + t.Fatalf("spool dir left: %v", err) |
| + } |
| + // The name is free again, for anyone. |
| + wantOK(t, f.shareLive(t, 1002, "shop", 8080)) |
| +} |
| + |
| +func TestShareFolderSwapsCurrent(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "one"}))) |
| + k1, _ := f.r.Links.Get("shop") |
| + if got := readCurrent(t, f.spool, "shop", "index.html"); got != "one" { |
| + t.Fatalf("current = %q", got) |
| + } |
| + rt := f.row(t, "shop") |
| + if rt.Kind != "static" || rt.App != "shop" || rt.Status != "ready" || rt.Addr != "" || rt.Host != "shop."+testDomain { |
| + t.Fatalf("row = %+v", rt) |
| + } |
| + |
| + wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "two"}))) |
| + k2, _ := f.r.Links.Get("shop") |
| + if got := readCurrent(t, f.spool, "shop", "index.html"); got != "two" { |
| + t.Fatalf("current = %q", got) |
| + } |
| + if k2.Snapshot == k1.Snapshot { |
| + t.Fatal("snapshot did not change") |
| + } |
| + // R7: the tree before stays until the next swap, so a request that |
| + // resolved current just before the swap can finish reading. |
| + if names := dirNames(t, filepath.Join(f.spool, "shop")); !equal(names, sorted("current", k1.Snapshot, k2.Snapshot)) { |
| + t.Fatalf("after two uploads: %v", names) |
| + } |
| + |
| + wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "three"}))) |
| + k3, _ := f.r.Links.Get("shop") |
| + if got := readCurrent(t, f.spool, "shop", "index.html"); got != "three" { |
| + t.Fatalf("current = %q", got) |
| + } |
| + // The first tree is gone; only the one before current stays. |
| + if names := dirNames(t, filepath.Join(f.spool, "shop")); !equal(names, sorted("current", k2.Snapshot, k3.Snapshot)) { |
| + t.Fatalf("after three uploads: %v", names) |
| + } |
| + target, err := os.Readlink(filepath.Join(f.spool, "shop", "current")) |
| + if err != nil || target != k3.Snapshot { |
| + t.Fatalf("current -> %q, %v; want %q", target, err, k3.Snapshot) |
| + } |
| + if k3.Created != k1.Created || !k3.Updated.After(k1.Updated) && !k3.Updated.Equal(k1.Updated) { |
| + t.Fatalf("created %v -> %v, updated %v -> %v", k1.Created, k3.Created, k1.Updated, k3.Updated) |
| + } |
| +} |
| + |
| +// zeros streams n zero bytes and counts what was read, so a test can send an |
| +// over-cap body without allocating it. |
| +type zeros struct{ n, read int64 } |
| + |
| +func (z *zeros) Read(p []byte) (int, error) { |
| + if z.read >= z.n { |
| + return 0, io.EOF |
| + } |
| + k := int64(len(p)) |
| + if rest := z.n - z.read; k > rest { |
| + k = rest |
| + } |
| + clear(p[:k]) |
| + z.read += k |
| + return int(k), nil |
| +} |
| + |
| +func TestShareFolderOverCapRefused(t *testing.T) { |
| + f := newFixture(t) |
| + over := int64(MaxFolderBytes) + 1 |
| + z := &zeros{n: over} |
| + req := httptest.NewRequest("POST", "http://devbox/share/folder?name=shop", z) |
| + req.ContentLength = over |
| + req = req.WithContext(WithPeerUID(req.Context(), 1001)) |
| + rec := httptest.NewRecorder() |
| + f.r.Handler().ServeHTTP(rec, req) |
| + wantCode(t, rec, CodeFolderTooBig) |
| + if rec.Code != http.StatusRequestEntityTooLarge { |
| + t.Fatalf("status = %d", rec.Code) |
| + } |
| + if z.read > 1<<20 { |
| + t.Fatalf("read %d bytes of a body refused by its length", z.read) |
| + } |
| + if _, err := os.Stat(filepath.Join(f.spool, "shop")); err == nil { |
| + t.Fatal("extracted something") |
| + } |
| + if _, ok := f.r.Links.Get("shop"); ok { |
| + t.Fatal("link written") |
| + } |
| + |
| + // A body longer than it declared is cut at the cap by MaxBytesReader, |
| + // never buffered past it. (A real http.Server frames by Content-Length; |
| + // this drives the handler directly with a body that lies.) |
| + z = &zeros{n: over} |
| + req = httptest.NewRequest("POST", "http://devbox/share/folder?name=shop", z) |
| + req.ContentLength = 64 |
| + req = req.WithContext(WithPeerUID(req.Context(), 1001)) |
| + rec = httptest.NewRecorder() |
| + f.r.Handler().ServeHTTP(rec, req) |
| + if rec.Code == 200 { |
| + t.Fatal("a lying body was accepted") |
| + } |
| + if z.read > 1<<20 { |
| + t.Fatalf("read %d bytes of a body that declared 64", z.read) |
| + } |
| + |
| + // No declared length is refused before reading: the cap is decided up |
| + // front. |
| + z = &zeros{n: over} |
| + req = httptest.NewRequest("POST", "http://devbox/share/folder?name=shop", z) |
| + req.ContentLength = -1 |
| + req = req.WithContext(WithPeerUID(req.Context(), 1001)) |
| + rec = httptest.NewRecorder() |
| + f.r.Handler().ServeHTTP(rec, req) |
| + wantCode(t, rec, CodeBadRequest) |
| + if z.read != 0 { |
| + t.Fatalf("read %d bytes of a body with no length", z.read) |
| + } |
| + |
| + // A small archive that unpacks to more than the spool can ever hold is |
| + // too big, refused before anything is written (a gzip bomb). |
| + f.r.SpoolCap = 1 << 20 |
| + bomb := rawTar(t, &tar.Header{Name: "big.bin", Typeflag: tar.TypeReg, Mode: 0o644, Size: 2 << 20}) |
| + wantCode(t, f.shareFolder(t, 1001, "shop", bomb), CodeFolderTooBig) |
| + if _, err := os.Stat(filepath.Join(f.spool, "shop")); err == nil { |
| + t.Fatal("bomb extracted") |
| + } |
| +} |
| + |
| +func TestSpoolFullRefused(t *testing.T) { |
| + f := newFixture(t) |
| + f.r.SpoolCap = 3000 |
| + wantOK(t, f.shareFolder(t, 1001, "one", packSite(t, map[string]string{"a.bin": strings.Repeat("a", 2000)}))) |
| + wantCode(t, f.shareFolder(t, 1002, "two", packSite(t, map[string]string{"b.bin": strings.Repeat("b", 2000)})), CodeSpoolFull) |
| + if _, err := os.Stat(filepath.Join(f.spool, "two")); err == nil { |
| + if names := dirNames(t, filepath.Join(f.spool, "two")); len(names) != 0 { |
| + t.Fatalf("refused upload left %v", names) |
| + } |
| + } |
| + if _, ok := f.r.Links.Get("two"); ok { |
| + t.Fatal("link written") |
| + } |
| + if rt := f.row(t, "two"); rt != nil { |
| + t.Fatal("row written") |
| + } |
| + // Re-sharing a folder counts the kept previous tree too (R7): a.bin |
| + // twice already fills the 3000-byte cap. |
| + wantCode(t, f.shareFolder(t, 1001, "one", packSite(t, map[string]string{"a.bin": strings.Repeat("c", 2000)})), CodeSpoolFull) |
| + if got := readCurrent(t, f.spool, "one", "a.bin"); got[0] != 'a' { |
| + t.Fatal("current changed on a refused upload") |
| + } |
| +} |
| + |
| +func TestShareFolderRefusesEscapes(t *testing.T) { |
| + f := newFixture(t) |
| + outside := t.TempDir() |
| + cases := map[string][]byte{ |
| + "dotdot": rawTar(t, &tar.Header{Name: "../escape.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 1}), |
| + "absolute": rawTar(t, &tar.Header{Name: filepath.Join(outside, "abs.txt"), Typeflag: tar.TypeReg, Mode: 0o644, Size: 1}), |
| + "symlink": rawTar(t, &tar.Header{Name: "link", Typeflag: tar.TypeSymlink, Linkname: outside}), |
| + "hardlink": rawTar(t, &tar.Header{Name: "hard", Typeflag: tar.TypeLink, Linkname: "/etc/passwd"}), |
| + "notgzip": []byte("not an archive"), |
| + } |
| + for label, data := range cases { |
| + wantCode(t, f.shareFolder(t, 1001, "shop", data), CodeBadRequest) |
| + if _, ok := f.r.Links.Get("shop"); ok { |
| + t.Fatalf("%s: link written", label) |
| + } |
| + } |
| + if names := dirNames(t, outside); len(names) != 0 { |
| + t.Fatalf("wrote outside the spool: %v", names) |
| + } |
| + if _, err := os.Stat(filepath.Join(filepath.Dir(f.spool), "escape.txt")); err == nil { |
| + t.Fatal("dotdot escaped") |
| + } |
| +} |
| + |
| +// A symlink planted where a link's spool dir belongs is never written |
| +// through, and never followed on removal. |
| +func TestShareFolderRefusesPlantedSymlink(t *testing.T) { |
| + if runtime.GOOS == "windows" { |
| + t.Skip("symlinks") |
| + } |
| + f := newFixture(t) |
| + outside := t.TempDir() |
| + if err := os.MkdirAll(f.spool, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(outside, filepath.Join(f.spool, "shop")); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "x"})) |
| + if rec.Code == 200 { |
| + t.Fatal("shared through a planted symlink") |
| + } |
| + if names := dirNames(t, outside); len(names) != 0 { |
| + t.Fatalf("wrote through the symlink: %v", names) |
| + } |
| + if _, ok := f.r.Links.Get("shop"); ok { |
| + t.Fatal("link written") |
| + } |
| + |
| + // Removing a folder link whose dir was swapped for a symlink removes the |
| + // symlink, not what it names. |
| + if err := os.Remove(filepath.Join(f.spool, "shop")); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "x"}))) |
| + if err := os.WriteFile(filepath.Join(outside, "keep.txt"), []byte("keep"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.RemoveAll(filepath.Join(f.spool, "shop")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(outside, filepath.Join(f.spool, "shop")); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantOK(t, f.unshare(t, 1001, "shop")) |
| + if _, err := os.Stat(filepath.Join(outside, "keep.txt")); err != nil { |
| + t.Fatalf("unshare followed the symlink: %v", err) |
| + } |
| +} |
| + |
| +func TestReshareSwitchesKind(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareLive(t, 1001, "shop", 5173)) |
| + created, _ := f.r.Links.Get("shop") |
| + |
| + // live -> folder |
| + wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "mock"}))) |
| + rt := f.row(t, "shop") |
| + if rt.Kind != "static" || rt.Addr != "" || rt.App != "shop" || rt.Status != "ready" { |
| + t.Fatalf("row after live->folder = %+v", rt) |
| + } |
| + k, _ := f.r.Links.Get("shop") |
| + if k.Kind != KindFolder || k.Port != 0 || k.Snapshot == "" || k.OwnerUID != 1001 || !k.Created.Equal(created.Created) { |
| + t.Fatalf("link after live->folder = %+v", k) |
| + } |
| + if got := readCurrent(t, f.spool, "shop", "index.html"); got != "mock" { |
| + t.Fatalf("current = %q", got) |
| + } |
| + |
| + // folder -> live |
| + wantOK(t, f.shareLive(t, 1001, "shop", 3000)) |
| + rt = f.row(t, "shop") |
| + if rt.Kind != "service" || rt.Addr != "127.0.0.1:3000" || rt.App != "shop" || rt.Status != "ready" { |
| + t.Fatalf("row after folder->live = %+v", rt) |
| + } |
| + k, _ = f.r.Links.Get("shop") |
| + if k.Kind != KindLive || k.Port != 3000 || k.Snapshot != "" { |
| + t.Fatalf("link after folder->live = %+v", k) |
| + } |
| + if _, err := os.Lstat(filepath.Join(f.spool, "shop")); !os.IsNotExist(err) { |
| + t.Fatalf("spool dir left after folder->live: %v", err) |
| + } |
| +} |
| + |
| +func TestShareLiveBeforeServerUp(t *testing.T) { |
| + if AnswerTimeout != 300*time.Millisecond { |
| + t.Fatalf("dial timeout = %v, want 300ms", AnswerTimeout) |
| + } |
| + f := newFixture(t) |
| + port := closedPort(t) |
| + wantOK(t, f.shareLive(t, 1001, "shop", port)) |
| + got := f.list(t, 1002) // any local caller may list |
| + if len(got) != 1 || got[0].Name != "shop" || got[0].Answering { |
| + t.Fatalf("list before the server = %+v", got) |
| + } |
| + if got[0].Target != fmt.Sprintf("127.0.0.1:%d", port) || got[0].Kind != KindLive || got[0].Owner != "ana" { |
| + t.Fatalf("entry = %+v", got[0]) |
| + } |
| + if got[0].Host != "shop."+testDomain { |
| + t.Fatalf("host = %q", got[0].Host) |
| + } |
| + |
| + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) |
| + if err != nil { |
| + t.Skipf("port %d was taken in between: %v", port, err) |
| + } |
| + defer ln.Close() |
| + if got := f.list(t, 1002); len(got) != 1 || !got[0].Answering { |
| + t.Fatalf("list after the server = %+v", got) |
| + } |
| +} |
| + |
| +// The dials run at once, so many silent ports cost one timeout, not many. |
| +// The dial is swapped for one that takes the whole timeout, as a filtered |
| +// port would; loopback refusals are too quick to tell serial from parallel. |
| +func TestListDialsConcurrently(t *testing.T) { |
| + f := newFixture(t) |
| + for i := 0; i < 8; i++ { |
| + wantOK(t, f.shareLive(t, 1001, fmt.Sprintf("app%d", i), closedPort(t))) |
| + } |
| + dialAnswer = func(context.Context, int) bool { time.Sleep(AnswerTimeout); return false } |
| + t.Cleanup(func() { dialAnswer = answering }) |
| + start := time.Now() |
| + got := f.list(t, 1001) |
| + if len(got) != 8 { |
| + t.Fatalf("list = %d entries", len(got)) |
| + } |
| + if d := time.Since(start); d > 4*AnswerTimeout { |
| + t.Fatalf("list took %v", d) |
| + } |
| +} |
| + |
| +func TestListShowsUnknownOwnerAsUID(t *testing.T) { |
| + f := newFixture(t) |
| + f.r.LookupUser = func(uint32) string { return "" } |
| + wantOK(t, f.shareLive(t, 1003, "shop", closedPort(t))) |
| + got := f.list(t, 1001) |
| + if len(got) != 1 || got[0].Owner != "uid 1003" || got[0].OwnerUID != 1003 { |
| + t.Fatalf("list = %+v", got) |
| + } |
| + e := wantCode(t, f.shareLive(t, 1001, "shop", 8080), CodeOwned) |
| + if e.Owner != "uid 1003" { |
| + t.Fatalf("owned owner = %q", e.Owner) |
| + } |
| + // A nil LookupUser behaves the same. |
| + f.r.LookupUser = nil |
| + if got := f.list(t, 1001); got[0].Owner != "uid 1003" { |
| + t.Fatalf("nil lookup owner = %q", got[0].Owner) |
| + } |
| +} |
| + |
| +func TestRegistrarRestartKeepsLinks(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareLive(t, 1001, "live", closedPort(t))) |
| + wantOK(t, f.shareFolder(t, 1002, "mock", packSite(t, map[string]string{"index.html": "kept"}))) |
| + before := f.list(t, 1001) |
| + rowsBefore, err := f.reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + links, err := OpenLinks(f.linksPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fresh := &Registrar{Reg: f.reg, Links: links, Domain: testDomain, SpoolRoot: f.spool, SpoolCap: 5 << 30, LookupUser: f.r.LookupUser} |
| + f.r = fresh |
| + after := f.list(t, 1001) |
| + if len(after) != len(before) { |
| + t.Fatalf("list %+v -> %+v", before, after) |
| + } |
| + for i := range before { |
| + b, a := before[i], after[i] |
| + if b.Name != a.Name || b.Owner != a.Owner || b.OwnerUID != a.OwnerUID || b.Kind != a.Kind || b.Target != a.Target || !b.Created.Equal(a.Created) || !b.Updated.Equal(a.Updated) { |
| + t.Fatalf("entry %d: %+v -> %+v", i, b, a) |
| + } |
| + } |
| + rowsAfter, err := f.reg.List() |
| + if err != nil || len(rowsAfter) != len(rowsBefore) { |
| + t.Fatalf("rows %d -> %d (%v)", len(rowsBefore), len(rowsAfter), err) |
| + } |
| + |
| + // The folder still serves through the edge's local-static handler. |
| + e, err := edge.New(f.reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + edge.WithLocalStatic(f.spool)(e) |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + req := httptest.NewRequest("GET", "http://mock."+testDomain+"/", nil) |
| + rec := httptest.NewRecorder() |
| + e.ServeHTTP(rec, req) |
| + if rec.Code != 200 || rec.Body.String() != "kept" { |
| + t.Fatalf("edge GET / = %d %q", rec.Code, rec.Body.String()) |
| + } |
| + |
| + // And the owner is still the owner. |
| + wantCode(t, f.unshare(t, 1001, "mock"), CodeNotYours) |
| + wantOK(t, f.unshare(t, 1002, "mock")) |
| +} |
| + |
| +// A request with no peer uid in its context is refused, whatever it asks. |
| +func TestRegistrarRefusesNoIdentity(t *testing.T) { |
| + f := newFixture(t) |
| + for _, c := range []struct{ method, path, body string }{ |
| + {"GET", "/list", ""}, |
| + {"POST", "/share/live", `{"name":"shop","port":8080}`}, |
| + {"POST", "/unshare", `{"name":"shop"}`}, |
| + {"POST", "/share/folder?name=shop", "x"}, |
| + } { |
| + req := httptest.NewRequest(c.method, "http://devbox"+c.path, strings.NewReader(c.body)) |
| + rec := httptest.NewRecorder() |
| + f.r.Handler().ServeHTTP(rec, req) |
| + wantCode(t, rec, CodeBadRequest) |
| + } |
| + // ConnContext on a conn it cannot read credentials from gives no |
| + // identity: never uid 0 or any other. |
| + a, b := net.Pipe() |
| + defer a.Close() |
| + defer b.Close() |
| + ctx := ConnContext(context.Background(), a) |
| + if _, ok := peerUIDFrom(ctx); ok { |
| + t.Fatal("a pipe conn got an identity") |
| + } |
| + req := httptest.NewRequest("GET", "http://devbox/list", nil).WithContext(ctx) |
| + rec := httptest.NewRecorder() |
| + f.r.Handler().ServeHTTP(rec, req) |
| + wantCode(t, rec, CodeBadRequest) |
| + if _, ok := f.r.Links.Get("shop"); ok { |
| + t.Fatal("link written") |
| + } |
| +} |
| + |
| +// The client cannot name itself: an owner or uid field in the body is |
| +// ignored. |
| +func TestRegistrarIgnoresClaimedIdentity(t *testing.T) { |
| + f := newFixture(t) |
| + body := `{"name":"shop","port":8080,"uid":1001,"ownerUID":1001,"owner":"ana"}` |
| + wantOK(t, f.do(t, 1002, "POST", "/share/live", strings.NewReader(body))) |
| + k, _ := f.r.Links.Get("shop") |
| + if k.OwnerUID != 1002 || k.OwnerName != "ben" { |
| + t.Fatalf("link = %+v", k) |
| + } |
| +} |
| + |
| +func TestRegistrarUnknownRoutes(t *testing.T) { |
| + f := newFixture(t) |
| + wantCode(t, f.do(t, 1001, "GET", "/nope", nil), CodeBadRequest) |
| + wantCode(t, f.do(t, 1001, "GET", "/share/live", nil), CodeBadRequest) |
| + wantCode(t, f.do(t, 1001, "POST", "/list", nil), CodeBadRequest) |
| + wantCode(t, f.do(t, 1001, "POST", "/share/live", strings.NewReader("{")), CodeBadRequest) |
| + wantCode(t, f.do(t, 1001, "POST", "/unshare", strings.NewReader(`{"name":`)), CodeBadRequest) |
| +} |
| + |
| +func equal(a, b []string) bool { |
| + if len(a) != len(b) { |
| + return false |
| + } |
| + for i := range a { |
| + if a[i] != b[i] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func sorted(s ...string) []string { |
| + sort.Strings(s) |
| + return s |
| +} |