Enforce required per-job IPv4 allowlists with leased isolated network broker

This commit is contained in:
omar committed 2026-09-25 00:18:35 +03:00
1 parent b3373373e8
commit 32312548ea
24 files changed
+3059 -170

No files matched your search

+1 -1
View File
@@ -39,7 +39,7 @@ func (s *Server) adminRoutes() {
jsonResponse(w, 200, v)
}))
m.HandleFunc("GET /api/v1/admin/bindings", s.protected(true, func(w http.ResponseWriter, r *http.Request) {
s.list(w, r, `SELECT to_jsonb(b)||jsonb_build_object('configured',configured AND COALESCE(isolation_expires_at>now(),false),'reason',CASE WHEN configured AND NOT COALESCE(isolation_expires_at>now(),false) THEN 'Isolation proof expired or requires revalidation' ELSE reason END) FROM bindings b ORDER BY owner_id`)
s.list(w, r, `SELECT to_jsonb(b)||jsonb_build_object('configured',configured AND COALESCE(isolation_expires_at>now(),false),'reason',CASE WHEN configured AND NOT COALESCE(isolation_expires_at>now(),false) THEN 'Isolation proof expired or requires revalidation' ELSE reason END,'online_ready',online_ready AND COALESCE(online_expires_at>now(),false),'online_reason',CASE WHEN online_ready AND NOT COALESCE(online_expires_at>now(),false) THEN 'Online network proof expired or requires revalidation' ELSE online_reason END) FROM bindings b ORDER BY owner_id`)
}))
m.HandleFunc("GET /api/v1/admin/health", s.protected(true, s.health))
m.HandleFunc("GET /api/v1/admin/attempts/held", s.protected(true, s.heldAttempts))
+1 -1
View File
@@ -58,7 +58,7 @@ func TestJobSummariesIncludeAssignedProfile(t *testing.T) {
if _, err = db.Exec(ctx, `INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,'win11','fingerprint','config')`, revision, profile); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO jobs(id,owner_id,upload_id,execution_filename,status,settings) VALUES($1,$2,$3,'panel-bat-smoke.bat','completed','{}')`, job, owner, upload); err != nil {
if _, err = db.Exec(ctx, `INSERT INTO jobs(id,owner_id,upload_id,execution_filename,status,settings) VALUES($1,$2,$3,'panel-bat-smoke.bat','completed','{"internet":"offline"}')`, job, owner, upload); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name,status) SELECT $1,$2,id,$4,name,'completed' FROM profiles WHERE id=$3`, run, job, profile, revision); err != nil {
+28 -7
View File
@@ -17,12 +17,14 @@ import (
"github.com/jackc/pgx/v5"
"otche/internal/grub"
"otche/internal/netpolicy"
"otche/internal/pve"
"otche/internal/store"
)
type Settings struct {
Internet string `json:"internet"`
AllowedCIDRs []string `json:"allowed_cidrs,omitempty"`
Duration int `json:"duration_seconds"`
Filename string `json:"filename"`
Privilege string `json:"privilege"`
@@ -59,9 +61,11 @@ func (v *Settings) validate(filename string) error {
if err := grub.Validate(v.GrubPaths); err != nil {
return err
}
if v.Internet != "online" && v.Internet != "offline" {
return errors.New("internet must be online/offline")
allowed, err := netpolicy.Normalize(v.Internet, v.AllowedCIDRs)
if err != nil {
return err
}
v.AllowedCIDRs = allowed
ok := false
for _, d := range []int{30, 60, 90, 120, 180, 300, 600, 900, 1200} {
if v.Duration == d {
@@ -330,7 +334,7 @@ func (s *Server) createJob(w http.ResponseWriter, r *http.Request) {
fail(w, 400, "invalid_settings", e.Error())
return
}
if e = s.admit(r, tx, a.ID); e != nil {
if e = s.admit(r, tx, a.ID, in.Settings.Internet); e != nil {
fail(w, 409, "admission_closed", e.Error())
return
}
@@ -377,7 +381,7 @@ func (s *Server) createJob(w http.ResponseWriter, r *http.Request) {
}
s.respondJob(w, r, id, 201)
}
func (s *Server) admit(r *http.Request, tx pgx.Tx, owner string) error {
func (s *Server) admit(r *http.Request, tx pgx.Tx, owner, network string) error {
var id string
if e := tx.QueryRow(r.Context(), `SELECT id::text FROM users WHERE id=$1 FOR UPDATE`, owner).Scan(&id); e != nil {
return e
@@ -387,6 +391,13 @@ func (s *Server) admit(r *http.Request, tx pgx.Tx, owner string) error {
if e != nil || !configured {
return errors.New("Owner PVE isolation and credentials are not configured")
}
if network == "online" {
var onlineReady bool
e = tx.QueryRow(r.Context(), `SELECT online_ready AND COALESCE(online_expires_at>now(),false) FROM bindings WHERE owner_id=$1`, owner).Scan(&onlineReady)
if e != nil || !onlineReady {
return errors.New("Owner online network is unavailable or requires revalidation")
}
}
var workerReady bool
e = tx.QueryRow(r.Context(), `SELECT COALESCE(bool_or(ready AND seen_at>now()-interval '45 seconds'),false) FROM heartbeats WHERE name='worker'`).Scan(&workerReady)
if e != nil || !workerReady {
@@ -494,7 +505,8 @@ func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
}
defer tx.Rollback(r.Context())
var status, owner string
e = tx.QueryRow(r.Context(), `SELECT status,owner_id::text FROM jobs WHERE id=$1 FOR UPDATE`, id).Scan(&status, &owner)
var rawSettings json.RawMessage
e = tx.QueryRow(r.Context(), `SELECT status,owner_id::text,settings FROM jobs WHERE id=$1 FOR UPDATE`, id).Scan(&status, &owner, &rawSettings)
if e != nil {
s.dbError(w, e)
return
@@ -509,11 +521,20 @@ func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
fail(w, 409, "job_active", "An active job cannot be retried")
return
}
if e = s.admit(r, tx, owner); e != nil {
var settings Settings
if e = json.Unmarshal(rawSettings, &settings); e != nil {
fail(w, 409, "invalid_settings", "Stored job settings cannot be decoded; submit a new job")
return
}
if _, e = netpolicy.Normalize(settings.Internet, settings.AllowedCIDRs); e != nil {
fail(w, 409, "invalid_settings", "Stored network settings cannot be retried; submit a new job: "+e.Error())
return
}
if e = s.admit(r, tx, owner, settings.Internet); e != nil {
fail(w, 409, "admission_closed", e.Error())
return
}
rows, e := tx.Query(r.Context(), `SELECT r.id::text,p.enabled AND p.state='published' AND p.qualification='qualified' AND p.current_revision_id=r.revision_id FROM runs r JOIN profiles p ON p.id=r.profile_id WHERE r.job_id=$1 FOR SHARE OF p`, id)
rows, e := tx.Query(r.Context(), `SELECT r.id::text,p.enabled AND p.state='published' AND p.qualification='qualified' AND p.current_revision_id=r.revision_id AND ($2='offline' OR p.online_available) FROM runs r JOIN profiles p ON p.id=r.profile_id WHERE r.job_id=$1 FOR SHARE OF p`, id, settings.Internet)
if e != nil {
s.dbError(w, e)
return
+214
View File
@@ -0,0 +1,214 @@
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)
}
}