This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package containerapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/container"
|
||||
"github.com/itworx/pulse/internal/problem"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
Provider interface {
|
||||
Snapshot(context.Context) (container.Snapshot, error)
|
||||
}
|
||||
Limits container.Limits
|
||||
}
|
||||
|
||||
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || (r.URL.Path != "/api/v1/containers" && !strings.HasPrefix(r.URL.Path, "/api/v1/containers/")) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if _, ok := auth.PrincipalFromContext(r.Context()); !ok {
|
||||
problem.Write(w, r, http.StatusUnauthorized, "UNAUTHORIZED", "Authentication required", "Authentication is required to read containers.", nil)
|
||||
return
|
||||
}
|
||||
snapshot, err := h.snapshot(r)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "CONTAINERS_UNAVAILABLE", "Containers not available", "Containergegevens konden niet worden gelezen.", nil)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/api/v1/containers" {
|
||||
id := strings.TrimPrefix(r.URL.Path, "/api/v1/containers/")
|
||||
for _, item := range snapshot.Containers {
|
||||
if item.ID == id {
|
||||
writeJSON(w, struct {
|
||||
Source container.Source `json:"source"`
|
||||
Container container.Container `json:"container"`
|
||||
}{Source: snapshot.Source, Container: item})
|
||||
return
|
||||
}
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
if value := r.URL.Query().Get("limit"); value != "" {
|
||||
parsed, parseErr := strconv.Atoi(value)
|
||||
if parseErr != nil {
|
||||
problem.Write(w, r, http.StatusBadRequest, "CONTAINER_QUERY_INVALID", "Invalid container query", "De containerlimiet is ongeldig.", nil)
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
order := r.URL.Query().Get("sort")
|
||||
if order == "" {
|
||||
order = "name"
|
||||
}
|
||||
page, err := container.FilteredPage(snapshot, limit, r.URL.Query().Get("after"), h.Limits, r.URL.Query().Get("q"), r.URL.Query().Get("state"), r.URL.Query().Get("health"), order)
|
||||
if err != nil {
|
||||
problem.Write(w, r, http.StatusBadRequest, "CONTAINER_QUERY_INVALID", "Invalid container query", "De containerlimiet of cursor is ongeldig.", nil)
|
||||
return
|
||||
}
|
||||
writeJSON(w, page)
|
||||
}
|
||||
func (h Handler) snapshot(r *http.Request) (container.Snapshot, error) {
|
||||
if h.Provider == nil {
|
||||
return container.UnknownSnapshot(time.Now().UTC(), "container", "agent", "source_unavailable"), nil
|
||||
}
|
||||
return h.Provider.Snapshot(r.Context())
|
||||
}
|
||||
func writeJSON(w http.ResponseWriter, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "private, max-age=5")
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package containerapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/container"
|
||||
)
|
||||
|
||||
type provider struct{ value container.Snapshot }
|
||||
|
||||
func (p provider) Snapshot(context.Context) (container.Snapshot, error) { return p.value, nil }
|
||||
func authRequest(method, path string) *http.Request {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
return r.WithContext(auth.WithPrincipal(r.Context(), auth.Principal{Subject: "viewer", Role: auth.RoleViewer}))
|
||||
}
|
||||
|
||||
func TestHandlerListDetailAndNoMutation(t *testing.T) {
|
||||
snapshot := container.Snapshot{ContractVersion: container.ContractVersion, Source: container.Source{ID: "agent", State: "healthy"}, Containers: []container.Container{{ID: "abc", Name: "media", State: "running", Health: "unhealthy"}}, Total: 1}
|
||||
h := Handler{Provider: provider{value: snapshot}}
|
||||
list := httptest.NewRecorder()
|
||||
h.ServeHTTP(list, authRequest(http.MethodGet, "/api/v1/containers?limit=1"))
|
||||
if list.Code != http.StatusOK || !strings.Contains(list.Body.String(), `"name":"media"`) {
|
||||
t.Fatalf("status=%d body=%s", list.Code, list.Body.String())
|
||||
}
|
||||
detail := httptest.NewRecorder()
|
||||
h.ServeHTTP(detail, authRequest(http.MethodGet, "/api/v1/containers/abc"))
|
||||
if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), `"container":{"id":"abc"`) {
|
||||
t.Fatalf("status=%d body=%s", detail.Code, detail.Body.String())
|
||||
}
|
||||
mutate := httptest.NewRecorder()
|
||||
h.ServeHTTP(mutate, authRequest(http.MethodPost, "/api/v1/containers/abc/restart"))
|
||||
if mutate.Code != http.StatusNotFound {
|
||||
t.Fatalf("mutation=%d", mutate.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerRequiresAuthentication(t *testing.T) {
|
||||
response := httptest.NewRecorder()
|
||||
Handler{}.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/containers", nil))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status=%d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerAppliesFiltersBeforePagination(t *testing.T) {
|
||||
snapshot := container.Snapshot{Source: container.Source{ID: "agent", State: "healthy"}, Containers: []container.Container{{ID: "a", Name: "api", State: "running", Health: "healthy"}, {ID: "b", Name: "database", State: "running", Health: "healthy"}}, Total: 2}
|
||||
response := httptest.NewRecorder()
|
||||
Handler{Provider: provider{value: snapshot}}.ServeHTTP(response, authRequest(http.MethodGet, "/api/v1/containers?limit=1&q=database&state=running&health=healthy&sort=name"))
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"name":"database"`) || !strings.Contains(response.Body.String(), `"total":1`) {
|
||||
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user