215 lines
9.0 KiB
Go
215 lines
9.0 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http/httptest"
|
|
"os"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"otche/internal/store"
|
|
)
|
|
|
|
func TestNetworkSettingsSubmissionAndRetry(t *testing.T) {
|
|
url := os.Getenv("OTCHE_TEST_DATABASE_URL")
|
|
if url == "" {
|
|
t.Skip("OTCHE_TEST_DATABASE_URL required for isolated PostgreSQL regression")
|
|
}
|
|
ctx := context.Background()
|
|
admin, err := pgxpool.New(ctx, url)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer admin.Close()
|
|
schema := "test_" + strings.ReplaceAll(store.NewID(), "-", "")
|
|
if _, err = admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE")
|
|
cfg, err := pgxpool.ParseConfig(url)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg.ConnConfig.RuntimeParams["search_path"] = schema
|
|
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
if err = store.Migrate(ctx, db); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
owner, err := CreateUser(ctx, db, "network-admin", "Network-regression-password-only", "admin")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
upload, profile, revision := store.NewID(), store.NewID(), store.NewID()
|
|
if _, err = db.Exec(ctx, `INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1,$2,'test.bat',1,$3,$4)`, upload, owner, strings.Repeat("a", 64), upload); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, `INSERT INTO profiles(id,name,os,architecture,enabled,qualification,state,current_revision_id,online_available) VALUES($1,'Network test','Windows','x64',true,'qualified','published',$2,true)`, profile, revision); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, `INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,'network-test','fingerprint','config')`, revision, profile); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, `INSERT INTO bindings(owner_id,pool,iso_storage,disk_storage,node,configured,isolation_expires_at,online_ready,online_expires_at) VALUES($1,'test','test','test','test',true,now()+interval '1 hour',true,now()+interval '1 hour')`, owner); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, `INSERT INTO heartbeats(name,seen_at,ready) VALUES('worker',now(),true)`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s, err := New(db, Config{Origin: "http://localhost", ArtifactRoot: t.TempDir(), MaxQueuedJobs: 20})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
login := httptest.NewRequest("POST", "/api/v1/auth/login", strings.NewReader(`{"username":"network-admin","password":"Network-regression-password-only"}`))
|
|
login.Header.Set("Origin", "http://localhost")
|
|
logged := httptest.NewRecorder()
|
|
s.ServeHTTP(logged, login)
|
|
if logged.Code != 200 {
|
|
t.Fatalf("login: %d %s", logged.Code, logged.Body)
|
|
}
|
|
var session struct {
|
|
CSRF string `json:"csrf_token"`
|
|
}
|
|
if err = json.Unmarshal(logged.Body.Bytes(), &session); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
request := func(path string, body any, status int, code string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
encoded, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req := httptest.NewRequest("POST", path, strings.NewReader(string(encoded)))
|
|
req.AddCookie(logged.Result().Cookies()[0])
|
|
req.Header.Set("Origin", "http://localhost")
|
|
req.Header.Set("X-CSRF-Token", session.CSRF)
|
|
res := httptest.NewRecorder()
|
|
s.ServeHTTP(res, req)
|
|
if res.Code != status {
|
|
t.Fatalf("%s: %d %s; want %d", path, res.Code, res.Body, status)
|
|
}
|
|
if code != "" {
|
|
var value struct {
|
|
Error struct {
|
|
Code string `json:"code"`
|
|
} `json:"error"`
|
|
}
|
|
if err := json.Unmarshal(res.Body.Bytes(), &value); err != nil || value.Error.Code != code {
|
|
t.Fatalf("unexpected error response: %s, %v", res.Body, err)
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
base := Settings{Internet: "online", Duration: 30, Filename: "original", Privilege: "admin", ArgsMode: "none", Args: []string{}}
|
|
for _, tc := range []struct {
|
|
name string
|
|
mode string
|
|
entries []string
|
|
}{
|
|
{"online missing", "online", nil},
|
|
{"online empty", "online", []string{}},
|
|
{"malformed", "online", []string{"example.com"}},
|
|
{"ipv6", "online", []string{"::ffff:1.1.1.1"}},
|
|
{"offline nonempty", "offline", []string{"1.1.1.1"}},
|
|
{"protected special", "online", []string{"127.0.0.1"}},
|
|
{"wildcard does not suppress rejection", "online", []string{"0.0.0.0/0", "169.254.1.1"}},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
settings := base
|
|
settings.Internet, settings.AllowedCIDRs = tc.mode, tc.entries
|
|
request("/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": settings}, 400, "invalid_settings")
|
|
})
|
|
}
|
|
var jobs int
|
|
if err = db.QueryRow(ctx, `SELECT count(*) FROM jobs`).Scan(&jobs); err != nil || jobs != 0 {
|
|
t.Fatalf("invalid submissions persisted jobs: %d, %v", jobs, err)
|
|
}
|
|
base.AllowedCIDRs = []string{" 1.1.1.1 ", "10.27.8.9/16", "0.0.0.0", "10.27.0.0/16", "1.1.1.1/32"}
|
|
created := request("/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": base}, 201, "")
|
|
var job struct {
|
|
ID string `json:"id"`
|
|
Settings Settings `json:"settings"`
|
|
}
|
|
if err = json.Unmarshal(created.Body.Bytes(), &job); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := []string{"1.1.1.1/32", "10.27.0.0/16", "0.0.0.0/0"}
|
|
if !slices.Equal(job.Settings.AllowedCIDRs, want) {
|
|
t.Fatalf("immutable policy not canonical or explicit LAN lost: %v", job.Settings.AllowedCIDRs)
|
|
}
|
|
if _, err = db.Exec(ctx, `UPDATE attempts SET phase='finished',outcome='error' WHERE run_id IN (SELECT id FROM runs WHERE job_id=$1)`, job.ID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, `UPDATE jobs SET status='failed' WHERE id=$1`, job.ID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// Old online jobs must fail before retry admission and never gain a wildcard.
|
|
if _, err = db.Exec(ctx, `UPDATE jobs SET settings=settings-'allowed_cidrs' WHERE id=$1`, job.ID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
request("/api/v1/jobs/"+job.ID+"/retry", map[string]any{}, 409, "invalid_settings")
|
|
var unfinished int
|
|
if err = db.QueryRow(ctx, `SELECT count(*) FROM attempts WHERE phase<>'finished'`).Scan(&unfinished); err != nil || unfinished != 0 {
|
|
t.Fatalf("legacy policy retry queued work: %d, %v", unfinished, err)
|
|
}
|
|
canonical, err := json.Marshal(job.Settings)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, `UPDATE jobs SET settings=$2 WHERE id=$1`, job.ID, canonical); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, `UPDATE profiles SET online_available=false WHERE id=$1`, profile); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
request("/api/v1/jobs/"+job.ID+"/retry", map[string]any{}, 409, "revision_unavailable")
|
|
if _, err = db.Exec(ctx, `UPDATE profiles SET online_available=true WHERE id=$1`, profile); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, expiry := range []string{"now()-interval '1 second'", "NULL"} {
|
|
if _, err = db.Exec(ctx, `UPDATE bindings SET online_ready=true,online_expires_at=`+expiry+` WHERE owner_id=$1`, owner); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
request("/api/v1/jobs/"+job.ID+"/retry", map[string]any{}, 409, "admission_closed")
|
|
request("/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": base}, 409, "admission_closed")
|
|
bindingsRequest := httptest.NewRequest("GET", "/api/v1/admin/bindings", nil)
|
|
bindingsRequest.AddCookie(logged.Result().Cookies()[0])
|
|
bindingsResponse := httptest.NewRecorder()
|
|
s.ServeHTTP(bindingsResponse, bindingsRequest)
|
|
var bindings struct {
|
|
Items []struct {
|
|
Configured bool `json:"configured"`
|
|
OnlineReady bool `json:"online_ready"`
|
|
} `json:"items"`
|
|
}
|
|
if err = json.Unmarshal(bindingsResponse.Body.Bytes(), &bindings); err != nil || bindingsResponse.Code != 200 || len(bindings.Items) != 1 || bindings.Items[0].OnlineReady || !bindings.Items[0].Configured {
|
|
t.Fatalf("stale online proof remained ready or disabled offline: %s, %v", bindingsResponse.Body, err)
|
|
}
|
|
}
|
|
if err = db.QueryRow(ctx, `SELECT count(*) FROM attempts WHERE phase<>'finished'`).Scan(&unfinished); err != nil || unfinished != 0 {
|
|
t.Fatalf("expired online proof queued work: %d, %v", unfinished, err)
|
|
}
|
|
offline := base
|
|
offline.Internet, offline.AllowedCIDRs = "offline", nil
|
|
request("/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": offline}, 201, "")
|
|
if _, err = db.Exec(ctx, `UPDATE attempts SET phase='finished',outcome='error' WHERE phase<>'finished'`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, `UPDATE bindings SET online_expires_at=now()+interval '1 hour' WHERE owner_id=$1`, owner); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
retried := request("/api/v1/jobs/"+job.ID+"/retry", map[string]any{}, 200, "")
|
|
if err = json.Unmarshal(retried.Body.Bytes(), &job); err != nil || !slices.Equal(job.Settings.AllowedCIDRs, want) {
|
|
t.Fatalf("retry changed immutable policy: %s, %v", retried.Body, err)
|
|
}
|
|
if err = db.QueryRow(ctx, `SELECT count(*) FROM attempts WHERE phase<>'finished'`).Scan(&unfinished); err != nil || unfinished != 1 {
|
|
t.Fatalf("valid policy retry failed to queue exactly one attempt: %d, %v", unfinished, err)
|
|
}
|
|
}
|