Files
otche-backend/internal/api/auth_test.go
T
omar dfb285fc2e Run owner jobs in parallel with atomic reservations and harden recovery
Worker
- Per-owner max_active_attempts (default 1, <= concurrent) replaces the
  one-active-attempt-per-owner claim rule; claims fill free slots each tick
  in deterministic created_at/profile_name/id order and record claimed_at.
- Disk, memory and artifact reservations are admitted and inserted in one
  owner-locked transaction; clones reserve measured source disk bytes and
  source RAM plus overhead; pending clone storage and aggregate artifact
  headroom are accounted.
- nextid lock is released right after the allocation reservation; source
  lock waits follow the caller context (20 min ceiling) with specific text.
- Shared settleJobSQL for worker and watchdog; cancellation is reported as
  cancelled instead of failed/error.
- Safety deadline is refreshed when collection starts so the watchdog
  cannot take over a live collection.
- Evidence release continues past failures, keeps the original error and
  stops retrying until an admin re-requests.
- Job ISO media is reconciled after all attempts finish (fixes leaks and the
  parallel-finish race); readiness errors carry the last guest/transport
  cause and distinguish cancellation/lease loss.
- Watchdog prunes expired sessions, login limits and old orphan events;
  worker health events are throttled.

PVE client
- Bounded retries for idempotent GETs on transport errors/5xx only; task
  polling starts at 250 ms; task exitstatus is logged for operators;
  QGA file reads use 1 MiB chunks.

API/store
- Indexes for hot job/claim/quota queries; claimed_at column.
- Native UUID path comparisons with early 404; deterministic run ordering;
  queue_ahead; admin held-attempts listing; stale revision publish guard;
  retry refused while any attempt is unfinished.
- Uploads stream outside the DB transaction with a short locked quota
  recheck; explicit pool sizes; `otche healthcheck` CLI mode.

Recorder
- Network reads and FFmpeg writes happen outside the framebuffer lock;
  wall-clock frame pacing with bounded catch-up and explicit gaps; fsync at
  most once per second after the first durable fragment.

Windows runner
- UTC-safe timestamp parsing everywhere; readiness checks desktop first and
  computes the baseline once; per-nonce probe results; collector publishes
  initial telemetry immediately and reads event logs incrementally.
- Baseline records UAC, Smart App Control, Secure Boot and Device Guard
  registry state; installer stores the LSA secret last and gains read-only
  -Verify and signed -UpdateRunner maintenance modes.
2026-09-24 17:55:13 +03:00

160 lines
4.9 KiB
Go

package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"otche/internal/store"
)
// This integration test uses its own PostgreSQL schema and never a runtime adapter.
func TestAccountLoginLimitAndSessionRevocation(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)
}
password := "Regression-only-long-password"
for _, name := range []string{"first-user", "second-user"} {
if _, err = CreateUser(ctx, db, name, password, "operator"); err != nil {
t.Fatal(err)
}
}
s, err := New(db, Config{Origin: "http://localhost", ArtifactRoot: t.TempDir()})
if err != nil {
t.Fatal(err)
}
login := func(name, pass string) *httptest.ResponseRecorder {
body, _ := json.Marshal(map[string]string{"username": name, "password": pass})
r := httptest.NewRequest("POST", "/api/v1/auth/login", strings.NewReader(string(body)))
r.RemoteAddr = "172.20.0.2:80"
r.Header.Set("Origin", "http://localhost")
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
return w
}
var cookie *http.Cookie
for i := range 17 {
w := login("first-user", password)
if w.Code != 200 {
t.Fatalf("valid login %d locked out: %d %s", i, w.Code, w.Body)
}
cookie = w.Result().Cookies()[0]
}
for i := range 15 {
w := login("first-user", "wrong password")
if w.Code != 401 {
t.Fatalf("failed attempt %d: %d", i, w.Code)
}
}
if w := login("first-user", password); w.Code != 429 {
t.Fatalf("exhausted account should throttle, got %d", w.Code)
}
if w := login("second-user", password); w.Code != 200 {
t.Fatalf("shared proxy must not lock unrelated account: %d", w.Code)
}
if _, err = db.Exec(ctx, `UPDATE users SET disabled=true WHERE username='first-user'`); err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("GET", "/api/v1/auth/session", nil)
r.AddCookie(cookie)
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
if w.Code != 401 {
t.Fatalf("disabled user session retained access: %d", w.Code)
}
if _, err = db.Exec(ctx, `UPDATE users SET role='admin' WHERE username='second-user'`); err != nil {
t.Fatal(err)
}
elevated := login("second-user", password)
adminRequest := httptest.NewRequest("GET", "/api/v1/admin/users", nil)
adminRequest.AddCookie(elevated.Result().Cookies()[0])
before := httptest.NewRecorder()
s.ServeHTTP(before, adminRequest)
if before.Code != 200 {
t.Fatalf("admin access unavailable: %d", before.Code)
}
if _, err = db.Exec(ctx, `UPDATE users SET role='operator' WHERE username='second-user'`); err != nil {
t.Fatal(err)
}
after := httptest.NewRecorder()
s.ServeHTTP(after, adminRequest)
if after.Code != 403 {
t.Fatalf("demoted existing session retained admin: %d", after.Code)
}
db.Close()
w = httptest.NewRecorder()
s.ServeHTTP(w, r)
if w.Code != 500 {
t.Fatalf("database failure disguised as auth failure: %d", w.Code)
}
fmt.Fprintln(os.Stdout, "17 valid proxied logins; account failure throttling; unrelated user unaffected; revoked session denied; DB failure remains 500")
}
func TestInvalidUUIDPathsReturnNotFound(t *testing.T) {
s := &Server{mux: http.NewServeMux()}
s.routes()
for _, route := range []struct {
method string
path string
}{
{"GET", "/api/v1/jobs/not-a-uuid"},
{"POST", "/api/v1/jobs/not-a-uuid/retry"},
{"GET", "/api/v1/uploads/not-a-uuid/content"},
{"GET", "/api/v1/artifacts/not-a-uuid/content"},
{"GET", "/api/v1/attempts/not-a-uuid/video"},
{"PATCH", "/api/v1/admin/users/not-a-uuid"},
{"POST", "/api/v1/admin/profiles/not-a-uuid/publish"},
{"GET", "/api/v1/admin/profiles/not-a-uuid/revisions"},
{"GET", "/api/v1/admin/qualifications/not-a-uuid"},
{"POST", "/api/v1/admin/attempts/not-a-uuid/release-evidence"},
} {
t.Run(route.method+" "+route.path, func(t *testing.T) {
r := httptest.NewRequest(route.method, route.path, strings.NewReader(`{}`))
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
var body struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if w.Code != 404 || body.Error.Code != "not_found" {
t.Fatalf("invalid UUID: %d %s", w.Code, w.Body)
}
})
}
}