Files
otche-backend/internal/api/api_keys_test.go
T

439 lines
20 KiB
Go

package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"otche/internal/store"
)
// Real PostgreSQL and the actual HTTP router: credentials must not expand authority.
func TestAPIKeySecurityBoundary(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)
}
s, err := New(db, Config{Origin: "https://localhost", ArtifactRoot: t.TempDir()})
if err != nil {
t.Fatal(err)
}
exec := func(q string, args ...any) {
t.Helper()
if _, err := db.Exec(ctx, q, args...); err != nil {
t.Fatal(err)
}
}
type session struct{ id, token, csrf string }
makeUser := func(name, role string) session {
t.Helper()
v := session{store.NewID(), randomToken(), randomToken()}
exec(`INSERT INTO users(id,username,password_hash,role) VALUES($1,$2,'unused',$3)`, v.id, name, role)
exec(`INSERT INTO sessions(token_hash,user_id,csrf_token,expires_at) VALUES($1,$2,$3,now()+interval '1 hour')`, hashToken(v.token), v.id, v.csrf)
return v
}
owner := makeUser("key-admin", "admin")
other := makeUser("other-owner", "operator")
request := func(method, path, body string, ss *session, authorization *string, csrf bool) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, "/api/v1"+path, strings.NewReader(body))
if ss != nil {
r.AddCookie(&http.Cookie{Name: "otche_session", Value: ss.token})
if csrf {
r.Header.Set("Origin", "https://localhost")
r.Header.Set("X-CSRF-Token", ss.csrf)
}
}
if authorization != nil {
r.Header.Set("Authorization", *authorization)
}
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
return w
}
expect := func(w *httptest.ResponseRecorder, status int) {
t.Helper()
if w.Code != status {
t.Fatalf("expected HTTP %d got %d: %s", status, w.Code, w.Body)
}
}
type credential struct {
Key struct{ ID, Prefix string }
Token string
}
issue := func(ss session, scopes []string) credential {
t.Helper()
body, _ := json.Marshal(map[string]any{"name": "CI key", "expires_in_days": 90, "scopes": scopes})
w := request("POST", "/api-keys", string(body), &ss, nil, true)
expect(w, 201)
var c credential
if err := json.Unmarshal(w.Body.Bytes(), &c); err != nil {
t.Fatal(err)
}
return c
}
allScopes := []string{"profiles:read", "jobs:read", "jobs:write", "uploads:read", "uploads:write", "artifacts:read"}
key := issue(owner, allScopes)
bearer := "Bearer " + key.Token
if len(key.Token) != 70 || !strings.HasPrefix(key.Token, "otche_") {
t.Fatal("malformed issued credential")
}
var stored string
if err = db.QueryRow(ctx, `SELECT token_hash FROM api_keys WHERE id=$1`, key.Key.ID).Scan(&stored); err != nil {
t.Fatal(err)
}
if stored != hashToken(key.Token) || strings.Contains(stored, key.Token) {
t.Fatal("credential not stored as digest")
}
listed := request("GET", "/api-keys", "", &owner, nil, false)
expect(listed, 200)
if strings.Contains(listed.Body.String(), key.Token) || strings.Contains(listed.Body.String(), stored) || strings.Contains(listed.Body.String(), "token_hash") {
t.Fatal("credential leaked from list")
}
expect(request("GET", "/profiles", "", nil, &bearer, false), 200)
expect(request("HEAD", "/profiles", "", nil, &bearer, false), 200)
var used *time.Time
if err = db.QueryRow(ctx, `SELECT last_used_at FROM api_keys WHERE id=$1`, key.Key.ID).Scan(&used); err != nil || used == nil {
t.Fatal("successful authentication not recorded", err)
}
// Invalid explicit credentials never downgrade to an otherwise valid browser session.
for _, invalid := range []string{"", "Basic abc", "Bearer otche_bad", "Bearer " + strings.Repeat("0", 64)} {
expect(request("GET", "/profiles", "", &owner, &invalid, false), 401)
}
unknown := "Bearer otche_" + strings.Repeat("0", 64)
expect(request("GET", "/profiles", "", &owner, &unknown, false), 401)
duplicate := httptest.NewRequest("GET", "/api/v1/profiles", nil)
duplicate.Header.Add("Authorization", bearer)
duplicate.Header.Add("Authorization", bearer)
duplicateResponse := httptest.NewRecorder()
s.ServeHTTP(duplicateResponse, duplicate)
expect(duplicateResponse, 401)
expect(request("GET", "/profiles?api_key="+key.Token, "", nil, nil, false), 401)
for _, path := range []string{"/api-keys", "/auth/session", "/admin/users"} {
expect(request("GET", path, "", &owner, &bearer, false), 403)
}
expect(request("POST", "/auth/login", `{}`, nil, &bearer, false), 403)
expect(request("POST", "/auth/logout", `{}`, &owner, &bearer, true), 403)
expect(request("POST", "/api-keys", `{}`, &owner, nil, false), 403)
for _, origin := range []string{"https://localhost", "https://foreign.invalid"} {
r := httptest.NewRequest("DELETE", "/api/v1/api-keys/"+key.Key.ID, nil)
r.AddCookie(&http.Cookie{Name: "otche_session", Value: owner.token})
r.Header.Set("Origin", origin)
r.Header.Set("X-CSRF-Token", "wrong")
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
expect(w, 403)
}
expect(request("DELETE", "/api-keys/"+key.Key.ID, "", &other, nil, true), 404)
readOnly := issue(owner, []string{"profiles:read"})
readBearer := "Bearer " + readOnly.Token
expect(request("GET", "/jobs", "", nil, &readBearer, false), 403)
expect(request("POST", "/uploads", "", nil, &readBearer, false), 403)
expect(request("POST", "/jobs", `{}`, nil, &readBearer, false), 403)
expect(request("POST", "/api-keys", `{}`, nil, &readBearer, false), 403)
writeOnly := issue(owner, []string{"jobs:write"})
writeBearer := "Bearer " + writeOnly.Token
expect(request("GET", "/jobs", "", nil, &writeBearer, false), 403)
// A scoped write reaches normal validation without cookie Origin/CSRF.
expect(request("POST", "/jobs", `{}`, nil, &writeBearer, false), 400)
missingID := store.NewID()
for _, granted := range allScopes {
limited := issue(owner, []string{granted})
authorization := "Bearer " + limited.Token
for _, endpoint := range []struct {
method, path, scope string
status int
}{
{"GET", "/profiles", "profiles:read", 200},
{"GET", "/dashboard", "jobs:read", 200},
{"GET", "/jobs", "jobs:read", 200},
{"GET", "/jobs/" + missingID, "jobs:read", 404},
{"GET", "/jobs/" + missingID + "/events", "jobs:read", 404},
{"POST", "/jobs", "jobs:write", 400},
{"POST", "/jobs/" + missingID + "/cancel", "jobs:write", 404},
{"POST", "/jobs/" + missingID + "/retry", "jobs:write", 404},
{"POST", "/uploads", "uploads:write", 400},
{"GET", "/uploads/" + missingID + "/content", "uploads:read", 404},
{"GET", "/jobs/" + missingID + "/artifacts", "artifacts:read", 404},
{"GET", "/artifacts/" + missingID + "/content", "artifacts:read", 404},
{"GET", "/attempts/" + missingID + "/video", "artifacts:read", 404},
} {
want := 403
if endpoint.scope == granted {
want = endpoint.status
}
t.Run(granted+"/"+endpoint.method+endpoint.path, func(t *testing.T) {
w := request(endpoint.method, endpoint.path, `{}`, nil, &authorization, false)
if w.Code != want {
t.Fatalf("scope boundary: expected%d got%d %s", want, w.Code, w.Body)
}
})
}
}
for _, body := range []string{
`{"name":"bad","expires_in_days":0,"scopes":["jobs:read"]}`,
`{"name":"bad","expires_in_days":366,"scopes":["jobs:read"]}`,
`{"name":"bad","expires_in_days":1,"scopes":[]}`,
`{"name":"bad","expires_in_days":1,"scopes":["admin"]}`,
`{"name":"bad","expires_in_days":1,"scopes":["jobs:read","jobs:read"]}`,
`{"name":"bad\u0000","expires_in_days":1,"scopes":["jobs:read"]}`,
} {
expect(request("POST", "/api-keys", body, &owner, nil, true), 400)
}
// Seed two owners' completed observations, including private downloadable artifacts.
makeJob := func(ss session) (string, string, string, string) {
upload, job, run, attempt, profile, revision, artifact := store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID()
exec(`INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1::uuid,$2,'sample.exe',4,'digest',$1::uuid::text)`, upload, ss.id)
exec(`INSERT INTO jobs(id,owner_id,upload_id,execution_filename,settings,status) VALUES($1,$2,$3,'sample.exe','{}','finished')`, job, ss.id, upload)
exec(`INSERT INTO profiles(id,name,os,architecture) VALUES($1,'Windows test','windows','x64')`, profile)
exec(`INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,'source','fingerprint','digest')`, revision, profile)
exec(`INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name,status) VALUES($1,$2,$3,$4,'Windows test','finished')`, run, job, profile, revision)
exec(`INSERT INTO attempts(id,run_id,command_id,phase) VALUES($1,$2,$3,'finished')`, attempt, run, store.NewID())
exec(`INSERT INTO artifacts(id,job_id,attempt_id,kind,filename,content_type,size,sha256,storage_key) VALUES($1::uuid,$2,$3,'report','report.json','application/json',4,'digest',$1::uuid::text)`, artifact, job, attempt)
if err := os.WriteFile(s.cfg.ArtifactRoot+"/"+upload, []byte("data"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(s.cfg.ArtifactRoot+"/"+artifact, []byte("data"), 0600); err != nil {
t.Fatal(err)
}
return job, upload, artifact, attempt
}
ownJob, ownUpload, ownArtifact, _ := makeJob(owner)
foreignJob, foreignUpload, foreignArtifact, foreignAttempt := makeJob(other)
for _, path := range []string{"/jobs/" + ownJob, "/uploads/" + ownUpload + "/content", "/artifacts/" + ownArtifact + "/content"} {
expect(request("GET", path, "", nil, &bearer, false), 200)
}
for _, path := range []string{"/jobs/" + foreignJob, "/jobs/" + foreignJob + "/events", "/jobs/" + foreignJob + "/artifacts", "/uploads/" + foreignUpload + "/content", "/artifacts/" + foreignArtifact + "/content", "/attempts/" + foreignAttempt + "/video"} {
expect(request("GET", path, "", nil, &bearer, false), 404)
}
for _, suffix := range []string{"/cancel", "/retry"} {
expect(request("POST", "/jobs/"+foreignJob+suffix, `{}`, nil, &bearer, false), 404)
}
list := request("GET", "/jobs", "", nil, &bearer, false)
expect(list, 200)
if !strings.Contains(list.Body.String(), ownJob) || strings.Contains(list.Body.String(), foreignJob) {
t.Fatal("admin-owned key escaped owner isolation")
}
// Browser administrator access remains unchanged.
expect(request("GET", "/jobs/"+foreignJob, "", &owner, nil, false), 200)
writeCancel := request("POST", "/jobs/"+ownJob+"/cancel", `{}`, nil, &writeBearer, false)
expect(writeCancel, 200)
var acknowledgment map[string]any
if err := json.Unmarshal(writeCancel.Body.Bytes(), &acknowledgment); err != nil {
t.Fatal(err)
}
if len(acknowledgment) != 3 || acknowledgment["id"] != ownJob || acknowledgment["status"] != "finished" || acknowledgment["cancel_requested"] != false {
t.Fatal("write-only cancel leaked report instead of acknowledgment", writeCancel.Body)
}
// Exercise the automation protocol through the real handlers, not fixture echoes.
uploadRequest := httptest.NewRequest("POST", "/api/v1/uploads", strings.NewReader("harmless integration fixture"))
uploadRequest.Header.Set("Authorization", bearer)
uploadRequest.Header.Set("X-Filename", "integration.exe")
uploadResponse := httptest.NewRecorder()
s.ServeHTTP(uploadResponse, uploadRequest)
expect(uploadResponse, 201)
var uploaded struct{ ID, SHA256 string }
if err := json.Unmarshal(uploadResponse.Body.Bytes(), &uploaded); err != nil {
t.Fatal(err)
}
if uploaded.SHA256 != hashToken("harmless integration fixture") {
t.Fatal("upload digest mismatch")
}
downloaded := request("GET", "/uploads/"+uploaded.ID+"/content", "", nil, &bearer, false)
expect(downloaded, 200)
if downloaded.Body.String() != "harmless integration fixture" {
t.Fatal("uploaded content changed")
}
var profileID string
if err := db.QueryRow(ctx, `SELECT profile_id::text FROM runs WHERE job_id=$1`, ownJob).Scan(&profileID); err != nil {
t.Fatal(err)
}
settings := `{"internet":"offline","duration_seconds":30,"filename":"original","privilege":"user","args_mode":"none","args":[],"set_zoneid":false}`
jobInput := fmt.Sprintf(`{"upload_id":%q,"profile_ids":[%q],"settings":%s}`, uploaded.ID, profileID, settings)
expect(request("POST", "/jobs", jobInput, nil, &bearer, false), 409)
exec(`INSERT INTO bindings(owner_id,pool,iso_storage,disk_storage,node,configured,isolation_expires_at) VALUES($1,'test','test','test','test',true,now()+interval '1 hour')`, owner.id)
exec(`INSERT INTO heartbeats(name,seen_at,ready) VALUES('worker',now(),true)`)
// Credentials do not bypass qualification, even for administrator-owned keys.
expect(request("POST", "/jobs", jobInput, nil, &bearer, false), 409)
exec(`UPDATE profiles SET enabled=true,state='published',qualification='qualified',current_revision_id=(SELECT id FROM revisions WHERE profile_id=$1) WHERE id=$1`, profileID)
createdJob := request("POST", "/jobs", jobInput, nil, &writeBearer, false)
expect(createdJob, 201)
acknowledgment = nil
if err := json.Unmarshal(createdJob.Body.Bytes(), &acknowledgment); err != nil || len(acknowledgment) != 3 || acknowledgment["status"] != "queued" {
t.Fatal("write-only create leaked report", err, createdJob.Body)
}
createdJob = request("GET", "/jobs/"+acknowledgment["id"].(string), "", nil, &bearer, false)
expect(createdJob, 200)
var admitted struct {
ID string
CancelRequested bool `json:"cancel_requested"`
Runs []struct {
ProfileName string `json:"profile_name"`
Attempts []struct{ ID string }
}
}
if err := json.Unmarshal(createdJob.Body.Bytes(), &admitted); err != nil {
t.Fatal(err)
}
if len(admitted.Runs) != 1 || admitted.Runs[0].ProfileName != "Windows test" || len(admitted.Runs[0].Attempts) != 1 {
t.Fatal("admission did not snapshot selected source")
}
for _, path := range []string{"/dashboard", "/jobs/" + admitted.ID + "/events", "/jobs/" + admitted.ID + "/artifacts", "/attempts/" + admitted.Runs[0].Attempts[0].ID + "/video"} {
expect(request("GET", path, "", nil, &bearer, false), 200)
}
expect(request("POST", "/jobs/"+admitted.ID+"/retry", `{}`, nil, &bearer, false), 409)
canceled := request("POST", "/jobs/"+admitted.ID+"/cancel", `{}`, nil, &bearer, false)
expect(canceled, 200)
if err := json.Unmarshal(canceled.Body.Bytes(), &admitted); err != nil || !admitted.CancelRequested {
t.Fatal("cancel not observable", err)
}
exec(`UPDATE attempts SET phase='finished' WHERE run_id IN(SELECT id FROM runs WHERE job_id=$1)`, admitted.ID)
exec(`UPDATE jobs SET status='finished' WHERE id=$1`, admitted.ID)
retried := request("POST", "/jobs/"+admitted.ID+"/retry", `{}`, nil, &writeBearer, false)
expect(retried, 200)
acknowledgment = nil
if err := json.Unmarshal(retried.Body.Bytes(), &acknowledgment); err != nil || len(acknowledgment) != 3 || acknowledgment["status"] != "queued" || acknowledgment["cancel_requested"] != false {
t.Fatal("write-only retry leaked report", err, retried.Body)
}
retried = request("GET", "/jobs/"+admitted.ID, "", nil, &bearer, false)
expect(retried, 200)
if err := json.Unmarshal(retried.Body.Bytes(), &admitted); err != nil || admitted.CancelRequested || len(admitted.Runs[0].Attempts) != 2 {
t.Fatal("retry did not create a fresh attempt", err)
}
// A newly expired isolation proof closes admission for keys too.
exec(`UPDATE bindings SET isolation_expires_at=now()-interval '1 second' WHERE owner_id=$1`, owner.id)
expect(request("POST", "/jobs", jobInput, nil, &bearer, false), 409)
expect(request("DELETE", "/api-keys/"+key.Key.ID, "", &owner, nil, true), 204)
expect(request("DELETE", "/api-keys/"+key.Key.ID, "", &owner, nil, true), 204)
expect(request("GET", "/profiles", "", nil, &bearer, false), 401)
exec(`UPDATE api_keys SET created_at=now()-interval '2 days',expires_at=now()-interval '1 day' WHERE id=$1`, readOnly.Key.ID)
expect(request("GET", "/profiles", "", nil, &readBearer, false), 401)
// Disabling and then reenabling via the real admin API cannot resurrect keys.
otherKey := issue(other, []string{"profiles:read"})
otherBearer := "Bearer " + otherKey.Token
expect(request("PATCH", "/admin/users/"+other.id, `{"disabled":true}`, &owner, nil, true), 200)
expect(request("GET", "/profiles", "", nil, &otherBearer, false), 401)
expect(request("PATCH", "/admin/users/"+other.id, `{"disabled":false}`, &owner, nil, true), 200)
expect(request("GET", "/profiles", "", nil, &otherBearer, false), 401)
// Reestablish a session after the admin mutation to issue a replacement.
exec(`INSERT INTO sessions(token_hash,user_id,csrf_token,expires_at) VALUES($1,$2,$3,now()+interval '1 hour')`, hashToken(other.token), other.id, other.csrf)
replacement := issue(other, []string{"profiles:read"})
replacementBearer := "Bearer " + replacement.Token
expect(request("PATCH", "/admin/users/"+other.id, `{"password":"New-regression-only-password"}`, &owner, nil, true), 200)
expect(request("GET", "/profiles", "", nil, &replacementBearer, false), 401)
// Hold the same users lock as password reset, then let an authenticated issuance wait.
racing := makeUser("reset-race", "operator")
reset, err := db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer reset.Rollback(ctx)
if _, err = reset.Exec(ctx, `UPDATE users SET password_hash='reset' WHERE id=$1`, racing.id); err != nil {
t.Fatal(err)
}
if _, err = reset.Exec(ctx, `DELETE FROM sessions WHERE user_id=$1`, racing.id); err != nil {
t.Fatal(err)
}
if _, err = reset.Exec(ctx, `UPDATE api_keys SET revoked_at=now() WHERE owner_id=$1`, racing.id); err != nil {
t.Fatal(err)
}
issued := make(chan *httptest.ResponseRecorder, 1)
go func() {
issued <- request("POST", "/api-keys", `{"name":"race","scopes":["profiles:read"],"expires_in_days":1}`, &racing, nil, true)
}()
deadline := time.Now().Add(5 * time.Second)
for {
var waiting bool
if err = db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid<>pg_backend_pid() AND wait_event_type='Lock' AND query LIKE 'SELECT id::text FROM users WHERE id=$1 AND NOT disabled FOR UPDATE%')`).Scan(&waiting); err != nil {
t.Fatal(err)
}
if waiting {
break
}
if time.Now().After(deadline) {
t.Fatal("issuance did not reach owner lock")
}
time.Sleep(5 * time.Millisecond)
}
if err = reset.Commit(ctx); err != nil {
t.Fatal(err)
}
select {
case w := <-issued:
expect(w, 401)
case <-time.After(5 * time.Second):
t.Fatal("issuance did not unblock")
}
var survivors int
if err = db.QueryRow(ctx, `SELECT count(*) FROM api_keys WHERE owner_id=$1 AND revoked_at IS NULL`, racing.id).Scan(&survivors); err != nil || survivors != 0 {
t.Fatal("key survived session reset", survivors, err)
}
// Concurrent issuance shares the owner lock, not a racy count-then-insert.
capped := makeUser("concurrent-owner", "operator")
statuses := make(chan int, 24)
var wg sync.WaitGroup
for range 24 {
wg.Add(1)
go func() {
defer wg.Done()
statuses <- request("POST", "/api-keys", `{"name":"parallel","expires_in_days":1,"scopes":["profiles:read"]}`, &capped, nil, true).Code
}()
}
wg.Wait()
close(statuses)
created, limited := 0, 0
for status := range statuses {
switch status {
case 201:
created++
case 409:
limited++
default:
t.Fatalf("unexpected concurrent issue status %d", status)
}
}
if created != 20 || limited != 4 {
t.Fatalf("cap race: created=%d limited=%d", created, limited)
}
var cappedID string
if err := db.QueryRow(ctx, `SELECT id::text FROM api_keys WHERE owner_id=$1 LIMIT 1`, capped.id).Scan(&cappedID); err != nil {
t.Fatal(err)
}
expect(request("DELETE", "/api-keys/"+cappedID, "", &capped, nil, true), 204)
issue(capped, []string{"profiles:read"})
db.Close()
expect(request("GET", "/profiles", "", nil, &writeBearer, false), 500)
fmt.Println("API keys: scopes, owner isolation, expiry/revocation, credential precedence, session CSRF, account resets, concurrent cap and database failure verified")
}