Spaces:
Sleeping

File size: 7,840 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
package core

import (
	"bytes"
	"context"
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"

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

// recordingRemote captures published paths and content for assertions.
type recordingRemote struct {
	mu      sync.Mutex
	written map[string][]byte
}

func newRecorder() *recordingRemote {
	return &recordingRemote{written: map[string][]byte{}}
}

func (r *recordingRemote) List(context.Context, string) ([]hf.RemoteFile, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	out := make([]hf.RemoteFile, 0, len(r.written))
	for p, c := range r.written {
		out = append(out, hf.RemoteFile{Path: p, Version: hf.BlobSHA(c)})
	}
	return out, nil
}

func (r *recordingRemote) Publish(_ context.Context, _ string, files []hf.File) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	for _, f := range files {
		r.written[f.Path] = f.Content
	}
	return nil
}

func (r *recordingRemote) Download(_ context.Context, p string) ([]byte, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	return r.written[p], nil
}

func (r *recordingRemote) snapshot() map[string][]byte {
	r.mu.Lock()
	defer r.mu.Unlock()
	out := make(map[string][]byte, len(r.written))
	for k, v := range r.written {
		out[k] = v
	}
	return out
}

func attachRecorder(t *testing.T, h *harness) *recordingRemote {
	t.Helper()
	remote := newRecorder()
	sc := syncctl.New(syncctl.Config{
		Interval:  time.Hour, // never fires on its own in tests
		MaxFiles:  100,
		MaxQueued: 10000,
	}, remote, nil)
	h.svc.WithSync(sc)
	t.Cleanup(func() {
		_ = sc.FlushNow(context.Background())
	})
	return remote
}

// The dataset must receive hashes, never raw identifiers.
func TestDatasetReceivesNoRawIdentity(t *testing.T) {
	h := newHarness(t, 50)
	remote := attachRecorder(t, h)

	if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
		t.Fatalf("draw: %v", err)
	}
	if err := h.svc.SyncFlush(context.Background()); err != nil {
		t.Fatalf("flush: %v", err)
	}

	published := remote.snapshot()
	if len(published) == 0 {
		t.Fatal("nothing was published")
	}
	for path, content := range published {
		if strings.HasPrefix(path, "raw/") {
			t.Fatalf("raw identity row published to the dataset at %s", path)
		}
		for _, secret := range []string{"203.0.113.10", machA, diskA} {
			if strings.Contains(string(content), secret) {
				t.Fatalf("%s leaked %q to the dataset", path, secret)
			}
		}
	}
}

func TestDatasetReceivesHashedRecord(t *testing.T) {
	h := newHarness(t, 50)
	remote := attachRecorder(t, h)

	grant, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA))
	if err != nil {
		t.Fatal(err)
	}
	if err := h.svc.SyncFlush(context.Background()); err != nil {
		t.Fatal(err)
	}

	published := remote.snapshot()
	var found []byte
	for path, content := range published {
		if strings.HasPrefix(path, "identities/") && strings.Contains(path, grant.IdentityID) {
			found = content
		}
	}
	if found == nil {
		t.Fatalf("expected the hashed record for %s, published: %v", grant.IdentityID, keys(published))
	}
	var rec map[string]any
	if err := json.Unmarshal(found, &rec); err != nil {
		t.Fatalf("published record is not valid JSON: %v", err)
	}
	if rec["id"] != grant.IdentityID {
		t.Fatalf("unexpected record id: %v", rec["id"])
	}
}

func TestDatasetReceivesEventLog(t *testing.T) {
	h := newHarness(t, 50)
	remote := attachRecorder(t, h)

	if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
		t.Fatal(err)
	}
	if err := h.svc.SyncFlush(context.Background()); err != nil {
		t.Fatal(err)
	}

	var events []byte
	for path, content := range remote.snapshot() {
		if strings.HasPrefix(path, "events/") {
			events = append(events, content...)
		}
	}
	if len(events) == 0 {
		t.Fatal("expected an event log to be published")
	}
	if !strings.Contains(string(events), `"decision":"allow"`) {
		t.Fatalf("event log missing the allow decision: %s", events)
	}
	// The event log must carry hashes only.
	if strings.Contains(string(events), "203.0.113.10") {
		t.Fatal("event log leaked a raw IP")
	}
}

func TestSyncEnqueueNeverBlocksDraw(t *testing.T) {
	h := newHarness(t, 200)
	// A controller whose remote always fails: enqueue must still be instant.
	sc := syncctl.New(syncctl.Config{
		Interval: time.Hour, MaxFiles: 1, MaxQueued: 2,
	}, &blockingRemote{}, nil)
	h.svc.WithSync(sc)

	done := make(chan struct{})
	go func() {
		defer close(done)
		for i := 0; i < 50; i++ {
			in := input("203.0.113.10", machA, diskA)
			in.RequestID = "r"
			in.Size = 1
			h.advance(2 * time.Second)
			_, _ = h.svc.RequestDraw(context.Background(), in)
		}
	}()
	select {
	case <-done:
	case <-time.After(5 * time.Second):
		t.Fatal("draws blocked on a failing dataset controller")
	}
}

type blockingRemote struct{}

func (blockingRemote) List(context.Context, string) ([]hf.RemoteFile, error) { return nil, nil }
func (blockingRemote) Publish(context.Context, string, []hf.File) error {
	return context.DeadlineExceeded
}
func (blockingRemote) Download(context.Context, string) ([]byte, error) {
	return nil, context.DeadlineExceeded
}

func keys(m map[string][]byte) []string {
	out := make([]string, 0, len(m))
	for k := range m {
		out = append(out, k)
	}
	return out
}

// Regression: the one-shot -sync export used its own subtree list and shipped
// raw/ to the dataset, while the live controller correctly excluded it. Both
// paths now read PublishableSubtrees, and this test pins the guarantee.
func TestExportSnapshotExcludesRaw(t *testing.T) {
	h := newHarness(t, 50)
	if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.10", machA, diskA)); err != nil {
		t.Fatal(err)
	}

	dir := t.TempDir()
	if _, err := h.svc.ExportSnapshot(dir); err != nil {
		t.Fatalf("export: %v", err)
	}

	for _, sub := range PublishableSubtrees {
		if sub == "raw" {
			t.Fatal("raw must never be listed as publishable")
		}
	}
	entries, err := os.ReadDir(dir)
	if err != nil {
		t.Fatal(err)
	}
	for _, e := range entries {
		if e.Name() == "raw" {
			t.Fatalf("export produced a raw/ subtree at %s", dir)
		}
	}

	// And nothing exported may contain a raw value.
	filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
		if err != nil || d.IsDir() {
			return nil
		}
		buf, err := os.ReadFile(p)
		if err != nil {
			return nil
		}
		for _, secret := range []string{"203.0.113.10", machA, diskA} {
			if strings.Contains(string(buf), secret) {
				t.Fatalf("%s leaked %q into the dataset export", p, secret)
			}
		}
		return nil
	})
}

// The bank is the answer key. It must never be a publishable subtree, because
// the dataset is written by this service and the Space repository is public.
func TestBankIsNeverPublishable(t *testing.T) {
	for _, sub := range PublishableSubtrees {
		if sub == "bank" {
			t.Fatal("bank must never appear in PublishableSubtrees: it is the answer key")
		}
	}

	h := newHarness(t, 50)
	if _, err := h.svc.RequestDraw(context.Background(), input("203.0.113.11", machB, diskB)); err != nil {
		t.Fatal(err)
	}
	dir := t.TempDir()
	if _, err := h.svc.ExportSnapshot(dir); err != nil {
		t.Fatalf("export: %v", err)
	}
	if _, err := os.Stat(filepath.Join(dir, "bank")); !os.IsNotExist(err) {
		t.Fatalf("export produced a bank/ subtree (err=%v)", err)
	}

	// Even with examples loaded, no reference solution may reach the snapshot.
	err := filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
		if err != nil || d.IsDir() {
			return nil
		}
		buf, rerr := os.ReadFile(p)
		if rerr != nil {
			return rerr
		}
		if bytes.Contains(buf, []byte("reference_solution")) {
			t.Fatalf("%s contains a reference solution", p)
		}
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
}