266 lines
11 KiB
Go
266 lines
11 KiB
Go
package server_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/netip"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/labd/internal/lxd/lxdfake"
|
|
"lincodex/labd/internal/pool"
|
|
"lincodex/labd/internal/server"
|
|
"lincodex/labd/internal/store"
|
|
"lincodex/labd/internal/template"
|
|
)
|
|
|
|
const (
|
|
serviceToken = "0123456789abcdef0123456789abcdef"
|
|
nodeMemory = 768 << 20
|
|
seedHex = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
|
|
)
|
|
|
|
type reachable struct{}
|
|
|
|
func (reachable) Probe(context.Context, netip.AddrPort) error { return nil }
|
|
|
|
func oneNodeTemplate() template.Template {
|
|
return template.Template{
|
|
ID: "ubuntu-dns", Version: 1,
|
|
Nodes: []template.Node{{Name: "srv", Kind: template.Ubuntu, Profile: "lincodex-lab-small", Source: "tpl-ubuntu/base", MemoryBytes: nodeMemory}},
|
|
Links: []template.Link{{Name: "lan", Nodes: []string{"srv"}}},
|
|
Render: func(template.Variant) (map[string]template.Bootstrap, error) {
|
|
return map[string]template.Bootstrap{}, nil
|
|
},
|
|
Check: func(context.Context, template.Variant, []template.NodeAccess) ([]template.Criterion, error) {
|
|
return []template.Criterion{{ID: "dns", Passed: true}, {ID: "zone", Passed: false}}, nil
|
|
},
|
|
}
|
|
}
|
|
|
|
// newServer starts the API with a real manager on the fake LXD; the budget
|
|
// fits two labs.
|
|
func newServer(t *testing.T, allowed string) (*httptest.Server, *pool.Manager) {
|
|
t.Helper()
|
|
registry, err := template.NewRegistry(oneNodeTemplate())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
states, err := store.New(filepath.Join(t.TempDir(), "labs.json"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
logger := slog.New(slog.DiscardHandler)
|
|
manager, err := pool.New(pool.Config{
|
|
MemoryBudgetBytes: 2 * nodeMemory, MaxLifetime: 2 * time.Hour, ProvisionTimeout: 5 * time.Second,
|
|
ProbeInterval: time.Millisecond, DeletedRetention: time.Hour, ConsoleTokenTTL: time.Minute, CheckTimeout: time.Second,
|
|
ManagementNetwork: "lxdbr-labmgmt", ManagementPrefix: netip.MustParsePrefix("10.81.0.0/24"),
|
|
ManagementHost: netip.MustParseAddr("10.81.0.1"), ManagementFirst: netip.MustParseAddr("10.81.0.16"),
|
|
}, lxdfake.New([]string{"tpl-ubuntu/base"}, "lxdbr-labmgmt"), states, registry, reachable{}, time.Now, logger)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := manager.Start(context.Background()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = manager.Close(context.Background()) }) // Test teardown.
|
|
handler := server.NewHandler(manager, manager.Ready, 30*time.Second, logger)
|
|
httpHandler, err := server.New(handler, server.Options{
|
|
Token: serviceToken, MaxRequestBytes: 64 << 10, AllowedClients: []netip.Prefix{netip.MustParsePrefix(allowed)},
|
|
}, logger)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
httpServer := httptest.NewServer(httpHandler)
|
|
t.Cleanup(httpServer.Close)
|
|
return httpServer, manager
|
|
}
|
|
|
|
// reply is the status and headers of a response whose body was read.
|
|
type reply struct {
|
|
StatusCode int
|
|
Header http.Header
|
|
}
|
|
|
|
func call(t *testing.T, base, method, path, token string, body any) (reply, map[string]any) {
|
|
t.Helper()
|
|
var reader io.Reader = http.NoBody
|
|
if body != nil {
|
|
encoded, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reader = bytes.NewReader(encoded)
|
|
}
|
|
request, err := http.NewRequestWithContext(context.Background(), method, base+path, reader)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if body != nil {
|
|
request.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if token != "" {
|
|
request.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
response, err := http.DefaultClient.Do(request)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = response.Body.Close() }()
|
|
var decoded map[string]any
|
|
_ = json.NewDecoder(response.Body).Decode(&decoded) // Some answers have no JSON body.
|
|
return reply{StatusCode: response.StatusCode, Header: response.Header}, decoded
|
|
}
|
|
|
|
func createBody(seed string) map[string]any {
|
|
return map[string]any{"template_id": "ubuntu-dns", "template_version": 1, "seed": seed, "ttl_seconds": 600}
|
|
}
|
|
|
|
func TestLabOperationsNeedTheServiceToken(t *testing.T) {
|
|
httpServer, _ := newServer(t, "127.0.0.0/8")
|
|
id := uuid.NewString()
|
|
for _, token := range []string{"", "wrong-token-wrong-token-wrong-token"} {
|
|
response, body := call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+id, token, createBody(seedHex))
|
|
if response.StatusCode != http.StatusUnauthorized || body["code"] != "unauthenticated" {
|
|
t.Fatalf("PUT with token %q = %d %v", token, response.StatusCode, body)
|
|
}
|
|
}
|
|
response, _ := call(t, httpServer.URL, http.MethodGet, "/healthz", "", nil)
|
|
if response.StatusCode != http.StatusOK {
|
|
t.Fatalf("healthz = %d", response.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestRequestsFromOtherNetworksAreRefused(t *testing.T) {
|
|
httpServer, _ := newServer(t, "172.29.79.0/24")
|
|
response, body := call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+uuid.NewString(), serviceToken, nil)
|
|
if response.StatusCode != http.StatusUnauthorized || body["code"] != "unauthenticated" {
|
|
t.Fatalf("GET from loopback = %d %v", response.StatusCode, body)
|
|
}
|
|
}
|
|
|
|
func TestCreateIsIdempotentAndTheExtraLabIsBusy(t *testing.T) {
|
|
httpServer, manager := newServer(t, "127.0.0.0/8")
|
|
first, second := uuid.NewString(), uuid.NewString()
|
|
|
|
response, body := call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+first, serviceToken, createBody(seedHex))
|
|
if response.StatusCode != http.StatusAccepted || body["state"] != "provisioning" {
|
|
t.Fatalf("first PUT = %d %v", response.StatusCode, body)
|
|
}
|
|
assertNoInfrastructure(t, body)
|
|
response, _ = call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+first, serviceToken, createBody(seedHex))
|
|
if response.StatusCode != http.StatusOK {
|
|
t.Fatalf("repeated PUT = %d", response.StatusCode)
|
|
}
|
|
response, body = call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+first, serviceToken, createBody(strings.Repeat("0", 63)+"1"))
|
|
if response.StatusCode != http.StatusUnprocessableEntity || body["code"] != "idempotency_key_reused" {
|
|
t.Fatalf("PUT with another seed = %d %v", response.StatusCode, body)
|
|
}
|
|
if response, _ = call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+second, serviceToken, createBody(seedHex)); response.StatusCode != http.StatusAccepted {
|
|
t.Fatalf("second lab = %d", response.StatusCode)
|
|
}
|
|
|
|
extra := uuid.NewString()
|
|
response, body = call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+extra, serviceToken, createBody(seedHex))
|
|
if response.StatusCode != http.StatusServiceUnavailable || body["code"] != "lab_pool_busy" || response.Header.Get("Retry-After") != "30" {
|
|
t.Fatalf("PUT beyond the budget = %d %v Retry-After %q", response.StatusCode, body, response.Header.Get("Retry-After"))
|
|
}
|
|
response, body = call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+extra, serviceToken, nil)
|
|
if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" {
|
|
t.Fatalf("a busy lab was stored: %d %v", response.StatusCode, body)
|
|
}
|
|
if _, count := manager.Usage(); count != 2 {
|
|
t.Fatalf("labs holding capacity = %d, want 2", count)
|
|
}
|
|
}
|
|
|
|
func TestReadyLabIssuesConsoleTokensAndChecks(t *testing.T) {
|
|
httpServer, manager := newServer(t, "127.0.0.0/8")
|
|
id := uuid.New()
|
|
if response, _ := call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+id.String(), serviceToken, createBody(seedHex)); response.StatusCode != http.StatusAccepted {
|
|
t.Fatalf("PUT = %d", response.StatusCode)
|
|
}
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for {
|
|
record, err := manager.Get(id)
|
|
if err == nil && record.State == "ready" {
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("lab did not become ready: %+v %v", record, err)
|
|
}
|
|
time.Sleep(2 * time.Millisecond)
|
|
}
|
|
response, body := call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+id.String(), serviceToken, nil)
|
|
if response.StatusCode != http.StatusOK || body["ready_at"] == nil {
|
|
t.Fatalf("GET = %d %v", response.StatusCode, body)
|
|
}
|
|
assertNoInfrastructure(t, body)
|
|
|
|
response, body = call(t, httpServer.URL, http.MethodPost, "/v1/labs/"+id.String()+"/console-tokens", serviceToken, map[string]any{"node": "srv"})
|
|
if response.StatusCode != http.StatusCreated || response.Header.Get("Cache-Control") != "no-store" ||
|
|
body["attach_path"] != "/v1/labs/"+id.String()+"/console" || len(body["token"].(string)) != 43 {
|
|
t.Fatalf("console token = %d %v", response.StatusCode, body)
|
|
}
|
|
response, body = call(t, httpServer.URL, http.MethodPost, "/v1/labs/"+id.String()+"/console-tokens", serviceToken, map[string]any{"node": "r9"})
|
|
if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" {
|
|
t.Fatalf("console token for an unknown node = %d %v", response.StatusCode, body)
|
|
}
|
|
response, body = call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+id.String()+"/console", serviceToken, nil)
|
|
if response.StatusCode != http.StatusNotImplemented || body["code"] != "not_implemented" {
|
|
t.Fatalf("console attach = %d %v", response.StatusCode, body)
|
|
}
|
|
if response, _ = call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+id.String()+"/console", "", nil); response.StatusCode != http.StatusUnauthorized {
|
|
t.Fatalf("console attach without a token = %d", response.StatusCode)
|
|
}
|
|
|
|
response, body = call(t, httpServer.URL, http.MethodPost, "/v1/labs/"+id.String()+"/check", serviceToken, nil)
|
|
if response.StatusCode != http.StatusOK || body["score"] != 1.0 || body["max_score"] != 2.0 {
|
|
t.Fatalf("check = %d %v", response.StatusCode, body)
|
|
}
|
|
|
|
response, body = call(t, httpServer.URL, http.MethodDelete, "/v1/labs/"+id.String(), serviceToken, nil)
|
|
if response.StatusCode != http.StatusAccepted || body["state"] != "deleting" {
|
|
t.Fatalf("DELETE = %d %v", response.StatusCode, body)
|
|
}
|
|
response, body = call(t, httpServer.URL, http.MethodPost, "/v1/labs/"+id.String()+"/check", serviceToken, nil)
|
|
if response.StatusCode != http.StatusConflict || body["code"] != "state_conflict" {
|
|
t.Fatalf("check of a deleting lab = %d %v", response.StatusCode, body)
|
|
}
|
|
}
|
|
|
|
func TestUnknownTemplateIsAValidationFailure(t *testing.T) {
|
|
httpServer, _ := newServer(t, "127.0.0.0/8")
|
|
body := createBody(seedHex)
|
|
body["template_id"] = "mikrotik-bgp"
|
|
response, decoded := call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+uuid.NewString(), serviceToken, body)
|
|
if response.StatusCode != http.StatusBadRequest || decoded["code"] != "validation_failed" {
|
|
t.Fatalf("PUT with an unknown template = %d %v", response.StatusCode, decoded)
|
|
}
|
|
}
|
|
|
|
// assertNoInfrastructure fails when a lab status names an address, an LXD
|
|
// object, or the seed.
|
|
func assertNoInfrastructure(t *testing.T, body map[string]any) {
|
|
t.Helper()
|
|
encoded, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
text := string(encoded)
|
|
for _, forbidden := range []string{"10.81.", "lcxl-", "lxl", "address", "instance", "bridge", seedHex} {
|
|
if strings.Contains(text, forbidden) {
|
|
t.Fatalf("lab status contains %q: %s", forbidden, text)
|
|
}
|
|
}
|
|
}
|