Files
ilkerandClaude Opus 5 d67af5d6c3 hpcod: projects, and what a cluster cost
"How much did the protein run use" is a question about a piece of
work, not about c003-15. A tenant asks for clusters over months;
individually each one is an address, some hardware and a lease, and
nothing joined them up.

A project groups them, and is optional throughout. Somebody who wants
one cluster for an afternoon should not have to invent a project to
get it, and requiring one would mean every tenant carrying a
"default" that means nothing. The form does not even ask when there
are none: a field whose only option is "none" is a question with one
answer.

The cost side needed no new columns. The cluster record already said
when it was created and destroyed, and cluster_vm said how many cores
and how much memory it held; what was missing was anything that read
them. cluster_usage is that, and it is a view rather than a table
because a derived number stored is a number that can disagree with
what it was derived from. It works retroactively - every cluster this
estate has ever built now has a line.

Core-hours are reserved, not executed, and the view says so. That is
the honest unit for an on-demand cluster: the hardware was yours and
nobody else could have it, whether or not a job ran. What was
actually executed is a Slurm accounting question and there is no
slurmdbd.

The project is attached inside the allocating transaction, for the
same reason the placement and the applications are, and it is checked
there to be the tenant's own and still open - a cluster filed against
somebody else's project leaks what they are working on. Closing keeps
history and stops it being offered. There is no delete: the reference
from cluster is RESTRICT, because a project removed from under its
clusters leaves their cost attributed to nothing, and afterwards is
when the question gets asked.

A release now writes manifest.json beside home.tgz: the nodes, the
wall time, the core-hours. The database knows all of it and outlives
the cluster, but the tarball can be moved off this host and the
description travels with it. Not fatal if it fails - the data is
already safe by then, and holding hardware because a note could not
be written is the wrong trade.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 13:05:35 +02:00

655 lines
23 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package httpapi
import (
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/ilkermanap/hpcod/internal/catalog"
"github.com/ilkermanap/hpcod/internal/model"
"github.com/ilkermanap/hpcod/internal/provision"
"github.com/ilkermanap/hpcod/internal/store"
)
func testServerWithPages(t *testing.T, f *fakeStore) *Server {
t.Helper()
s := &Server{cache: &cache{}, catalog: catalog.Static(nil), store: f}
s.cache.set([]model.Site{{ID: "hv01", Reachable: true, Healthy: true}})
tmpl, err := parseTemplates()
if err != nil {
t.Fatal(err)
}
s.tmpl = tmpl
return s
}
// testServerWithPages leaves auth nil, which is the loopback-only portal:
// every rule that asks "who is signed in" is then answered with "there is
// nobody, so show everything". Tests about who may see what have to turn
// authentication on, or they pass without exercising anything.
func withAuthentication(s *Server) *Server {
s.auth = &authStore{
users: map[string]string{}, sessions: map[string]*session{},
fails: map[string]*failure{}, idleTTL: time.Hour, absTTL: time.Hour,
}
return s
}
func TestClustersPageShowsWhatIsHeld(t *testing.T) {
soon := time.Now().Add(3*time.Hour + 30*time.Minute)
f := &fakeStore{
allocated: &store.Cluster{
SerialID: 7, ClusterID: 3, TenantName: "acme", Site: "hv01",
AccountingName: "c003-7", State: "ready", LeaseExpiresAt: &soon,
},
gotPlacement: store.Placement{VMs: []store.VM{
{Role: "head", NodeIndex: 0, HostNode: "hv01", Cores: 2, MemoryGB: 4},
{Role: "compute", NodeIndex: 1, HostNode: "pve2", Cores: 8, MemoryGB: 34,
Devices: []store.Device{{NativeID: "0000:01:00.0", Capability: "gpu"}}},
}},
}
s := testServerWithPages(t, f)
w := httptest.NewRecorder()
s.pageClusters(w, httptest.NewRequest(http.MethodGet, "/clusters", nil))
if w.Code != http.StatusOK {
t.Fatalf("status %d", w.Code)
}
body := w.Body.String()
for _, want := range []string{"c003-7", "acme", "hv01, pve2", "gpu 0000:01:00.0", "ready", "3 hours"} {
if !strings.Contains(body, want) {
t.Errorf("page does not mention %q", want)
}
}
}
// A release is destructive, so it has to be a POST that redirects: a GET
// would let a link or a prefetch do it, and rendering the result in place
// would repeat it on reload.
func TestReleaseIsAPostThatRedirects(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{SerialID: 7, TenantName: "acme", State: "ready"}}
s := testServerWithPages(t, f)
w := postAs(t, s, url.Values{"cluster": {"7"}, "do": {"release"}}, "acme", false)
if w.Code != http.StatusSeeOther {
t.Fatalf("status = %d, want 303", w.Code)
}
if len(f.released) != 1 || f.released[0] != 7 {
t.Errorf("released = %v, want [7]", f.released)
}
}
func TestExtendSetsALease(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{SerialID: 7, TenantName: "acme", State: "ready"}}
s := testServerWithPages(t, f)
w := postAs(t, s, url.Values{"cluster": {"7"}, "do": {"extend"}, "days": {"14"}}, "acme", false)
if w.Code != http.StatusSeeOther {
t.Fatalf("status = %d, want 303", w.Code)
}
if len(f.leaseSet) != 1 || f.leaseTo == nil {
t.Fatalf("lease not set: %v %v", f.leaseSet, f.leaseTo)
}
if d := time.Until(*f.leaseTo); d < 13*24*time.Hour || d > 15*24*time.Hour {
t.Errorf("lease set to %v from now, want about 14 days", d)
}
}
func TestClusterActionsRejectNonsense(t *testing.T) {
cases := []url.Values{
{"cluster": {"0"}, "do": {"release"}}, // no such id
{"cluster": {"abc"}, "do": {"release"}}, // not a number
{"cluster": {"7"}, "do": {"evaporate"}}, // unknown action
{"cluster": {"7"}, "do": {"extend"}}, // no days
{"cluster": {"7"}, "do": {"extend"}, "days": {"0"}},
{"cluster": {"7"}, "do": {"extend"}, "days": {"9999"}},
}
for _, form := range cases {
f := &fakeStore{allocated: &store.Cluster{SerialID: 7, TenantName: "acme", State: "ready"}}
s := testServerWithPages(t, f)
w := postAs(t, s, form, "acme", false)
if w.Code != http.StatusBadRequest {
t.Errorf("%v gave %d, want 400", form, w.Code)
}
if len(f.released) != 0 || len(f.leaseSet) != 0 {
t.Errorf("%v changed something anyway", form)
}
}
}
// "/" is a catch-all in ServeMux, so without an explicit check every
// mistyped URL renders the landing page and reports 200 for a page that
// does not exist.
func TestUnknownPathIsNotTheLandingPage(t *testing.T) {
f := &fakeStore{}
s := testServerWithPages(t, f)
mux := http.NewServeMux()
mux.HandleFunc("/clusters", s.pageClusters)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
s.pageOverview(w, r)
})
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/no-such-page", nil))
if w.Code != http.StatusNotFound {
t.Errorf("/no-such-page = %d, want 404", w.Code)
}
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/", nil))
if w.Code != http.StatusOK {
t.Errorf("/ = %d, want 200", w.Code)
}
}
func TestOverviewCountsWhatIsHeldAndWhatIsFree(t *testing.T) {
f := &fakeStore{}
s := testServerWithPages(t, f)
s.cache.set([]model.Site{{
ID: "hv01", Reachable: true, Healthy: true,
Nodes: []model.Node{{
Name: "hv01", Online: true, Cores: 32, AllocCores: 8,
MemBytes: 64 << 30, AllocMemBytes: 16 << 30,
Devices: []model.Device{
{NativeID: "0000:01:00.0", Capability: model.CapGPU, Confidence: model.ConfClass, Passthrough: true},
{NativeID: "0000:02:00.0", Capability: model.CapGPU, Confidence: model.ConfClass, Passthrough: true, AllocatedTo: "vm 100"},
},
}},
}})
w := httptest.NewRecorder()
s.pageOverview(w, httptest.NewRequest(http.MethodGet, "/", nil))
if w.Code != http.StatusOK {
t.Fatalf("status %d", w.Code)
}
body := w.Body.String()
for _, want := range []string{"24", "48", "gpu ×1", "1 device(s) held"} {
if !strings.Contains(body, want) {
t.Errorf("overview does not show %q:\n%s", want, body)
}
}
}
func TestOverviewNamesAnUnhealthySite(t *testing.T) {
s := testServerWithPages(t, &fakeStore{})
s.cache.set([]model.Site{
{ID: "hv01", Reachable: true, Healthy: true},
{ID: "pve2", Reachable: false},
{ID: "hv03", Reachable: true, Healthy: false},
})
w := httptest.NewRecorder()
s.pageOverview(w, httptest.NewRequest(http.MethodGet, "/", nil))
body := w.Body.String()
if !strings.Contains(body, "pve2: unreachable") || !strings.Contains(body, "hv03: not healthy") {
t.Errorf("unhealthy sites are not named:\n%s", body)
}
if !strings.Contains(body, "1/3") {
t.Errorf("the healthy count is wrong:\n%s", body)
}
}
// Truncation, never rounding up. A lease is a deadline, and a display that
// says three hours when there are two and a half is telling someone they
// have time they do not have.
func TestHumanDurationNeverOverstates(t *testing.T) {
cases := []struct {
d time.Duration
want string
}{
{7 * 24 * time.Hour, "7 days"},
{2*24*time.Hour + 23*time.Hour, "2 days"},
{47 * time.Hour, "47 hours"},
{3*time.Hour + 59*time.Minute, "3 hours"},
{2 * time.Hour, "2 hours"},
{119 * time.Minute, "119 min"},
{90 * time.Second, "1 min"},
{30 * time.Second, "under a minute"},
}
for _, c := range cases {
if got := humanDuration(c.d); got != c.want {
t.Errorf("humanDuration(%v) = %q, want %q", c.d, got, c.want)
}
}
}
// The lease state drives a colour and a warning, so the boundaries matter.
func TestClusterViewClassifiesLeases(t *testing.T) {
mk := func(d time.Duration) clusterView {
t := time.Now().Add(d)
return makeClusterView(store.Cluster{LeaseExpiresAt: &t}, nil)
}
if v := mk(-time.Minute); !v.Expired || v.LeaseIn != "expired" {
t.Errorf("a past lease: expired=%v in=%q", v.Expired, v.LeaseIn)
}
if v := mk(5 * time.Hour); !v.Expiring || v.Expired {
t.Errorf("five hours left should be expiring, not expired: %+v", v)
}
if v := mk(5 * 24 * time.Hour); v.Expiring || v.Expired {
t.Errorf("five days left should be neither: %+v", v)
}
// No lease is a deliberate choice and must never look like an expiry.
v := makeClusterView(store.Cluster{}, nil)
if v.Expired || v.Expiring || v.LeaseIn != "" {
t.Errorf("a cluster with no lease was classified: %+v", v)
}
}
// navLinks reads the hrefs out of a rendered page's navigation.
//
// Taking them from the page rather than from a list here is the point: a
// hardcoded list goes on passing after a link is renamed or moved, which
// is exactly when this check is worth having.
func navLinks(t *testing.T, body string) []string {
t.Helper()
nav := body[strings.Index(body, "<nav>"):]
nav = nav[:strings.Index(nav, "</nav>")]
var out []string
for _, part := range strings.Split(nav, `href="`)[1:] {
out = append(out, part[:strings.Index(part, `"`)])
}
if len(out) < 4 {
t.Fatalf("found %d navigation links, which cannot be right:\n%s", len(out), nav)
}
return out
}
// Every page the navigation offers has to answer. This is the check that
// was missing when /sites kept a path guard from the days it lived at "/".
func TestEveryNavigatedPageAnswers(t *testing.T) {
s := testServerWithPages(t, &fakeStore{})
mux := http.NewServeMux()
mux.HandleFunc("/clusters/new", s.pagePlan)
mux.HandleFunc("/capmap", s.pageCapMap)
mux.HandleFunc("/clusters", s.pageClusters)
mux.HandleFunc("/sites", s.pageSites)
mux.HandleFunc("/admin/accounts", s.pageAccounts)
mux.HandleFunc("/projects", s.pageProjects)
mux.HandleFunc("/usage", s.pageUsage)
mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
s.pageOverview(w, r)
})
// Rendered as an administrator, so the admin-only links are in the
// navigation and get walked too.
first := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/", nil)
mux.ServeHTTP(first, r.WithContext(withUser(r.Context(), "ilker", true)))
for _, path := range navLinks(t, first.Body.String()) {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, path, nil)
// As the same person the navigation was rendered for: an
// admin-only page answers 404 to anyone else, which would be
// the page working rather than failing.
mux.ServeHTTP(w, req.WithContext(withUser(req.Context(), "ilker", true)))
if w.Code != http.StatusOK {
t.Errorf("the navigation offers %s, which answers %d", path, w.Code)
}
}
}
// The page was called "Dry run" and lived at /plan. Renaming a page must
// not break a link somebody kept.
func TestTheOldPlanAddressStillLeadsSomewhere(t *testing.T) {
s := testServerWithPages(t, &fakeStore{})
mux := http.NewServeMux()
mux.HandleFunc("/plan", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/clusters/new", http.StatusMovedPermanently)
})
mux.HandleFunc("/clusters/new", s.pagePlan)
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/plan", nil))
if w.Code != http.StatusMovedPermanently || w.Header().Get("Location") != "/clusters/new" {
t.Errorf("/plan = %d to %q", w.Code, w.Header().Get("Location"))
}
}
// ---------- building ----------
func buildForm(id string) url.Values {
return url.Values{"cluster": {id}, "do": {"build"}}
}
func postAs(t *testing.T, s *Server, form url.Values, user string, admin bool) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest(http.MethodPost, "/clusters", strings.NewReader(form.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r = r.WithContext(withUser(r.Context(), user, admin))
w := httptest.NewRecorder()
s.pageClusters(w, r)
return w
}
// With no template configured the portal allocates but cannot build, and
// has to say that rather than fail obscurely.
func TestBuildingIsRefusedWhenThePortalCannotBuild(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 7, TenantName: "acme", State: "requested", AccountingName: "c003-7",
}}
s := testServerWithPages(t, f) // no builder
w := postAs(t, s, buildForm("7"), "acme", false)
if w.Code != http.StatusServiceUnavailable {
t.Errorf("status %d, want 503", w.Code)
}
if !strings.Contains(w.Body.String(), "no environment template") {
t.Errorf("the refusal does not say why: %s", w.Body)
}
}
// A cluster belongs to somebody. Its owner may rebuild it; a stranger may
// not, and must not even learn that it exists.
func TestOnlyTheOwnerOrAnAdminMayBuild(t *testing.T) {
c := store.Cluster{SerialID: 7, TenantName: "acme", State: "requested", AccountingName: "c003-7"}
for _, tc := range []struct {
user string
admin bool
want int
}{
{"acme", false, http.StatusServiceUnavailable}, // owner: gets as far as "cannot build"
{"someone-else", false, http.StatusNotFound}, // stranger: not told it exists
{"theboss", true, http.StatusServiceUnavailable},
} {
f := &fakeStore{allocated: &c}
s := testServerWithPages(t, f)
w := postAs(t, s, buildForm("7"), tc.user, tc.admin)
if w.Code != tc.want {
t.Errorf("%s (admin=%v) got %d, want %d", tc.user, tc.admin, w.Code, tc.want)
}
}
}
// Rebuilding a running cluster would re-run Terraform against live
// machines. A failed one is exactly what you do want to retry.
func TestOnlyRequestedOrFailedClustersAreBuilt(t *testing.T) {
for state, wantRefusal := range map[string]bool{
"requested": false, "failed": false,
"ready": true, "provisioning": true, "deleting": true,
} {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 7, TenantName: "acme", State: state, AccountingName: "c003-7",
}}
s := testServerWithPages(t, f)
w := postAs(t, s, buildForm("7"), "acme", false)
refused := w.Code == http.StatusConflict
if refused != wantRefusal {
t.Errorf("state %q gave %d (refused=%v), want refused=%v", state, w.Code, refused, wantRefusal)
}
}
}
// The button must not be offered to someone who cannot use it, and the
// actions on somebody else's cluster must not be rendered at all.
func TestTheBuildButtonFollowsTheSameRule(t *testing.T) {
f := &fakeStore{
allocated: &store.Cluster{SerialID: 7, TenantName: "acme", State: "requested", AccountingName: "c003-7"},
}
s := testServerWithPages(t, f)
r := httptest.NewRequest(http.MethodGet, "/clusters", nil)
r = r.WithContext(withUser(r.Context(), "someone-else", false))
w := httptest.NewRecorder()
s.pageClusters(w, r)
if strings.Contains(w.Body.String(), `value="release"`) {
t.Error("a stranger was shown the actions for somebody else's cluster")
}
r = httptest.NewRequest(http.MethodGet, "/clusters", nil)
r = r.WithContext(withUser(r.Context(), "acme", false))
w = httptest.NewRecorder()
s.pageClusters(w, r)
if !strings.Contains(w.Body.String(), `value="release"`) {
t.Error("the owner was not shown their own cluster's actions")
}
}
// The link only appears once the cluster is published. Linking a name the
// proxy does not know sends someone from their own cluster's row to "no
// cluster is published here", which reads as the cluster being broken.
func TestThePortalLinkWaitsForPublication(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 7, ClusterID: 1, TenantName: "acme", State: "ready", AccountingName: "c001-7",
}}
s := testServerWithPages(t, f)
s.opt.ClusterDomain = "hpc.example"
// No registry at all: nothing is published, so nothing is linked.
w := httptest.NewRecorder()
s.pageClusters(w, adminRequest(http.MethodGet, "/clusters", nil))
if strings.Contains(w.Body.String(), "Open portal") {
t.Error("an unpublished cluster was given a link")
}
// Published: the link is the name the proxy routes.
dir := t.TempDir()
certPath := filepath.Join(dir, "c001.crt")
if err := os.WriteFile(certPath, unrelatedCertPEM(t), 0o600); err != nil {
t.Fatal(err)
}
regPath := filepath.Join(dir, "clusters.yaml")
if err := os.WriteFile(regPath,
[]byte("clusters:\n - id: 1\n portal: 10.0.0.62:443\n cert: "+certPath+"\n"), 0o600); err != nil {
t.Fatal(err)
}
s.registry = NewClusterRegistry(regPath, "hpc.example")
w = httptest.NewRecorder()
s.pageClusters(w, adminRequest(http.MethodGet, "/clusters", nil))
if !strings.Contains(w.Body.String(), "https://c001.hpc.example/") {
t.Errorf("no link to the published portal:\n%s", w.Body)
}
}
// A released cluster must stop answering at its own name, or the proxy
// keeps routing to a machine nobody is maintaining.
func TestReleasingAlsoUnpublishes(t *testing.T) {
dir := t.TempDir()
reg := &provision.Registry{
Path: filepath.Join(dir, "clusters.yaml"), CertDir: filepath.Join(dir, "certs"),
}
if err := os.WriteFile(reg.Path,
[]byte("clusters:\n - id: 5\n portal: 10.0.0.62:443\n cert: /nope\n"), 0o600); err != nil {
t.Fatal(err)
}
f := &fakeStore{allocated: &store.Cluster{
SerialID: 7, ClusterID: 5, TenantName: "acme", State: "ready", AccountingName: "c005-7",
}}
s := testServerWithPages(t, f)
s.opt.Provision.Registry = reg
w := postAs(t, s, url.Values{"cluster": {"7"}, "do": {"release"}}, "acme", false)
if w.Code != http.StatusSeeOther {
t.Fatalf("status %d", w.Code)
}
body, err := os.ReadFile(reg.Path)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), "id: 5") {
t.Errorf("the released cluster is still published:\n%s", body)
}
if len(f.released) != 1 {
t.Errorf("the record was not released: %v", f.released)
}
}
// A link to somebody else's cluster is not a small cosmetic leak. It says
// that the cluster exists, publishes the hostname it answers on, and
// invites a click that the proxy then refuses - so the page has promised
// something the system will not honour. Whoever may not use a cluster is
// not shown the way in.
func TestOnlyTheOwnerOrAnAdminSeesThePortalLink(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 7, ClusterID: 1, TenantName: "acme", State: "ready", AccountingName: "c001-7",
}}
s := testServerWithPages(t, f)
s.opt.ClusterDomain = "hpc.example"
dir := t.TempDir()
certPath := filepath.Join(dir, "c001.crt")
if err := os.WriteFile(certPath, unrelatedCertPEM(t), 0o600); err != nil {
t.Fatal(err)
}
regPath := filepath.Join(dir, "clusters.yaml")
if err := os.WriteFile(regPath,
[]byte("clusters:\n - id: 1\n portal: 10.0.0.62:443\n cert: "+certPath+"\n"), 0o600); err != nil {
t.Fatal(err)
}
s.registry = NewClusterRegistry(regPath, "hpc.example")
// Both pages render the link, and both are fed by clusterViews.
for _, page := range []struct {
name string
path string
show func(http.ResponseWriter, *http.Request)
}{
{"clusters", "/clusters", s.pageClusters},
{"overview", "/", s.pageOverview},
} {
for _, who := range []struct {
user string
admin bool
see bool
}{
{"acme", false, true}, // the owner
{"ilker", true, true}, // an administrator
{"ilkermanap", false, false}, // signed in, and none of their business
} {
r := httptest.NewRequest(http.MethodGet, page.path, nil)
r = r.WithContext(withUser(r.Context(), who.user, who.admin))
w := httptest.NewRecorder()
page.show(w, r)
got := strings.Contains(w.Body.String(), "https://c001.hpc.example/")
if got != who.see {
t.Errorf("%s page, %q (admin=%v): link shown=%v, want %v",
page.name, who.user, who.admin, got, who.see)
}
}
}
}
// The row itself, not only the link. It names the tenant holding the
// cluster, the hypervisor it runs on and the devices it is keeping, which
// together are an inventory of who runs what.
func TestATenantSeesOnlyTheirOwnClusters(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 7, ClusterID: 1, TenantName: "acme", Site: "hv01",
State: "ready", AccountingName: "c001-7",
}}
s := withAuthentication(testServerWithPages(t, f))
for _, page := range []struct {
name string
path string
show func(http.ResponseWriter, *http.Request)
}{
{"clusters", "/clusters", s.pageClusters},
{"overview", "/", s.pageOverview},
} {
r := httptest.NewRequest(http.MethodGet, page.path, nil)
r = r.WithContext(withUser(r.Context(), "ilkermanap", false))
w := httptest.NewRecorder()
page.show(w, r)
for _, leak := range []string{"c001-7", "acme"} {
if strings.Contains(w.Body.String(), leak) {
t.Errorf("%s page leaked %q to a stranger", page.name, leak)
}
}
r = httptest.NewRequest(http.MethodGet, page.path, nil)
r = r.WithContext(withUser(r.Context(), "acme", false))
w = httptest.NewRecorder()
page.show(w, r)
if !strings.Contains(w.Body.String(), "c001-7") {
t.Errorf("%s page hid the owner's own cluster", page.name)
}
r = httptest.NewRequest(http.MethodGet, page.path, nil)
r = r.WithContext(withUser(r.Context(), "ilker", true))
w = httptest.NewRecorder()
page.show(w, r)
if !strings.Contains(w.Body.String(), "c001-7") {
t.Errorf("%s page hid a cluster from an administrator", page.name)
}
}
}
// With authentication disabled the portal is loopback-only and nobody is
// signed in. Filtering on a name that does not exist would hide every
// cluster from the only person who can reach the page.
func TestWithoutAuthenticationNothingIsFilteredAway(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 7, ClusterID: 1, TenantName: "acme", State: "ready", AccountingName: "c001-7",
}}
s := testServerWithPages(t, f)
s.auth = nil
w := httptest.NewRecorder()
s.pageClusters(w, httptest.NewRequest(http.MethodGet, "/clusters", nil))
if !strings.Contains(w.Body.String(), "c001-7") {
t.Error("the loopback portal was shown no clusters at all")
}
}
// The buttons are hidden for a cluster that is not yours. That was doing
// all the work: "release" and "extend" arrived at the handler with an id
// and acted on it, so any signed-in account could destroy or extend
// somebody else's cluster by posting the form themselves.
func TestAStrangerCannotReleaseOrExtendSomebodyElsesCluster(t *testing.T) {
for _, do := range []url.Values{
{"cluster": {"7"}, "do": {"release"}},
{"cluster": {"7"}, "do": {"extend"}, "days": {"14"}},
{"cluster": {"7"}, "do": {"build"}},
} {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 7, TenantName: "acme", State: "ready",
}}
s := testServerWithPages(t, f)
w := postAs(t, s, do, "ilkermanap", false)
if w.Code != http.StatusNotFound {
t.Errorf("%v by a stranger gave %d, want 404", do, w.Code)
}
if len(f.released) != 0 || len(f.leaseSet) != 0 {
t.Errorf("%v by a stranger changed something: released=%v leases=%v",
do, f.released, f.leaseSet)
}
}
}
// An administrator still may, on anyone's behalf.
func TestAnAdminMayActOnAnyCluster(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{SerialID: 7, TenantName: "acme", State: "ready"}}
s := testServerWithPages(t, f)
w := postAs(t, s, url.Values{"cluster": {"7"}, "do": {"release"}}, "ilker", true)
if w.Code != http.StatusSeeOther {
t.Fatalf("status = %d, want 303", w.Code)
}
if len(f.released) != 1 {
t.Errorf("released = %v, want one", f.released)
}
}