feat(egress): relay forwards the proxy, NATS and the State Store
A Kit task's worker shares the sandbox network with its harness, so it reaches NATS and the State Store through the relay like the harness reaches the proxy. archie-agent relay takes repeated -forward listen=target pairs, binds them all before serving so a port conflict fails at start, and stops every forward when one fails. RelayArgs builds the command from the fixed relay ports.
This commit is contained in:
6 files changed
+205
-36
No files matched your search
@@ -8,8 +8,10 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/agentworker"
|
||||
@@ -85,29 +87,46 @@ func natsConnectionSettings(flagURL string, getenv func(string) string) (url, to
|
||||
return url, getenv("NATS_TOKEN")
|
||||
}
|
||||
|
||||
type relayServer func(ctx context.Context, listen, target string) error
|
||||
type relayServer func(ctx context.Context, forwards map[string]string) error
|
||||
|
||||
// runRelay is the sandbox egress relay: the container on both a sandbox's
|
||||
// isolated network and the host-reachable one, forwarding to the proxy.
|
||||
// isolated network and the host-reachable one, forwarding a fixed set of
|
||||
// ports to the proxy, NATS and the State Store.
|
||||
func runRelay(args []string, stderr io.Writer, serve relayServer) int {
|
||||
flags := flag.NewFlagSet("archie-agent relay", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
listen := flags.String("listen", ":3128", "address sandbox containers connect to")
|
||||
target := flags.String("to", "", "the egress proxy address every connection is forwarded to")
|
||||
forwards := map[string]string{}
|
||||
flags.Func("forward", "listen=target: forward connections on listen to target (repeatable)", func(v string) error {
|
||||
listen, target, ok := strings.Cut(v, "=")
|
||||
if !ok || listen == "" || target == "" {
|
||||
return fmt.Errorf("%q is not listen=target", v)
|
||||
}
|
||||
if _, _, err := net.SplitHostPort(listen); err != nil {
|
||||
return fmt.Errorf("listen address %q: %w", listen, err)
|
||||
}
|
||||
if _, _, err := net.SplitHostPort(target); err != nil {
|
||||
return fmt.Errorf("target %q: %w", target, err)
|
||||
}
|
||||
if _, dup := forwards[listen]; dup {
|
||||
return fmt.Errorf("listen address %q is forwarded twice", listen)
|
||||
}
|
||||
forwards[listen] = target
|
||||
return nil
|
||||
})
|
||||
if err := flags.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return 0
|
||||
}
|
||||
return 2
|
||||
}
|
||||
if *target == "" {
|
||||
fmt.Fprintln(stderr, "error: -to is required")
|
||||
if len(forwards) == 0 {
|
||||
fmt.Fprintln(stderr, "error: at least one -forward is required")
|
||||
flags.Usage()
|
||||
return 1
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := serve(ctx, *listen, *target); err != nil {
|
||||
if err := serve(ctx, forwards); err != nil {
|
||||
fmt.Fprintln(stderr, "error:", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -3,33 +3,44 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"maps"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunRelay(t *testing.T) {
|
||||
t.Run("-to is required", func(t *testing.T) {
|
||||
var stderr bytes.Buffer
|
||||
called := false
|
||||
serve := func(context.Context, string, string) error { called = true; return nil }
|
||||
if code := runRelay([]string{"-listen", "127.0.0.1:0"}, &stderr, serve); code != 1 {
|
||||
t.Fatalf("exit %d, want 1", code)
|
||||
}
|
||||
if called || !strings.Contains(stderr.String(), "-to is required") {
|
||||
t.Fatalf("served=%v stderr=%q", called, stderr.String())
|
||||
}
|
||||
})
|
||||
t.Run("serves the named target on the listen address", func(t *testing.T) {
|
||||
var gotTarget, gotAddr string
|
||||
serve := func(_ context.Context, listen, target string) error {
|
||||
gotTarget, gotAddr = target, listen
|
||||
noServe := func(t *testing.T) relayServer {
|
||||
return func(context.Context, map[string]string) error {
|
||||
t.Error("the relay served despite a usage error")
|
||||
return nil
|
||||
}
|
||||
if code := runRelay([]string{"-listen", "127.0.0.1:0", "-to", "172.17.0.1:3129"}, &bytes.Buffer{}, serve); code != 0 {
|
||||
}
|
||||
for name, args := range map[string][]string{
|
||||
"no forward": {},
|
||||
"a forward with no =": {"-forward", "127.0.0.1:0"},
|
||||
"a forward with no port": {"-forward", "=172.17.0.1:3129"},
|
||||
"one listen address used": {"-forward", ":3128=a:1", "-forward", ":3128=b:2"},
|
||||
} {
|
||||
t.Run(name+" is a usage error", func(t *testing.T) {
|
||||
var stderr bytes.Buffer
|
||||
if code := runRelay(args, &stderr, noServe(t)); code == 0 {
|
||||
t.Fatalf("exit 0, want a usage error; stderr %q", stderr.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("every forward is served", func(t *testing.T) {
|
||||
var got map[string]string
|
||||
serve := func(_ context.Context, forwards map[string]string) error {
|
||||
got = forwards
|
||||
return nil
|
||||
}
|
||||
args := []string{"-forward", ":3128=172.17.0.1:3129", "-forward", ":4222=172.17.0.1:4222"}
|
||||
if code := runRelay(args, &bytes.Buffer{}, serve); code != 0 {
|
||||
t.Fatalf("exit %d, want 0", code)
|
||||
}
|
||||
if gotTarget != "172.17.0.1:3129" || gotAddr != "127.0.0.1:0" {
|
||||
t.Fatalf("served %q on %q", gotTarget, gotAddr)
|
||||
want := map[string]string{":3128": "172.17.0.1:3129", ":4222": "172.17.0.1:4222"}
|
||||
if !maps.Equal(got, want) {
|
||||
t.Fatalf("served %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -37,7 +48,7 @@ func TestRunRelay(t *testing.T) {
|
||||
func TestRelaySubcommandRoutes(t *testing.T) {
|
||||
var stderr bytes.Buffer
|
||||
code := runCommand([]string{"relay"}, func(string) string { return "" }, &stderr, nil)
|
||||
if code != 1 || !strings.Contains(stderr.String(), "-to is required") {
|
||||
if code != 1 || !strings.Contains(stderr.String(), "-forward") {
|
||||
t.Fatalf("relay subcommand exit %d stderr %q; want the relay's own usage error", code, stderr.String())
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,50 @@ package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress/relay"
|
||||
)
|
||||
|
||||
// RunRelay listens on listen and forwards every connection to target, the
|
||||
// egress proxy, until ctx is cancelled.
|
||||
func RunRelay(ctx context.Context, listen, target string) error {
|
||||
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", listen)
|
||||
if err != nil {
|
||||
return err
|
||||
// RunRelay forwards each listen address to its target until ctx is
|
||||
// cancelled. Every listener binds before any serves, so a port conflict
|
||||
// fails the relay at start; one forward failing later stops them all.
|
||||
func RunRelay(ctx context.Context, forwards map[string]string) error {
|
||||
listeners := make(map[string]net.Listener, len(forwards))
|
||||
closeAll := func() {
|
||||
for _, ln := range listeners {
|
||||
_ = ln.Close()
|
||||
}
|
||||
}
|
||||
return relay.Serve(ctx, ln, target)
|
||||
for listen := range forwards {
|
||||
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", listen)
|
||||
if err != nil {
|
||||
closeAll()
|
||||
return fmt.Errorf("relay listen %s: %w", listen, err)
|
||||
}
|
||||
listeners[listen] = ln
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
errs []error
|
||||
)
|
||||
for listen, ln := range listeners {
|
||||
target := forwards[listen]
|
||||
wg.Go(func() {
|
||||
if err := relay.Serve(ctx, ln, target); err != nil {
|
||||
mu.Lock()
|
||||
errs = append(errs, fmt.Errorf("relay %s -> %s: %w", listen, target, err))
|
||||
mu.Unlock()
|
||||
cancel()
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func echoTarget(t *testing.T, reply string) string {
|
||||
t.Helper()
|
||||
ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
go func() {
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(c, reply)
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
return ln.Addr().String()
|
||||
}
|
||||
|
||||
func freeAddr(t *testing.T) string {
|
||||
t.Helper()
|
||||
ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := ln.Addr().String()
|
||||
_ = ln.Close()
|
||||
return addr
|
||||
}
|
||||
|
||||
func TestRunRelayForwardsEachListenerToItsTarget(t *testing.T) {
|
||||
proxy, nats := freeAddr(t), freeAddr(t)
|
||||
forwards := map[string]string{proxy: echoTarget(t, "proxy"), nats: echoTarget(t, "nats")}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- RunRelay(ctx, forwards) }()
|
||||
|
||||
for listen, want := range map[string]string{proxy: "proxy", nats: "nats"} {
|
||||
var got []byte
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
c, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", listen)
|
||||
if err == nil {
|
||||
_ = c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
got, _ = io.ReadAll(c)
|
||||
_ = c.Close()
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("relay never listened on %s: %v", listen, err)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if string(got) != want {
|
||||
t.Fatalf("%s reached %q, want %q", listen, got, want)
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("RunRelay after cancel: %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("RunRelay did not stop on cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRelayFailsWhenAListenerCannotBind(t *testing.T) {
|
||||
taken, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer taken.Close()
|
||||
err = RunRelay(t.Context(), map[string]string{taken.Addr().String(): "127.0.0.1:1", freeAddr(t): "127.0.0.1:1"})
|
||||
if err == nil {
|
||||
t.Fatal("RunRelay started with a listener that could not bind")
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,12 @@ import (
|
||||
const (
|
||||
// RelayAlias is the name a sandbox container reaches its relay by.
|
||||
RelayAlias = "archie-egress"
|
||||
// RelayPort is the port the relay listens on inside sandbox networks.
|
||||
// RelayPort is the port the relay forwards to the egress proxy.
|
||||
RelayPort = 3128
|
||||
// RelayNATSPort and RelayStateStorePort are the ports the relay forwards
|
||||
// to NATS and the State Store, for the worker in a sandbox container.
|
||||
RelayNATSPort = 4222
|
||||
RelayStateStorePort = 50051
|
||||
|
||||
relayLabel = "archie-egress-relay"
|
||||
sandboxLabel = "archie-egress-sandbox"
|
||||
@@ -160,3 +164,16 @@ func ProxyEnv(token, caPath string) []string {
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// RelayArgs is archie-agent relay's arguments forwarding the relay's fixed
|
||||
// ports to the proxy, NATS and the State Store at their host-reachable
|
||||
// addresses. An empty address is not forwarded.
|
||||
func RelayArgs(proxy, nats, stateStore string) []string {
|
||||
args := []string{"relay"}
|
||||
for port, target := range map[int]string{RelayPort: proxy, RelayNATSPort: nats, RelayStateStorePort: stateStore} {
|
||||
if target != "" {
|
||||
args = append(args, "-forward", ":"+strconv.Itoa(port)+"="+target)
|
||||
}
|
||||
}
|
||||
return args
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -157,7 +156,7 @@ func TestSandboxNetworkReachesOnlyTheProxy(t *testing.T) {
|
||||
Name: name + "-relay",
|
||||
Image: probeImage,
|
||||
Entrypoint: []string{"/bin/archie-agent"},
|
||||
Cmd: []string{"relay", "-listen", ":" + strconv.Itoa(RelayPort), "-to", proxyAddr},
|
||||
Cmd: RelayArgs(proxyAddr, "", ""),
|
||||
Network: "bridge",
|
||||
Binds: []string{filepath.Join(bin, "archie-agent") + ":/bin/archie-agent:ro,z"},
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user