Files

133 lines
4.0 KiB
Go

package container
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/moby/moby/client"
)
// fakeSandbox records the sandbox networks a pool creates and removes.
type fakeSandbox struct {
mu sync.Mutex
created []string
removed []string
}
func (f *fakeSandbox) Create(_ context.Context, name string) error {
f.mu.Lock()
defer f.mu.Unlock()
f.created = append(f.created, name)
return nil
}
func (f *fakeSandbox) Remove(_ context.Context, name string) error {
f.mu.Lock()
defer f.mu.Unlock()
f.removed = append(f.removed, name)
return nil
}
// TestTaskContainerRunsOnItsOwnSandboxNetwork guards the task container's
// network boundary and its cleanup: the container joins only its own sandbox
// network, never the daemon's, so the egress relay is all it can reach; and
// the network goes with the task, so a host never fills with leaked
// networks.
func TestTaskContainerRunsOnItsOwnSandboxNetwork(t *testing.T) {
const daemonNetwork = "daemon-net"
tests := []struct {
name string
failStart bool
}{
{name: "released task"},
{name: "container that fails to start", failStart: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var (
mu sync.Mutex
attached []string
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/create"):
var req struct {
HostConfig struct {
NetworkMode string `json:"NetworkMode"`
} `json:"HostConfig"`
NetworkingConfig struct {
EndpointsConfig map[string]any `json:"EndpointsConfig"`
} `json:"NetworkingConfig"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
t.Error(err)
}
mu.Lock()
attached = append(attached, req.HostConfig.NetworkMode)
for name := range req.NetworkingConfig.EndpointsConfig {
attached = append(attached, name)
}
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"Id":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}`))
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/start"):
if tt.failStart {
http.Error(w, `{"message":"start failed"}`, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/wait"):
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"StatusCode":0}`))
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/stop"),
r.Method == http.MethodDelete:
w.WriteHeader(http.StatusNoContent)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
cli, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.54"))
if err != nil {
t.Fatal(err)
}
defer func() { _ = cli.Close() }()
sandbox := &fakeSandbox{}
p := &Pool{
cli: cli,
cfg: Config{Instance: "archie", Network: daemonNetwork},
sandbox: sandbox,
network: daemonNetwork,
log: slog.New(slog.DiscardHandler),
}
ctr, err := p.Acquire(t.Context(), "agent:test", nil, nil)
if tt.failStart != (err != nil) {
t.Fatalf("Acquire error = %v, want failure %t", err, tt.failStart)
}
p.Release(t.Context(), ctr)
mu.Lock()
defer mu.Unlock()
sandbox.mu.Lock()
defer sandbox.mu.Unlock()
if len(sandbox.created) != 1 {
t.Fatalf("sandbox networks created = %v, want exactly one for the task", sandbox.created)
}
if want := sandbox.created[:1]; !slices.Equal(attached, want) {
t.Fatalf("container attached to %v, want only its sandbox network %v", attached, want)
}
if !slices.Equal(sandbox.removed, sandbox.created) {
t.Fatalf("sandbox networks removed = %v, want %v removed with the task", sandbox.removed, sandbox.created)
}
})
}
}