Spaces:
Sleeping

File size: 10,479 Bytes
d8e884c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package httpapi

import (
	"bytes"
	"encoding/json"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/archnemix/archx-eval/relay/internal/identity"
)

// --- authentication -------------------------------------------------------

func TestDrawRequiresToken(t *testing.T) {
	srv, _ := newServer(t, 20)
	req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
	req.RemoteAddr = "203.0.113.10:5555"
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != http.StatusForbidden {
		t.Fatalf("expected 403 without a token, got %d", rec.Code)
	}
}

func TestDrawRejectsWrongToken(t *testing.T) {
	srv, _ := newServer(t, 20)
	req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
	req.RemoteAddr = "203.0.113.10:5555"
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer nope")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != http.StatusForbidden {
		t.Fatalf("expected 403, got %d", rec.Code)
	}
}

func TestDrawAcceptsAlternateTokenHeader(t *testing.T) {
	srv, _ := newServer(t, 20)
	req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
	req.RemoteAddr = "203.0.113.10:5555"
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Access-Token", "test-access-token")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != 200 {
		t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body)
	}
}

// --- transport hardening --------------------------------------------------

func TestSecurityHeadersPresent(t *testing.T) {
	srv, _ := newServer(t, 10)
	req := httptest.NewRequest(http.MethodGet, "/health", nil)
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)

	want := map[string]string{
		"X-Content-Type-Options":       "nosniff",
		"X-Frame-Options":              "DENY",
		"Referrer-Policy":              "no-referrer",
		"Cross-Origin-Resource-Policy": "same-origin",
		"Strict-Transport-Security":    "max-age=31536000; includeSubDomains",
	}
	for k, v := range want {
		if got := rec.Header().Get(k); got != v {
			t.Fatalf("header %s = %q, want %q", k, got, v)
		}
	}
	if csp := rec.Header().Get("Content-Security-Policy"); !strings.Contains(csp, "default-src 'none'") {
		t.Fatalf("weak CSP: %q", csp)
	}
}

func TestNonJSONContentTypeRejected(t *testing.T) {
	srv, _ := newServer(t, 10)
	req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
	req.RemoteAddr = "203.0.113.10:5555"
	req.Header.Set("Authorization", "Bearer test-access-token")
	req.Header.Set("Content-Type", "text/plain")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected 400 for wrong content type, got %d", rec.Code)
	}
}

func TestOversizedBodyRejectedBeforeParsing(t *testing.T) {
	srv, _ := newServer(t, 10)
	huge := strings.Repeat("x", 3<<20)
	req := httptest.NewRequest(http.MethodPost, "/v1/draw", strings.NewReader(`{"categories":["`+huge+`"]}`))
	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()
	srv.ServeHTTP(rec, req)
	if rec.Code != http.StatusBadRequest && rec.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("expected body rejection, got %d", rec.Code)
	}
}

func TestClientRequestIDCannotBeUnbounded(t *testing.T) {
	srv, _ := newServer(t, 10)
	req := httptest.NewRequest(http.MethodGet, "/health", nil)
	req.Header.Set("X-Request-Id", strings.Repeat("a", 500))
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	got := rec.Header().Get("X-Request-Id")
	if len(got) > 64 {
		t.Fatalf("client-supplied request id echoed unbounded: %d chars", len(got))
	}
}

// --- proxy / rate-limit bypass --------------------------------------------

func TestSpoofedForwardedForDoesNotBypassWindow(t *testing.T) {
	srv, _ := newServer(t, 50)
	if rec := post(t, srv, "/v1/draw", drawBody); rec.Code != 200 {
		t.Fatalf("first draw: %d", rec.Code)
	}
	// A classic bypass attempt: keep the same device but claim a fresh IP each
	// time. The marker set must still recognise the caller.
	for i := 0; i < 5; i++ {
		ip := "198.51." + string(rune('1'+i)) + ".77"
		req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
		req.RemoteAddr = "203.0.113.10:5555"
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Authorization", "Bearer test-access-token")
		req.Header.Set(identity.HeaderForwardedFor, ip+", 10.0.0.1")
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, req)
		if rec.Code == 200 {
			t.Fatalf("spoofed X-Forwarded-For granted a second draw")
		}
	}
}

func TestPrivateClientAddressRefused(t *testing.T) {
	// Production posture: loopback and RFC1918 clients are refused, because a
	// private address on a public request cannot be attributed or limited.
	srv, _ := newServerWith(t, 50, false)
	req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
	req.RemoteAddr = "10.1.2.3: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 != http.StatusForbidden {
		t.Fatalf("expected private address to be refused, got %d: %s", rec.Code, rec.Body)
	}
}

// --- input abuse ----------------------------------------------------------

func TestCategoryFloodRejected(t *testing.T) {
	srv, _ := newServer(t, 20)
	cats := make([]string, 40)
	for i := range cats {
		cats[i] = "python"
	}
	payload, _ := json.Marshal(map[string]any{
		"categories": cats,
		"size":       1,
		"device": map[string]any{
			"machine_id": "4c4c4544-0044-3510-8054-b4c04f4e4e32",
			"disk_uuid":  "9f1b2c3d4e5f60718293a4b5c6d7e8f9",
		},
	})
	rec := post(t, srv, "/v1/draw", string(payload))
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected category flood to be rejected, got %d", rec.Code)
	}
}

func TestFeedbackCannotBeUsedAsFreeStorage(t *testing.T) {
	srv, _ := newServer(t, 10)
	huge := strings.Repeat("A", 100<<10)
	body, _ := json.Marshal(map[string]any{
		"model_id": "m",
		"items": []map[string]any{{
			"example_id": "py-000", "category": "python", "difficulty": "easy",
			"passed": true, "score": 1, "code": huge,
		}},
	})
	rec := post(t, srv, "/v1/feedback", string(body))
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected oversize code to be rejected, got %d", rec.Code)
	}
}

func TestErrorResponsesDoNotLeakInternals(t *testing.T) {
	srv, _ := newServer(t, 10)
	// Unknown category produces an error; it must not mention files or types.
	rec := post(t, srv, "/v1/draw", `{"categories":["nope"],"size":1,"device":{"machine_id":"4c4c4544-0044-3510-8054-b4c04f4e4e32","disk_uuid":"9f1b2c3d4e5f60718293a4b5c6d7e8f9"}}`)
	body := strings.ToLower(rec.Body.String())
	for _, bad := range []string{"/home/", "goroutine", "panic", ".go:", "sql", "stack"} {
		if strings.Contains(body, bad) {
			t.Fatalf("error response leaked %q: %s", bad, rec.Body)
		}
	}
}

// --- privacy --------------------------------------------------------------

// The HTTP layer must never log or echo a raw client address. Behind a proxy
// the socket address is the proxy's, which is harmless, but with
// TRUSTED_PROXY_HOPS=0 it is the caller's real address.
func TestAccessLogContainsNoRawAddress(t *testing.T) {
	var buf bytes.Buffer
	log := slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))

	srv, _ := newServerWith(t, 20, true)
	srv.log = log

	req := httptest.NewRequest(http.MethodPost, "/v1/draw", bytes.NewBufferString(drawBody))
	req.RemoteAddr = "198.51.100.7:5555"
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer test-access-token")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)

	out := buf.String()
	if out == "" {
		t.Fatal("expected the request to be logged")
	}
	if strings.Contains(out, "198.51.100.7") {
		t.Fatalf("access log leaked a client address: %s", out)
	}
}

func TestEraseReportsNoPersonalData(t *testing.T) {
	srv, _ := 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", rec.Code)
	}
	var resp struct {
		Known  bool   `json:"identity_known"`
		Erased bool   `json:"erased"`
		Detail string `json:"detail"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatal(err)
	}
	if !resp.Known || resp.Erased {
		t.Fatalf("unexpected erase response: %+v", resp)
	}
	if !strings.Contains(resp.Detail, "salted hashes") {
		t.Fatalf("detail should explain why nothing was erased: %q", resp.Detail)
	}
}

// --- metrics --------------------------------------------------------------

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

	req = httptest.NewRequest(http.MethodGet, "/metrics", nil)
	req.Header.Set("Authorization", "Bearer metrics-token")
	rec = httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != 200 {
		t.Fatalf("expected 200 with metrics token, got %d", rec.Code)
	}
	if !strings.Contains(rec.Body.String(), "archx_bank_examples_total") {
		t.Fatalf("metrics body missing expected series: %s", rec.Body)
	}
}

func TestMetricsDisabledWhenUnset(t *testing.T) {
	srv, _ := newServer(t, 10)
	srv.metrics = ""
	req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
	req.Header.Set("Authorization", "Bearer anything")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, req)
	if rec.Code != http.StatusForbidden {
		t.Fatalf("expected metrics to be disabled, got %d", rec.Code)
	}
}