Spaces:
Sleeping

File size: 13,484 Bytes
0a855cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package httpapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/archnemix/archx-eval/relay/internal/bank"
	"github.com/archnemix/archx-eval/relay/internal/config"
	"github.com/archnemix/archx-eval/relay/internal/core"
	"github.com/archnemix/archx-eval/relay/internal/ratelog"
	"github.com/archnemix/archx-eval/relay/internal/reputation"
	"github.com/archnemix/archx-eval/relay/internal/store"
)

func newServer(t *testing.T, examples int) (*Server, *core.Service) {
	t.Helper()
	return newServerWith(t, examples, true)
}

// newServerWith builds a server whose loopback/private-address relaxation can
// be turned off, so the production posture is testable.
func newServerWith(t *testing.T, examples int, allowLoopback bool) (*Server, *core.Service) {
	t.Helper()
	dir := t.TempDir()
	bankDir := filepath.Join(dir, "bank")
	if err := os.MkdirAll(filepath.Join(bankDir, "python"), 0o750); err != nil {
		t.Fatal(err)
	}
	var b strings.Builder
	for i := 0; i < examples; i++ {
		fmt.Fprintf(&b, `{"id":"py-%03d","category":"python","difficulty":"easy","kind":"qa","prompt":"q%d","expected_answer":"secret-answer-%d","explanation":"hidden"}`+"\n", i, i, i)
	}
	if err := os.WriteFile(filepath.Join(bankDir, "python", "easy.jsonl"), []byte(b.String()), 0o640); err != nil {
		t.Fatal(err)
	}
	cfg := config.Config{
		BankDir: bankDir, DataDir: filepath.Join(dir, "data"),
		RateDir: filepath.Join(dir, "rate"),
		DrawMax: 75, StaleAfterUses: 3, Window: time.Hour,
		RateAllowance: 0.5, RateWindow: time.Minute, RateSample: time.Second, RateFloor: 10,
		BanWindow: 24 * time.Hour, MaxBan: 14 * 24 * time.Hour,
		FeedbackWindow: 24 * time.Hour, LedgerKeepDays: 7,
		SaltSecret: "test-salt", MaxBodyBytes: 1 << 20, AllowLoopback: allowLoopback,
		AccessToken: "test-access-token", MetricsToken: "metrics-token",
		NetWindow: time.Hour, NetMaxDraws: 1000,
		GlobalWindow: time.Hour, GlobalMax: 100000,
		RequestTimeout: 10 * time.Second,
	}
	st, err := store.Open(cfg.DataDir)
	if err != nil {
		t.Fatal(err)
	}
	bm, err := bank.Load(bankDir, 3)
	if err != nil {
		t.Fatal(err)
	}
	rep, _ := reputation.Load("")
	rates, err := ratelog.Open(cfg.RateDir, 96*time.Hour)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = rates.Close() })
	svc := core.New(cfg, st, bm, rep, rates)
	log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
	return New(cfg, svc, log, "admin-token"), svc
}

func post(t *testing.T, h http.Handler, path, body string) *httptest.ResponseRecorder {
	t.Helper()
	req := httptest.NewRequest(http.MethodPost, path, bytes.NewBufferString(body))
	req.RemoteAddr = "203.0.113.10:5555"
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer test-access-token")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

const drawBody = `{"categories":["python"],"size":5,"device":{"machine_id":"4c4c4544-0044-3510-8054-b4c04f4e4e32","disk_uuid":"9f1b2c3d4e5f60718293a4b5c6d7e8f9","os_family":"linux","arch":"x86_64"}}`

// drawnGrant is the subset of the draw response needed to build valid feedback.
type drawnGrant struct {
	RequestID  string `json:"request_id"`
	IdentityID string `json:"identity_id"`
	Examples   []struct {
		ID         string `json:"id"`
		Category   string `json:"category"`
		Difficulty string `json:"difficulty"`
	} `json:"examples"`
}

// drawFor performs a real draw, so feedback tests can report against ids that
// were actually issued. Verification makes a fabricated request id impossible
// to use, which is the point of the change.
func drawFor(t *testing.T, srv *Server, remoteAddr string) drawnGrant {
	t.Helper()
	req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
	req.RemoteAddr = remoteAddr + ":5555"
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer test-access-token")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != 200 {
		t.Fatalf("draw failed: %d %s", rec.Code, rec.Body)
	}
	var g drawnGrant
	if err := json.Unmarshal(rec.Body.Bytes(), &g); err != nil {
		t.Fatal(err)
	}
	return g
}

func TestDrawHappyPath(t *testing.T) {
	srv, _ := newServer(t, 20)
	rec := post(t, srv, "/v1/draw", drawBody)
	if rec.Code != 200 {
		t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body)
	}
	var out struct {
		Count    int              `json:"count"`
		Examples []map[string]any `json:"examples"`
		ByCat    map[string]int   `json:"by_category"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if out.Count != 5 || len(out.Examples) != 5 {
		t.Fatalf("expected 5 examples, got %d", out.Count)
	}
	if out.ByCat["python"] != 5 {
		t.Fatalf("bad by_category: %v", out.ByCat)
	}
}

func TestDrawNeverLeaksAnswers(t *testing.T) {
	srv, _ := newServer(t, 20)
	rec := post(t, srv, "/v1/draw", drawBody)
	body := rec.Body.String()
	for _, forbidden := range []string{"secret-answer", "hidden", "expected_answer", "explanation", "reference_solution"} {
		if strings.Contains(body, forbidden) {
			t.Fatalf("response leaked %q: %s", forbidden, body)
		}
	}
}

func TestDrawSetsRequestIDHeader(t *testing.T) {
	srv, _ := newServer(t, 10)
	rec := post(t, srv, "/v1/draw", drawBody)
	if rec.Header().Get("X-Request-Id") == "" {
		t.Fatal("expected an X-Request-Id header")
	}
	if got := rec.Header().Get("Cache-Control"); !strings.Contains(got, "no-store") {
		t.Fatalf("expected no-store cache header, got %q", got)
	}
}

// The draw body has no request_id field: the server mints the id. A client
// trying to supply one is told the body is not what this endpoint accepts,
// which is clearer than silently ignoring a field the caller thinks matters.
func TestDrawBodyMayNotCarryRequestID(t *testing.T) {
	srv, _ := newServer(t, 10)
	body := `{"request_id":"mine","categories":["python"],"size":1,` +
		`"device":{"machine_id":"4c4c4544-0044-3510-8054-b4c04f4e4e32",` +
		`"disk_uuid":"9f1b2c3d4e5f60718293a4b5c6d7e8f9","os_family":"linux","arch":"x86_64"}}`
	rec := post(t, srv, "/v1/draw", body)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected 400 for a body carrying request_id, got %d: %s", rec.Code, rec.Body)
	}
}

// The draw id must be the server's, and must match what the response reports.
func TestDrawIDIsMintedNotEchoed(t *testing.T) {
	srv, _ := newServer(t, 10)
	rec := post(t, srv, "/v1/draw", drawBody)
	if rec.Code != 200 {
		t.Fatalf("draw: %d %s", rec.Code, rec.Body)
	}
	var grant drawnGrant
	if err := json.Unmarshal(rec.Body.Bytes(), &grant); err != nil {
		t.Fatal(err)
	}
	if len(grant.RequestID) != 32 {
		t.Fatalf("expected a 32-char minted id, got %q", grant.RequestID)
	}
	// The transport header and the draw id are different values on purpose: one
	// correlating logs, the other keying the draw.
	if got := rec.Header().Get("X-Request-Id"); got == grant.RequestID {
		t.Fatal("the log correlation id must not be reused as the draw id")
	}
}

func TestSecondDrawGets429WithRetryAfter(t *testing.T) {
	srv, _ := newServer(t, 20)
	if rec := post(t, srv, "/v1/draw", drawBody); rec.Code != 200 {
		t.Fatalf("first: %d", rec.Code)
	}
	rec := post(t, srv, "/v1/draw", drawBody)
	if rec.Code != http.StatusTooManyRequests {
		t.Fatalf("expected 429, got %d: %s", rec.Code, rec.Body)
	}
	if rec.Header().Get("Retry-After") == "" {
		t.Fatal("expected a Retry-After header")
	}
	var out struct {
		Error struct {
			Code string `json:"code"`
		} `json:"error"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if out.Error.Code != "WINDOW_ACTIVE" {
		t.Fatalf("unexpected code %q", out.Error.Code)
	}
}

func TestMalformedJSONRejected(t *testing.T) {
	srv, _ := newServer(t, 10)
	rec := post(t, srv, "/v1/draw", `{"categories":`)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected 400, got %d", rec.Code)
	}
}

func TestUnknownFieldRejected(t *testing.T) {
	srv, _ := newServer(t, 10)
	rec := post(t, srv, "/v1/draw", `{"categories":["python"],"size":1,"surprise":true,"device":{"machine_id":"4c4c4544-0044-3510-8054-b4c04f4e4e32","disk_uuid":"9f1b2c3d4e5f60718293a4b5c6d7e8f9"}}`)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected 400 for unknown field, got %d", rec.Code)
	}
}

func TestOversizedBodyRejected(t *testing.T) {
	srv, _ := newServer(t, 10)
	big := strings.Repeat("a", 2<<20)
	rec := post(t, srv, "/v1/draw", `{"categories":["`+big+`"]}`)
	if rec.Code != http.StatusBadRequest && rec.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("expected rejection, got %d", rec.Code)
	}
}

func TestHealthReflectsBank(t *testing.T) {
	srv, _ := newServer(t, 7)
	req := httptest.NewRequest(http.MethodGet, "/health", nil)
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != 200 {
		t.Fatalf("expected 200, got %d", rec.Code)
	}
	var out map[string]any
	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
		t.Fatal(err)
	}
	if out["ok"] != true {
		t.Fatalf("expected ok true: %v", out)
	}
}

func TestHealthUnavailableWhenBankEmpty(t *testing.T) {
	srv, _ := newServer(t, 0)
	req := httptest.NewRequest(http.MethodGet, "/health", nil)
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != http.StatusServiceUnavailable {
		t.Fatalf("expected 503, got %d", rec.Code)
	}
}

func TestCategories(t *testing.T) {
	srv, _ := newServer(t, 3)
	req := httptest.NewRequest(http.MethodGet, "/v1/categories", nil)
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	var out struct {
		Categories []string `json:"categories"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
		t.Fatal(err)
	}
	if len(out.Categories) != 1 || out.Categories[0] != "python" {
		t.Fatalf("unexpected categories: %v", out.Categories)
	}
}

func TestAdminStaleRequiresToken(t *testing.T) {
	srv, _ := newServer(t, 5)
	req := httptest.NewRequest(http.MethodGet, "/v1/stale", nil)
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != http.StatusForbidden {
		t.Fatalf("expected 403 without token, got %d", rec.Code)
	}

	req = httptest.NewRequest(http.MethodGet, "/v1/stale", nil)
	req.Header.Set("Authorization", "Bearer admin-token")
	rec = httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != 200 {
		t.Fatalf("expected 200 with token, got %d: %s", rec.Code, rec.Body)
	}
}

// Feedback is now verified against the ledger, so this test does a real draw
// and reports against the ids that draw actually issued.
func TestFeedbackAcceptedAndScored(t *testing.T) {
	srv, _ := newServer(t, 5)

	grant := drawFor(t, srv, "203.0.113.10")
	if len(grant.Examples) < 2 {
		t.Fatalf("expected at least 2 examples, got %d", len(grant.Examples))
	}
	var items []string
	for i, ex := range grant.Examples {
		passed := i == 0
		score := 0
		if passed {
			score = 1
		}
		items = append(items, fmt.Sprintf(
			`{"example_id":%q,"category":%q,"difficulty":%q,"passed":%v,"score":%d}`,
			ex.ID, ex.Category, ex.Difficulty, passed, score))
	}
	body := fmt.Sprintf(`{"request_id":%q,"identity_id":%q,"model_id":"gpt-x","items":[%s]}`,
		grant.RequestID, grant.IdentityID, strings.Join(items, ","))

	rec := post(t, srv, "/v1/feedback", body)
	if rec.Code != 200 {
		t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body)
	}
	var out struct {
		Accepted bool `json:"accepted"`
		Summary  struct {
			Total  int     `json:"total"`
			Passed int     `json:"passed"`
			Score  float64 `json:"score"`
		} `json:"summary"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
		t.Fatal(err)
	}
	if !out.Accepted || out.Summary.Total != len(grant.Examples) || out.Summary.Passed != 1 {
		t.Fatalf("unexpected summary: %+v", out)
	}
}

func TestFeedbackRejectsBadInput(t *testing.T) {
	srv, _ := newServer(t, 5)
	if rec := post(t, srv, "/v1/feedback", `{"items":[{"example_id":"a"}]}`); rec.Code != 400 {
		t.Fatalf("expected 400 for missing model_id, got %d", rec.Code)
	}
	if rec := post(t, srv, "/v1/feedback", `{"model_id":"m","items":[]}`); rec.Code != 400 {
		t.Fatalf("expected 400 for empty items, got %d", rec.Code)
	}
}

func TestEraseRemovesRawOnly(t *testing.T) {
	srv, svc := newServer(t, 10)
	rec := post(t, srv, "/v1/draw", drawBody)
	var out struct {
		IdentityID string `json:"identity_id"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
		t.Fatal(err)
	}
	body := `{"identity_id":"` + out.IdentityID + `"}`
	req := httptest.NewRequest(http.MethodPost, "/v1/erase", bytes.NewBufferString(body))
	req.RemoteAddr = "203.0.113.10:5555"
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer admin-token")
	rec = httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != 200 {
		t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body)
	}
	if _, err := svc.Erase(out.IdentityID); err != nil {
		t.Fatalf("erase: %v", err)
	}
}

func TestIndexAnd404(t *testing.T) {
	srv, _ := newServer(t, 3)
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != 200 || !strings.Contains(rec.Body.String(), "archx-eval relay") {
		t.Fatalf("bad index: %d %s", rec.Code, rec.Body)
	}
	req = httptest.NewRequest(http.MethodGet, "/nope", nil)
	rec = httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != http.StatusNotFound {
		t.Fatalf("expected 404, got %d", rec.Code)
	}
}