feat(labs): add the labd provisioner with clone pool, time to live and limits
This commit is contained in:
1 parent
9fdaa62b9b
commit
9385b2ddd4
53 files changed
+14675
-6
No files matched your search
@@ -0,0 +1,213 @@
|
||||
// Package server implements the labd HTTP API on the generated ogen server.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
ogenerrors "github.com/ogen-go/ogen/ogenerrors"
|
||||
|
||||
"lincodex/labd/internal/api"
|
||||
"lincodex/labd/internal/lab"
|
||||
"lincodex/labd/internal/pool"
|
||||
"lincodex/labd/internal/template"
|
||||
)
|
||||
|
||||
// Labs is the lab manager; pool.Manager implements it.
|
||||
type Labs interface {
|
||||
Create(id uuid.UUID, request pool.CreateRequest) (lab.Lab, bool, error)
|
||||
Get(id uuid.UUID) (lab.Lab, error)
|
||||
Delete(id uuid.UUID) (lab.Lab, bool, error)
|
||||
ConsoleToken(id uuid.UUID, node string) (string, time.Time, error)
|
||||
Check(ctx context.Context, id uuid.UUID) (pool.CheckResult, error)
|
||||
}
|
||||
|
||||
// Handler implements the generated api.Handler.
|
||||
type Handler struct {
|
||||
labs Labs
|
||||
ready func() bool
|
||||
retryAfter time.Duration
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
var _ api.Handler = (*Handler)(nil)
|
||||
|
||||
// NewHandler returns the API handler.
|
||||
func NewHandler(labs Labs, ready func() bool, retryAfter time.Duration, logger *slog.Logger) *Handler {
|
||||
return &Handler{labs: labs, ready: ready, retryAfter: retryAfter, logger: logger}
|
||||
}
|
||||
|
||||
// GetLabdHealthz reports that the process responds.
|
||||
func (h *Handler) GetLabdHealthz(context.Context) (*api.LabdHealthResponse, error) {
|
||||
return &api.LabdHealthResponse{Status: api.LabdHealthResponseStatusOk}, nil
|
||||
}
|
||||
|
||||
// GetLabdReadyz reports whether labs can be created and deleted.
|
||||
func (h *Handler) GetLabdReadyz(context.Context) (api.GetLabdReadyzRes, error) {
|
||||
if h.ready() {
|
||||
return &api.GetLabdReadyzOK{Status: api.LabdReadinessResponseStatusReady}, nil
|
||||
}
|
||||
return &api.GetLabdReadyzServiceUnavailable{Status: api.LabdReadinessResponseStatusNotReady}, nil
|
||||
}
|
||||
|
||||
// CreateLab admits a lab or returns the lab with the same ID and payload.
|
||||
func (h *Handler) CreateLab(_ context.Context, req *api.LabCreateRequest, params api.CreateLabParams) (api.CreateLabRes, error) {
|
||||
seed, err := hex.DecodeString(req.Seed)
|
||||
if err != nil || len(seed) != template.SeedBytes {
|
||||
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
|
||||
invalidField(api.ProblemFieldLocationBody, "/seed"))
|
||||
}
|
||||
record, created, err := h.labs.Create(params.LabID, pool.CreateRequest{
|
||||
TemplateID: string(req.TemplateID),
|
||||
TemplateVersion: int(req.TemplateVersion),
|
||||
Seed: [template.SeedBytes]byte(seed),
|
||||
Lifetime: time.Duration(req.TTLSeconds) * time.Second,
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pool.ErrBusy):
|
||||
return &api.LabPoolBusyHeaders{
|
||||
RetryAfter: int32(min(math.Ceil(h.retryAfter.Seconds()), math.MaxInt32)),
|
||||
Response: newProblem(http.StatusServiceUnavailable, api.ProblemCodeLabPoolBusy, "No capacity for another lab. Retry later with the same lab ID."),
|
||||
}, nil
|
||||
case errors.Is(err, pool.ErrUnknownTemplate):
|
||||
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The template or its version is unknown.",
|
||||
invalidField(api.ProblemFieldLocationBody, "/template_id"), invalidField(api.ProblemFieldLocationBody, "/template_version"))
|
||||
case errors.Is(err, pool.ErrLifetimeTooLong):
|
||||
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The lifetime exceeds the maximum.",
|
||||
invalidField(api.ProblemFieldLocationBody, "/ttl_seconds"))
|
||||
case errors.Is(err, pool.ErrPayloadMismatch):
|
||||
return nil, problemError(http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused, "A lab with this ID exists with a different payload.")
|
||||
case errors.Is(err, pool.ErrIDCollision):
|
||||
return nil, problemError(http.StatusConflict, api.ProblemCodeStateConflict, "The lab ID collides with another lab. Use another lab ID.")
|
||||
case err != nil:
|
||||
return nil, fmt.Errorf("server.Handler.CreateLab - create: %w", err)
|
||||
}
|
||||
status := toLabStatus(record)
|
||||
if created {
|
||||
accepted := api.CreateLabAccepted(status)
|
||||
return &accepted, nil
|
||||
}
|
||||
existing := api.CreateLabOK(status)
|
||||
return &existing, nil
|
||||
}
|
||||
|
||||
// GetLab returns the state of a lab.
|
||||
func (h *Handler) GetLab(_ context.Context, params api.GetLabParams) (*api.LabStatus, error) {
|
||||
record, err := h.labs.Get(params.LabID)
|
||||
if err != nil {
|
||||
return nil, h.labError("GetLab", err)
|
||||
}
|
||||
status := toLabStatus(record)
|
||||
return &status, nil
|
||||
}
|
||||
|
||||
// DeleteLab ends a lab before its timer.
|
||||
func (h *Handler) DeleteLab(_ context.Context, params api.DeleteLabParams) (api.DeleteLabRes, error) {
|
||||
record, changed, err := h.labs.Delete(params.LabID)
|
||||
if err != nil {
|
||||
return nil, h.labError("DeleteLab", err)
|
||||
}
|
||||
status := toLabStatus(record)
|
||||
if changed {
|
||||
accepted := api.DeleteLabAccepted(status)
|
||||
return &accepted, nil
|
||||
}
|
||||
existing := api.DeleteLabOK(status)
|
||||
return &existing, nil
|
||||
}
|
||||
|
||||
// CreateLabConsoleToken issues a console token for one node.
|
||||
func (h *Handler) CreateLabConsoleToken(_ context.Context, req *api.ConsoleTokenRequest, params api.CreateLabConsoleTokenParams) (*api.ConsoleTokenHeaders, error) {
|
||||
token, expiresAt, err := h.labs.ConsoleToken(params.LabID, string(req.Node))
|
||||
if errors.Is(err, pool.ErrUnknownNode) {
|
||||
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The lab has no such node.",
|
||||
invalidField(api.ProblemFieldLocationBody, "/node"))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, h.labError("CreateLabConsoleToken", err)
|
||||
}
|
||||
return &api.ConsoleTokenHeaders{
|
||||
CacheControl: api.CreateLabConsoleTokenCreatedCacheControlNoStore,
|
||||
Response: api.ConsoleToken{
|
||||
Token: token, Node: req.Node, ExpiresAt: expiresAt,
|
||||
AttachPath: "/v1/labs/" + params.LabID.String() + "/console",
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CheckLab runs the checker of the template against a ready lab.
|
||||
func (h *Handler) CheckLab(ctx context.Context, params api.CheckLabParams) (*api.LabCheckResult, error) {
|
||||
result, err := h.labs.Check(ctx, params.LabID)
|
||||
if errors.Is(err, pool.ErrCheckUnavailable) {
|
||||
h.logger.WarnContext(ctx, "lab check unavailable", slog.String("lab_id", params.LabID.String()), slog.String("error", err.Error()))
|
||||
return nil, problemError(http.StatusServiceUnavailable, api.ProblemCodeLabUnavailable, "The lab could not be evaluated. Nothing was checked.")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, h.labError("CheckLab", err)
|
||||
}
|
||||
converted := api.LabCheckResult{LabID: params.LabID, CheckedAt: result.CheckedAt, Criteria: make([]api.CriterionResult, 0, len(result.Criteria))}
|
||||
for _, criterion := range result.Criteria {
|
||||
converted.Criteria = append(converted.Criteria, api.CriterionResult{ID: api.CriterionId(criterion.ID), Passed: criterion.Passed})
|
||||
if criterion.Passed {
|
||||
converted.Score++
|
||||
}
|
||||
}
|
||||
converted.MaxScore = int32(len(result.Criteria)) //nolint:gosec // Criteria are bounded by the template package.
|
||||
return &converted, nil
|
||||
}
|
||||
|
||||
// labError maps the errors that several operations share.
|
||||
func (h *Handler) labError(operation string, err error) error {
|
||||
switch {
|
||||
case errors.Is(err, pool.ErrNotFound):
|
||||
return problemError(http.StatusNotFound, api.ProblemCodeNotFound, "The provisioner holds no lab with this ID.")
|
||||
case errors.Is(err, pool.ErrNotReady):
|
||||
return problemError(http.StatusConflict, api.ProblemCodeStateConflict, "The lab is not ready.")
|
||||
default:
|
||||
return fmt.Errorf("server.Handler.%s: %w", operation, err)
|
||||
}
|
||||
}
|
||||
|
||||
// NewError maps errors of handlers and of the security check to problems.
|
||||
func (h *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
|
||||
var securityErr *ogenerrors.SecurityError
|
||||
if errors.As(err, &securityErr) {
|
||||
return problemError(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token.")
|
||||
}
|
||||
h.logger.ErrorContext(ctx, "request failed", slog.String("error_type", fmt.Sprintf("%T", err)))
|
||||
return problemError(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")
|
||||
}
|
||||
|
||||
// toLabStatus converts a record. It copies only the fields of the contract:
|
||||
// no address, instance, bridge, or seed leaves labd.
|
||||
func toLabStatus(record lab.Lab) api.LabStatus {
|
||||
status := api.LabStatus{
|
||||
LabID: record.ID,
|
||||
State: api.LabState(record.State),
|
||||
TemplateID: api.TemplateId(record.TemplateID),
|
||||
TemplateVersion: int32(record.TemplateVersion), //nolint:gosec // Template versions are at most 10000.
|
||||
CreatedAt: record.CreatedAt,
|
||||
ExpiresAt: record.ExpiresAt,
|
||||
Nodes: make([]api.LabNode, 0, len(record.Nodes)),
|
||||
}
|
||||
if !record.ReadyAt.IsZero() {
|
||||
status.ReadyAt = api.NewOptDateTime(record.ReadyAt)
|
||||
}
|
||||
if !record.DeletedAt.IsZero() {
|
||||
status.DeletedAt = api.NewOptDateTime(record.DeletedAt)
|
||||
}
|
||||
if record.FailureReason != "" {
|
||||
status.FailureReason = api.NewOptLabFailureReason(api.LabFailureReason(record.FailureReason))
|
||||
}
|
||||
for _, node := range record.Nodes {
|
||||
status.Nodes = append(status.Nodes, api.LabNode{Name: api.NodeName(node.Name), Kind: api.NodeKind(node.Kind)})
|
||||
}
|
||||
return status
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/jx"
|
||||
ogenerrors "github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
|
||||
"lincodex/labd/internal/api"
|
||||
)
|
||||
|
||||
const problemTypePrefix = "urn:lincodex:problem:"
|
||||
|
||||
// problemTitles are the fixed titles of the lab provisioner problem codes.
|
||||
var problemTitles = map[api.ProblemCode]string{
|
||||
api.ProblemCodeValidationFailed: "Request validation failed",
|
||||
api.ProblemCodeUnauthenticated: "Authentication required",
|
||||
api.ProblemCodeNotFound: "Not found",
|
||||
api.ProblemCodeMethodNotAllowed: "Method not allowed",
|
||||
api.ProblemCodeStateConflict: "State conflict",
|
||||
api.ProblemCodePayloadTooLarge: "Payload too large",
|
||||
api.ProblemCodeUnsupportedMediaType: "Unsupported media type",
|
||||
api.ProblemCodeIdempotencyKeyReused: "Lab ID reused with a different payload",
|
||||
api.ProblemCodeInternal: "Internal server error",
|
||||
api.ProblemCodeNotImplemented: "Not implemented",
|
||||
api.ProblemCodeLabPoolBusy: "Lab pool busy",
|
||||
api.ProblemCodeLabUnavailable: "Lab unavailable",
|
||||
}
|
||||
|
||||
const invalidFieldMessage = "The value does not match the contract."
|
||||
|
||||
func newProblem(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) api.Problem {
|
||||
problem := api.Problem{
|
||||
Type: problemTypePrefix + string(code),
|
||||
Title: problemTitles[code],
|
||||
Status: int32(status), //nolint:gosec // HTTP status codes fit in int32.
|
||||
Code: code,
|
||||
Errors: fieldErrors,
|
||||
}
|
||||
if detail != "" {
|
||||
problem.Detail = api.NewOptString(detail)
|
||||
}
|
||||
return problem
|
||||
}
|
||||
|
||||
func problemError(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) *api.ProblemStatusCode {
|
||||
return &api.ProblemStatusCode{StatusCode: status, Response: newProblem(status, code, detail, fieldErrors...)}
|
||||
}
|
||||
|
||||
func invalidField(in api.ProblemFieldLocation, pointer string) api.ProblemFieldError {
|
||||
return api.ProblemFieldError{In: in, Pointer: pointer, Code: "invalid", Message: invalidFieldMessage}
|
||||
}
|
||||
|
||||
// writeProblem writes a problem outside the generated handlers.
|
||||
func writeProblem(w http.ResponseWriter, problem api.Problem) {
|
||||
encoder := jx.GetEncoder()
|
||||
defer jx.PutEncoder(encoder)
|
||||
problem.Encode(encoder)
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(int(problem.Status))
|
||||
_, _ = w.Write(encoder.Bytes()) // The client may have gone away.
|
||||
}
|
||||
|
||||
// errorHandler answers request decoding errors of the generated server.
|
||||
func errorHandler(logger *slog.Logger) ogenerrors.ErrorHandler {
|
||||
return func(ctx context.Context, w http.ResponseWriter, _ *http.Request, err error) {
|
||||
writeProblem(w, decodeProblem(ctx, logger, err))
|
||||
}
|
||||
}
|
||||
|
||||
func decodeProblem(ctx context.Context, logger *slog.Logger, err error) api.Problem {
|
||||
var tooLarge *http.MaxBytesError
|
||||
var contentType *validate.InvalidContentTypeError
|
||||
var paramsErr *ogenerrors.DecodeParamsError
|
||||
var requestErr *ogenerrors.DecodeRequestError
|
||||
switch {
|
||||
case errors.As(err, &tooLarge):
|
||||
return newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit.")
|
||||
case errors.As(err, &contentType):
|
||||
return newProblem(http.StatusUnsupportedMediaType, api.ProblemCodeUnsupportedMediaType, "Send the body as application/json.")
|
||||
case errors.As(err, ¶msErr):
|
||||
return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
|
||||
invalidField(api.ProblemFieldLocationPath, "/lab_id"))
|
||||
case errors.As(err, &requestErr):
|
||||
return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
|
||||
invalidField(api.ProblemFieldLocationBody, ""))
|
||||
default:
|
||||
// The error text may describe internals; only its type is logged.
|
||||
logger.ErrorContext(ctx, "request handling failed", slog.String("error_type", fmt.Sprintf("%T", err)))
|
||||
return newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lincodex/labd/internal/api"
|
||||
)
|
||||
|
||||
var (
|
||||
errInvalidToken = errors.New("invalid bearer token")
|
||||
// consoleAttachPath is the planned WebSocket attach of a console token.
|
||||
consoleAttachPath = regexp.MustCompile(`^/v1/labs/[^/]+/console$`)
|
||||
)
|
||||
|
||||
// tokenAuth checks the shared service token. Comparing SHA-256 digests in
|
||||
// constant time hides both the content and the length of the token.
|
||||
type tokenAuth struct {
|
||||
digest [sha256.Size]byte
|
||||
}
|
||||
|
||||
func (a tokenAuth) HandleBearerAuth(ctx context.Context, _ api.OperationName, token api.BearerAuth) (context.Context, error) {
|
||||
if !a.valid(token.Token) {
|
||||
return ctx, errInvalidToken
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (a tokenAuth) valid(token string) bool {
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
return subtle.ConstantTimeCompare(digest[:], a.digest[:]) == 1
|
||||
}
|
||||
|
||||
// Options configure the HTTP handler.
|
||||
type Options struct {
|
||||
Token string
|
||||
MaxRequestBytes int64
|
||||
// AllowedClients are the networks requests may come from.
|
||||
AllowedClients []netip.Prefix
|
||||
}
|
||||
|
||||
// New returns the HTTP handler of the labd API.
|
||||
func New(handler *Handler, options Options, logger *slog.Logger) (http.Handler, error) {
|
||||
if options.Token == "" {
|
||||
return nil, errors.New("server.New - empty service token")
|
||||
}
|
||||
if len(options.AllowedClients) == 0 {
|
||||
return nil, errors.New("server.New - no allowed client network")
|
||||
}
|
||||
auth := tokenAuth{digest: sha256.Sum256([]byte(options.Token))}
|
||||
generated, err := api.NewServer(handler, auth,
|
||||
api.WithErrorHandler(errorHandler(logger)),
|
||||
api.WithNotFound(func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeProblem(w, newProblem(http.StatusNotFound, api.ProblemCodeNotFound, "The route does not exist."))
|
||||
}),
|
||||
api.WithMethodNotAllowed(func(w http.ResponseWriter, _ *http.Request, allowed string) {
|
||||
w.Header().Set("Allow", allowed)
|
||||
writeProblem(w, newProblem(http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed, "The route does not support this method."))
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("server.New - generated server: %w", err)
|
||||
}
|
||||
routes := consoleAttach(auth, limitBody(options.MaxRequestBytes, generated))
|
||||
return accessLog(generated, logger, recoverPanics(logger, allowClients(options.AllowedClients, logger, routes))), nil
|
||||
}
|
||||
|
||||
// allowClients refuses requests from outside the allowed networks before
|
||||
// any other check, as if the token were wrong, so the answer tells such a
|
||||
// caller nothing.
|
||||
func allowClients(allowed []netip.Prefix, logger *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
address, err := netip.ParseAddrPort(r.RemoteAddr)
|
||||
if err != nil || !contains(allowed, address.Addr().Unmap()) {
|
||||
logger.WarnContext(r.Context(), "request from a network outside LABD_ALLOWED_CLIENTS refused", slog.String("remote", r.RemoteAddr))
|
||||
writeProblem(w, newProblem(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token."))
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func contains(prefixes []netip.Prefix, address netip.Addr) bool {
|
||||
for _, prefix := range prefixes {
|
||||
if prefix.Contains(address) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// consoleAttach answers the planned WebSocket attach of a console token. It
|
||||
// checks the service token like every operation and then reports the attach
|
||||
// as not implemented.
|
||||
func consoleAttach(auth tokenAuth, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !consoleAttachPath.MatchString(r.URL.Path) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
token, found := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if !found || !auth.valid(token) {
|
||||
writeProblem(w, newProblem(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token."))
|
||||
return
|
||||
}
|
||||
writeProblem(w, newProblem(http.StatusNotImplemented, api.ProblemCodeNotImplemented, "The console attach is not implemented yet."))
|
||||
})
|
||||
}
|
||||
|
||||
// limitBody refuses bodies above the limit before they are read.
|
||||
func limitBody(limit int64, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.ContentLength > limit {
|
||||
writeProblem(w, newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit."))
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func recoverPanics(logger *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
// The panic value may hold request data; only its type is logged.
|
||||
logger.ErrorContext(ctx, "request panicked", slog.String("panic_type", fmt.Sprintf("%T", recovered)))
|
||||
writeProblem(w, newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request."))
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// accessLog writes one line per request with the operation, status, and
|
||||
// duration. Bodies, headers, and query strings are never logged.
|
||||
func accessLog(router *api.Server, logger *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(recorder, r)
|
||||
operation := "unknown"
|
||||
if route, ok := router.FindPath(r.Method, r.URL); ok {
|
||||
operation = route.OperationID()
|
||||
}
|
||||
logger.InfoContext(r.Context(), "request",
|
||||
slog.String("method", r.Method),
|
||||
slog.String("operation", operation),
|
||||
slog.Int("status", recorder.status),
|
||||
slog.Int64("duration_ms", time.Since(started).Milliseconds()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user