mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 16:27:33 -10:00
A VM's proxy runs as two processes, as design.md's "The proxy's broker"
says: devvm _proxy, the broker, which keeps what only the host should
do, and devvm _proxy-child, which reads the VM's network and can be
confined by the follow-ups.
- wire.go: the protocol over one socketpair (close-on-exec from the
start: SOCK_CLOEXEC on Linux, ForkLock elsewhere), length-prefixed JSON
frames of at most 2 MiB, unknown fields refused, bytes as base64, one
descriptor on a frame's first bytes (SCM_RIGHTS, MSG_CTRUNC breaks the
rules), wire types for every secret (redact.Secret at once).
- broker.go: newBroker, the start (handshake: version 1 and each side's
executable's SHA-256, within 4 s), the answers (value through lookups,
kept 30 s or 5 min, a failure 5 s, dropped when the bindings change;
file by number; link connected by the broker and passed as a
descriptor; token exchanged by the broker), each by something in its
own config, with caps 1/8/4/256; live: the lifeline closes the socket
and kills the child 6 s later, SIGTERM stops it within a second, a
child that ends ends the broker, a rule broken stops the child.
- child.go: the start (startOf), the child's server (newChildServer),
the broker as hostSide over the socket (brokerClient), runChildOn;
ready only after it reads the host's addresses (kept: the last good
read), roots and time zone loaded first.
- process.go: Main(ctx, ...) and ChildMain; the child spawned with
/proc/self/exe on Linux, PR_SET_PDEATHSIG from a locked thread
(daemon.Cmd.DieWithThread), descriptors 3 and 4, and TZ, SSL_CERT_*
and GODEBUG with updatemaxprocs=0 alone; run/proxy-child.pid and
run/proxy.confined ("none" until the follow-ups); KeepLogs in the
broker. ChildMain refuses to start unless descriptors 3 and 4 are a
unix socket and an IP one (checkInherited): run by hand, without
them, those numbers can be the Go runtime's own, which closing
crashed it (signal_recv: inconsistent state).
- capture.go: a captured token request goes to the broker
(captureToken, exchanger), so a login's real tokens never enter the
child; an error reply passes up to 1 MiB, longer gets 502.
- watched.go: the child stats each changing file and asks the broker
for it once it changed, keeping the stamp of what the broker read.
- rotate.go: proxy.log rotated by both through its descriptor, under a
lock of a description of its own; OpenLog opens a log never through a
link, one link, yours, replacing what a child left in its place.
- nixcache.go: the trim and its count through a safefile.Root, nar/
only as a folder, links deleted as themselves; reads never through a
link; the lock tried for 5 s (ErrNixLocked, nix_cache_locked).
- daemon: Cmd.Err, Files, Env, DieWithThread; Handle.Kill, Exit;
WritePID.
- netpolicy: Proxy.Stop also stops a child that outlived its broker
(run/proxy-child.pid, _proxy-child -for); proxy.log opened with
OpenLog; a refused launch keeps a running VM only while both run.
devvm network log and lock read the event log through safefile.
- vm, vmssh, vmlog: links.log and ports.log opened with OpenLog, read
through safefile, trimmed only as a regular file with one link.
- backend: the build proxy's logs in a logs/ folder of their own.
- cli: _proxy-child; _proxy waits for its child on a signal
(StopsItsOwn); the child reads none of devvm's folders (no
makePrivate); ui.Files.
- Tests: FuzzBrokerFrames, the frames' rules, the handshake and the
pair's end in synctest bubbles, the caps, the broker naming its own
alone, the client over a real socketpair with a passed descriptor,
ChildMain, TestInheritedSocket and proxy.txtar's child run by hand,
the frozen 0.1.0 configs starting a broker and child,
two writers rotating once, planted links, FIFOs and hard links; the
testscript runner stops _proxy-child too; e2e: broker and child, their
arguments, descriptors and environment, stop, SIGKILL either, planted
files in the logs folder and the Nix cache, build proxies gone.
- Review fixes: the lifeline closes the socket and starts the kill's
timer before logging; every log lock (proxy.log's, the event log's
rotation) is tried without blocking for 200 ms (flockWithin, which the
Nix lock shares), then written without or the rotation skipped; a
copied log's rotation streams at most twice its limit from a line's
start (copyFrom, copyAtomic); a reply too long to send goes as
too_long; kept token headers capped at 1 KiB; the child gives up on a
request whose context ended, dropping its late reply and holding its
slot until then; a write deadline on the start frame; errors reach the
child as codes (not_found, refused, busy, too_long, failed), their
text in the broker's log; FuzzFrameStreams, and FuzzBrokerFrames
writes from a goroutine; nix_cache_locked links to How it works.
- Docs: processes, network, overview, design (with threat rows for the
logs' locks and a log made huge), troubleshooting, the proxy's
README, structure, testing; CHANGELOG.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
439 lines
12 KiB
Go
439 lines
12 KiB
Go
package netpolicy
|
|
|
|
import (
|
|
"bufio"
|
|
"cmp"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"text/tabwriter"
|
|
"time"
|
|
|
|
"github.com/devvmhq/devvm/internal/msg"
|
|
"github.com/devvmhq/devvm/internal/paths"
|
|
"github.com/devvmhq/devvm/internal/proxy"
|
|
"github.com/devvmhq/devvm/internal/safefile"
|
|
"github.com/devvmhq/devvm/internal/vmname"
|
|
)
|
|
|
|
// Log is a VM's event log, as devvm network log shows it. NewLog sets every
|
|
// field; tests change them.
|
|
type Log struct {
|
|
Path string
|
|
// Tick is how often a followed log is read for new events.
|
|
Tick time.Duration
|
|
}
|
|
|
|
// NewLog returns vm's event log (paths.VM.EventLog).
|
|
func NewLog(d paths.Dirs, vm vmname.VM) *Log {
|
|
return &Log{Path: d.VM(vm).EventLog(), Tick: 250 * time.Millisecond}
|
|
}
|
|
|
|
// openLog opens the event log at path to read, as a file a VM can swap:
|
|
// its proxy's child writes the folder it's in, so it's opened never
|
|
// through a link and without waiting on a FIFO, and only a regular file
|
|
// with one link (safefile).
|
|
func openLog(path string) (*os.File, error) {
|
|
f, err := safefile.Open(path, safefile.Opts{OneLink: true})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return f.File, nil
|
|
}
|
|
|
|
// Old is the log's previous file, which the proxy renamed it to when it
|
|
// rotated it: its older events.
|
|
func (l *Log) Old() string { return l.Path + ".1" }
|
|
|
|
// Write writes the log's last n events to w, one line each (FormatEvent),
|
|
// the previous file's (Old) first. With follow it then writes each new
|
|
// one, until ctx ends, and goes on in the new log when the proxy rotates
|
|
// it. Lines that aren't events are skipped.
|
|
func (l *Log) Write(ctx context.Context, w io.Writer, n int, follow bool) error {
|
|
f, err := openLog(l.Path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
var last []string
|
|
keep := func(l string) {
|
|
if s, ok := FormatEvent(l); ok && n > 0 {
|
|
if len(last) == n {
|
|
last = last[1:]
|
|
}
|
|
last = append(last, s)
|
|
}
|
|
}
|
|
// The log is open first, so a rotation now leaves it as Old: read once.
|
|
if err := l.readOld(f, keep); err != nil {
|
|
return err
|
|
}
|
|
r := bufio.NewReader(f)
|
|
var read int64
|
|
partial, err := readLines(r, &read, keep)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !follow {
|
|
keep(partial)
|
|
}
|
|
for _, s := range last {
|
|
if _, err := fmt.Fprintln(w, s); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if !follow {
|
|
return nil
|
|
}
|
|
fl := follower{l: l, f: f, r: r, read: read, partial: partial, w: w}
|
|
defer func() { _ = fl.f.Close() }()
|
|
t := time.NewTicker(l.Tick)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil
|
|
case <-t.C:
|
|
}
|
|
if err := fl.next(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
// Event is one event of a VM's network log, as its proxy wrote it.
|
|
type Event = proxy.Event
|
|
|
|
// Events returns the log's last n events, the previous file's (Old)
|
|
// first. Lines that aren't events are skipped.
|
|
func (l *Log) Events(n int) ([]Event, error) {
|
|
var last []Event
|
|
err := l.each(func(line string) {
|
|
var e Event
|
|
if json.Unmarshal([]byte(line), &e) != nil || e.Event == "" || e.Event == learnEvent || n <= 0 {
|
|
return
|
|
}
|
|
if len(last) == n {
|
|
last = last[1:]
|
|
}
|
|
last = append(last, e)
|
|
})
|
|
return last, err
|
|
}
|
|
|
|
// each calls line for each line of the log, the previous file's (Old)
|
|
// first, and for what follows its last newline.
|
|
func (l *Log) each(line func(string)) error {
|
|
f, err := openLog(l.Path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
if err := l.readOld(f, line); err != nil {
|
|
return err
|
|
}
|
|
var read int64
|
|
rest, err := readLines(bufio.NewReader(f), &read, line)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
line(rest)
|
|
return nil
|
|
}
|
|
|
|
// readOld calls line for each line of Old, unless it's cur, the log
|
|
// already open.
|
|
func (l *Log) readOld(cur *os.File, line func(string)) error {
|
|
old, err := openLog(l.Old())
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return nil
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = old.Close() }()
|
|
if a, err := old.Stat(); err == nil {
|
|
if b, err := cur.Stat(); err == nil && os.SameFile(a, b) {
|
|
return nil
|
|
}
|
|
}
|
|
var read int64
|
|
rest, err := readLines(bufio.NewReader(old), &read, line)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
line(rest)
|
|
return nil
|
|
}
|
|
|
|
// follower writes each new event of a followed log.
|
|
type follower struct {
|
|
l *Log
|
|
f *os.File
|
|
r *bufio.Reader
|
|
read int64
|
|
partial string // a line still being written
|
|
w io.Writer
|
|
}
|
|
|
|
// next writes the events written since the last call. A log made shorter
|
|
// (emptied) is read again from its start. A log the proxy rotated is read
|
|
// to its end, then the new one from its start.
|
|
func (fl *follower) next() error {
|
|
if fi, err := fl.f.Stat(); err == nil && fi.Size() < fl.read {
|
|
if _, err := fl.f.Seek(0, io.SeekStart); err != nil {
|
|
return err
|
|
}
|
|
fl.r.Reset(fl.f)
|
|
fl.read, fl.partial = 0, ""
|
|
}
|
|
// Whether the log was renamed, checked before its end is read, so no
|
|
// line written to it after is missed.
|
|
nf := fl.rotated()
|
|
if err := fl.drain(); err != nil {
|
|
if nf != nil {
|
|
_ = nf.Close()
|
|
}
|
|
return err
|
|
}
|
|
if nf == nil {
|
|
return nil
|
|
}
|
|
_ = fl.f.Close()
|
|
fl.f, fl.read, fl.partial = nf, 0, ""
|
|
fl.r.Reset(nf)
|
|
return fl.drain()
|
|
}
|
|
|
|
// rotated returns the log's new file, open, when the proxy has renamed
|
|
// the one being read.
|
|
func (fl *follower) rotated() *os.File {
|
|
cur, err := fl.f.Stat()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
nf, err := openLog(fl.l.Path)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if fi, err := nf.Stat(); err != nil || os.SameFile(cur, fi) {
|
|
_ = nf.Close()
|
|
return nil
|
|
}
|
|
return nf
|
|
}
|
|
|
|
// drain writes the whole lines the log has after what was read.
|
|
func (fl *follower) drain() error {
|
|
var werr error
|
|
rest, err := readLines(fl.r, &fl.read, func(l string) {
|
|
if s, ok := FormatEvent(fl.partial + l); ok && werr == nil {
|
|
_, werr = fmt.Fprintln(fl.w, s)
|
|
}
|
|
fl.partial = ""
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if werr != nil {
|
|
return werr
|
|
}
|
|
fl.partial += rest
|
|
return nil
|
|
}
|
|
|
|
// readLines calls line for each whole line r has (without its newline),
|
|
// adding the bytes read to *read, and returns what's after the last
|
|
// newline: a line still being written.
|
|
func readLines(r *bufio.Reader, read *int64, line func(string)) (string, error) {
|
|
for {
|
|
s, err := r.ReadString('\n')
|
|
*read += int64(len(s))
|
|
if errors.Is(err, io.EOF) {
|
|
return s, nil
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
line(strings.TrimSuffix(s, "\n"))
|
|
}
|
|
}
|
|
|
|
// FormatEvent turns one line of an event log into what devvm network log shows:
|
|
// the time, allowed or BLOCKED, the host and port, and the rule that
|
|
// allowed it, the request, the tokens put in, or why it was blocked, after
|
|
// a blocked request's method and path. The
|
|
// VM chose the host and path: control characters are dropped. false for a
|
|
// line that isn't an event, and for devvm's mark of a VM starting to learn
|
|
// (MarkLearning), which is no connection.
|
|
func FormatEvent(line string) (string, bool) {
|
|
var e proxy.Event
|
|
if json.Unmarshal([]byte(line), &e) != nil || e.Event == "" || e.Event == learnEvent {
|
|
return "", false
|
|
}
|
|
what, d := "allowed", "rule "+e.Rule
|
|
switch e.Event {
|
|
case "blocked":
|
|
what, d = "BLOCKED", e.Reason
|
|
if e.Method != "" && e.Method != http.MethodConnect && e.Path != "" { // a request, not a tunnel
|
|
d = e.Method + " " + e.Path + ": " + e.Reason
|
|
}
|
|
if e.Quiet { // a host devvm leaves out on purpose, such as a tool's telemetry
|
|
d += ", quiet"
|
|
}
|
|
case "forward":
|
|
d = e.Method + " " + e.Path
|
|
if e.Rule != "" { // the rule that let it through, by method and path
|
|
d += ", rule " + e.Rule
|
|
}
|
|
case "intercept":
|
|
d += ", decrypted"
|
|
case "login": // an agent's login, captured at its token endpoint
|
|
what, d = "login", e.Login+"'s login saved: "+e.Method+" "+e.Path
|
|
case "nix-cache": // the shared Nix cache: a hit, fetched, or why not
|
|
what, d = "cache", e.Method+" "+e.Path+": "+e.Reason
|
|
case "link", "link_refused", "link_target_stopped", "link_limit": // devvm _links's
|
|
what, d = linkEvent(e)
|
|
}
|
|
if len(e.Secrets) > 0 {
|
|
d += ", token: " + strings.Join(e.Secrets, ",")
|
|
}
|
|
if e.Upstream != "" {
|
|
d += ", through " + e.Upstream
|
|
}
|
|
if e.Via == proxy.ViaDNS {
|
|
d += ", without proxy settings"
|
|
}
|
|
return fmt.Sprintf("%s %-7s %s %s", msg.OneLine(e.Time), what, hostPort(e.Host, e.Port), msg.OneLine(d)), true
|
|
}
|
|
|
|
// linkEvent is what devvm network log shows of a link's event, whose host
|
|
// is the link's name: carried to its target, or refused and why.
|
|
func linkEvent(e proxy.Event) (what, d string) {
|
|
switch e.Event {
|
|
case "link":
|
|
return "link", "to " + e.Target.String()
|
|
case "link_target_stopped":
|
|
return "REFUSED", "to " + e.Target.String() + ": it isn't running"
|
|
case "link_limit":
|
|
return "REFUSED", e.Reason + " connections carried already"
|
|
}
|
|
return "REFUSED", "to " + e.Target.String() + ": " + e.Reason
|
|
}
|
|
|
|
// AppendEvent adds an event to a VM's event log (EventLog), the user's
|
|
// alone, with the time and the VM's name: devvm _links's, beside its
|
|
// proxy's. It's written through the proxy's own writer, which rotates
|
|
// the log by the proxy's rule, so an open VM keeps two
|
|
// at most too, and the proxy goes on writing to the new log.
|
|
func AppendEvent(path string, vm vmname.VM, e Event) error {
|
|
e.Time, e.VM = time.Now().UTC().Format(time.RFC3339), vm
|
|
b, _ := json.Marshal(e)
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
|
return err
|
|
}
|
|
w, err := proxy.OpenEventLog(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = w.Write(append(b, '\n'))
|
|
if cerr := w.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
return err
|
|
}
|
|
|
|
func hostPort(host string, port int) string {
|
|
return net.JoinHostPort(msg.OneLine(host), strconv.Itoa(port))
|
|
}
|
|
|
|
// Block is a host and port a VM's proxy blocked, as devvm network log
|
|
// --blocked lists it.
|
|
type Block struct {
|
|
Last string // when it was last blocked
|
|
Count int // how many times
|
|
Host string
|
|
Port int
|
|
// Allow is the rule devvm network allow takes to allow it; "" for a
|
|
// request refused whatever the allowlist says, a host the policy
|
|
// doesn't take, or a quiet one, which devvm doesn't suggest.
|
|
Allow string
|
|
// Quiet is a host a built-in policy marks quiet (proxy.Event.Quiet),
|
|
// such as a tool's telemetry: devvm leaves it out on purpose.
|
|
Quiet bool
|
|
}
|
|
|
|
// Blocks returns the log's blocks (Old's too), one per host and port, by
|
|
// when each was last blocked.
|
|
func (l *Log) Blocks() ([]Block, error) {
|
|
type key struct {
|
|
host string
|
|
port int
|
|
refused bool
|
|
quiet bool // a quiet block and a plain one of the same host are rows of their own
|
|
}
|
|
rows := map[key]*Block{}
|
|
err := l.each(func(l string) {
|
|
var e proxy.Event
|
|
if json.Unmarshal([]byte(l), &e) != nil || e.Event != "blocked" {
|
|
return
|
|
}
|
|
k := key{e.Host, e.Port, e.Refused, e.Quiet}
|
|
r := rows[k]
|
|
if r == nil {
|
|
r = &Block{Host: e.Host, Port: e.Port, Quiet: e.Quiet}
|
|
if rule, ok := proxy.AllowRule(e.Host, e.Port); ok && !e.Refused && !e.Quiet {
|
|
r.Allow = rule
|
|
}
|
|
rows[k] = r
|
|
}
|
|
r.Count++
|
|
r.Last = e.Time
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sorted := make([]Block, 0, len(rows))
|
|
for _, r := range rows {
|
|
sorted = append(sorted, *r)
|
|
}
|
|
slices.SortFunc(sorted, func(a, b Block) int {
|
|
return cmp.Or(cmp.Compare(a.Last, b.Last), cmp.Compare(hostPort(a.Host, a.Port), hostPort(b.Host, b.Port)))
|
|
})
|
|
return sorted, nil
|
|
}
|
|
|
|
// WriteBlocked writes the log's blocks (Blocks) to w as a table, one row
|
|
// per host and port, by when it was last blocked: the last time, how many
|
|
// times, and the devvm network allow command that allows it. A request
|
|
// refused whatever the allowlist says, or a host the policy doesn't take,
|
|
// gets - instead: the command is meant to be pasted into a shell. The VM
|
|
// chose the host: control characters are dropped.
|
|
func (l *Log) WriteBlocked(w io.Writer) error {
|
|
blocks, err := l.Blocks()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
|
|
_, _ = fmt.Fprintln(tw, "LAST\tCOUNT\tHOST\tALLOW WITH")
|
|
for _, b := range blocks {
|
|
allow := "-"
|
|
switch {
|
|
case b.Allow != "":
|
|
allow = "devvm network allow " + b.Allow
|
|
case b.Quiet:
|
|
allow = "- (quiet)"
|
|
}
|
|
_, _ = fmt.Fprintf(tw, "%s\t%d\t%s\t%s\n", msg.OneLine(b.Last), b.Count, hostPort(b.Host, b.Port), allow)
|
|
}
|
|
return tw.Flush()
|
|
}
|