sh1k4ku commited on
Commit
12dcfe9
·
verified ·
1 Parent(s): abdacf0

Upload index.html with huggingface_hub

Browse files
Files changed (1) hide show
  1. index.html +151 -114
index.html CHANGED
@@ -259,116 +259,159 @@ problemSel.onchange = async () => {
259
 
260
  applyMode();
261
 
262
- // ===== Grading harness that runs inside Python (defined once at startup) =====
263
- // __bb_install: load a problem's hidden module, expose ONLY its public function as
264
- // "blackbox", and stash the oracle + bug definitions privately in __BB.
265
- // __bb_run: run the student's TESTS list, identify which bug each case catches,
266
- // and report it with the source line number + reason.
267
- const HARNESS = `
268
- import sys, types, linecache, ast, json
269
-
270
- def __bb_install(public_name, source):
271
- ns = {}
272
- exec(compile(source, "blackbox_impl", "exec"), ns)
273
- combined = ns["blackbox"] # the 5-bug program students test
274
- ref = ns["reference"] # the correct spec oracle (kept hidden)
275
- bugs = ns["BUGS"] # name -> (single_bug_fn, marks) (hidden)
276
- reasons = ns.get("REASONS", {})
277
- # scrub the answer key out of the namespace reachable via __globals__
278
- for k in ("reference", "BUGS", "REASONS", "_b1", "_b2", "_b3", "_b4", "_b5"):
279
- ns.pop(k, None)
280
- linecache.cache.clear()
281
- pub = types.ModuleType("blackbox")
282
- setattr(pub, public_name, combined)
283
- sys.modules["blackbox"] = pub
284
- globals()["__BB"] = {"fn": combined, "ref": ref, "bugs": bugs,
285
- "reasons": reasons, "pub": public_name}
286
-
287
- def __s(v):
288
- return v if isinstance(v, str) else repr(v)
289
-
290
- def __bb_run(source):
291
- g = globals()
292
- info = g.get("__BB")
293
- TESTS = g.get("TESTS", None)
294
- # map each TESTS element to its source line number (one case per line)
295
- linenos = {}
296
- try:
297
- tree = ast.parse(source)
298
- for node in ast.walk(tree):
299
- if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "TESTS" for t in node.targets):
300
- if isinstance(node.value, (ast.List, ast.Tuple)):
301
- for i, el in enumerate(node.value.elts):
302
- linenos[i] = el.lineno
303
- except Exception:
304
- pass
305
- if not isinstance(TESTS, (list, tuple)):
306
- return json.dumps({"ok": False, "error": "Define a list named TESTS = [ ((args), expected), ... ] -- one case per line."})
307
- fn = info["fn"]; ref = info["ref"]; BUGS = info["bugs"]; REASONS = info["reasons"]
308
- order = list(BUGS) # fixed bug numbering: order.index(name)+1
309
- caught = {}
310
- rows = []
311
- for i, case in enumerate(TESTS):
312
- line = linenos.get(i)
313
  try:
314
- args, expected = case
315
- args = tuple(args)
 
 
 
 
316
  except Exception:
317
- rows.append({"line": line, "status": "malformed", "raw": repr(case)})
318
- continue
319
- try:
320
- actual = fn(*args)
321
- except Exception as e:
322
- rows.append({"line": line, "status": "error", "argstr": repr(args), "msg": str(e)})
323
- continue
324
- spec = ref(*args)
325
- bug = None
326
- for name in BUGS:
327
  try:
328
- if BUGS[name][0](*args) != spec:
329
- bug = name; break
330
  except Exception:
331
- pass
332
- argstr = repr(args)
333
- valid_expected = (expected == spec)
334
- if actual != expected:
335
- if not valid_expected:
336
- rows.append({"line": line, "status": "invalid", "argstr": argstr,
337
- "expected": __s(expected), "spec": __s(spec)})
338
- else:
339
- if bug is None:
340
- bug = "(unknown)"
341
- num = order.index(bug) + 1 if bug in order else "?"
342
- first = bug not in caught
343
- if first:
344
- caught[bug] = line
345
- rows.append({"line": line, "status": "bug" if first else "dup",
346
- "bug": bug, "num": num, "total": len(BUGS),
347
- "reason": REASONS.get(bug, "output differs from the spec"),
348
- "argstr": argstr, "actual": __s(actual), "expected": __s(expected)})
349
- else:
350
- if not valid_expected:
351
- rows.append({"line": line, "status": "invalid", "argstr": argstr,
352
- "expected": __s(expected), "spec": __s(spec)})
 
 
 
 
 
 
 
 
 
 
353
  else:
354
- rows.append({"line": line, "status": "ok", "argstr": argstr, "actual": __s(actual)})
355
- return json.dumps({"ok": True, "rows": rows, "caught": list(caught.keys()),
356
- "caughtCount": len(caught), "totalBugs": len(BUGS), "numTests": len(TESTS)})
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  `;
358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359
  // ===== Load Pyodide + the hidden implementation =====
360
  let pyodide;
 
361
 
362
- // Fetch problem <key>'s hidden source and install it: only its public function is
363
- // exposed as "blackbox"; the oracle + bug definitions stay private in __BB.
364
  async function loadProblem(key) {
365
  if (!pyodide) return; // not ready yet; startup will load the current prob
366
  const b64 = (await (await fetch(PROBLEMS[key].data)).text()).trim();
367
- const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
368
- const src = new TextDecoder("utf-8").decode(bytes);
369
- pyodide.globals.set("__bb_src", src);
370
- pyodide.runPython(`__bb_install(${JSON.stringify(PROBLEMS[key].public)}, __bb_src)`);
371
- pyodide.runPython("del globals()['__bb_src']");
372
  modinfo.textContent = key + " · " + PROBLEMS[key].sig;
373
  }
374
 
@@ -379,21 +422,13 @@ async function loadProblem(key) {
379
  stderr: (s) => append(s + "\n", "err"),
380
  });
381
 
382
- // Block reading hidden source via inspect (defence-in-depth; getsource also
383
- // fails naturally because no source file exists on disk).
384
- pyodide.runPython(`
385
- import inspect
386
- _orig_getsource = inspect.getsource
387
- def _guard_getsource(obj, *a, **k):
388
- mod = getattr(obj, '__module__', None)
389
- if mod in (None, 'blackbox', 'blackbox_impl'):
390
- raise OSError("source code is not available")
391
- return _orig_getsource(obj, *a, **k)
392
- inspect.getsource = _guard_getsource
393
- inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available"))
394
- `);
395
 
396
- pyodide.runPython(HARNESS); // define __bb_install / __bb_run
397
  await loadProblem(prob); // load the currently selected problem
398
 
399
  statusEl.textContent = "✓ Ready";
@@ -416,11 +451,13 @@ async function run() {
416
  const code = editor.getValue();
417
  try {
418
  if (mode === "test") {
419
- // Run the student's code to define TESTS, then grade it against the hidden oracle.
 
420
  pyodide.runPython("globals().pop('TESTS', None)");
421
- pyodide.globals.set("__SRC", code);
422
  await pyodide.runPythonAsync(code); // defines TESTS (and any prints)
423
- const rep = JSON.parse(pyodide.runPython("__bb_run(__SRC)"));
 
 
424
  renderReport(rep);
425
  } else {
426
  // Plain run: just execute and show output, no grading
 
259
 
260
  applyMode();
261
 
262
+ // ===== Grading harness (closure-isolated) =====
263
+ // The whole harness is built inside a factory function. Its state (oracle, bug
264
+ // definitions, reasons) lives ONLY in closures held by the returned object, which
265
+ // we keep solely as a JS-side proxy. Nothing is stored in Python globals(), so
266
+ // student code (e.g. print(globals())) can never see the answer key.
267
+ const HARNESS_FACTORY = `
268
+ def __bb_make():
269
+ import sys, types, linecache, ast, json, inspect
270
+
271
+ # Block reading hidden source via inspect (defence in depth).
272
+ _og = inspect.getsource
273
+ def _guard(obj, *a, **k):
274
+ if getattr(obj, "__module__", None) in (None, "blackbox", "blackbox_impl"):
275
+ raise OSError("source code is not available")
276
+ return _og(obj, *a, **k)
277
+ inspect.getsource = _guard
278
+ inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available"))
279
+
280
+ state = {} # captured in closures only; never placed in any global
281
+
282
+ def install(public_name, source):
283
+ ns = {}
284
+ exec(compile(source, "blackbox_impl", "exec"), ns)
285
+ combined = ns["blackbox"] # the 5-bug program students test
286
+ ref = ns["reference"] # the correct spec oracle (kept hidden)
287
+ bugs = ns["BUGS"] # name -> (single_bug_fn, marks) (hidden)
288
+ reasons = ns.get("REASONS", {})
289
+ for k in ("reference", "BUGS", "REASONS", "_b1", "_b2", "_b3", "_b4", "_b5"):
290
+ ns.pop(k, None)
291
+ linecache.cache.clear()
292
+ # public wrapper: its __globals__ is this clean module, not the impl ns
293
+ def _public(*a, **k):
294
+ return combined(*a, **k)
295
+ _public.__name__ = public_name
296
+ sys.modules.pop("blackbox", None)
297
+ pub = types.ModuleType("blackbox")
298
+ setattr(pub, public_name, _public)
299
+ sys.modules["blackbox"] = pub
300
+ state.clear()
301
+ state.update(fn=combined, ref=ref, bugs=bugs, reasons=reasons)
302
+
303
+ def _s(v):
304
+ return v if isinstance(v, str) else repr(v)
305
+
306
+ def run(source, tests):
307
+ fn = state["fn"]; ref = state["ref"]; BUGS = state["bugs"]; REASONS = state["reasons"]
308
+ order = list(BUGS) # fixed bug numbering: order.index(name)+1
309
+ linenos = {}
 
 
 
310
  try:
311
+ tree = ast.parse(source)
312
+ for node in ast.walk(tree):
313
+ if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "TESTS" for t in node.targets):
314
+ if isinstance(node.value, (ast.List, ast.Tuple)):
315
+ for i, el in enumerate(node.value.elts):
316
+ linenos[i] = el.lineno
317
  except Exception:
318
+ pass
319
+ if not isinstance(tests, (list, tuple)):
320
+ return json.dumps({"ok": False, "error": "Define a list named TESTS = [ ((args), expected), ... ] -- one case per line."})
321
+ caught = {}
322
+ rows = []
323
+ for i, case in enumerate(tests):
324
+ line = linenos.get(i)
 
 
 
325
  try:
326
+ args, expected = case
327
+ args = tuple(args)
328
  except Exception:
329
+ rows.append({"line": line, "status": "malformed", "raw": repr(case)})
330
+ continue
331
+ try:
332
+ actual = fn(*args)
333
+ except Exception as e:
334
+ rows.append({"line": line, "status": "error", "argstr": repr(args), "msg": str(e)})
335
+ continue
336
+ spec = ref(*args)
337
+ bug = None
338
+ for name in BUGS:
339
+ try:
340
+ if BUGS[name][0](*args) != spec:
341
+ bug = name; break
342
+ except Exception:
343
+ pass
344
+ argstr = repr(args)
345
+ valid_expected = (expected == spec)
346
+ if actual != expected:
347
+ if not valid_expected:
348
+ rows.append({"line": line, "status": "invalid", "argstr": argstr,
349
+ "expected": _s(expected), "spec": _s(spec)})
350
+ else:
351
+ if bug is None:
352
+ bug = "(unknown)"
353
+ num = order.index(bug) + 1 if bug in order else "?"
354
+ first = bug not in caught
355
+ if first:
356
+ caught[bug] = line
357
+ rows.append({"line": line, "status": "bug" if first else "dup",
358
+ "bug": bug, "num": num, "total": len(BUGS),
359
+ "reason": REASONS.get(bug, "output differs from the spec"),
360
+ "argstr": argstr, "actual": _s(actual), "expected": _s(expected)})
361
  else:
362
+ if not valid_expected:
363
+ rows.append({"line": line, "status": "invalid", "argstr": argstr,
364
+ "expected": _s(expected), "spec": _s(spec)})
365
+ else:
366
+ rows.append({"line": line, "status": "ok", "argstr": argstr, "actual": _s(actual)})
367
+ return json.dumps({"ok": True, "rows": rows, "caught": list(caught.keys()),
368
+ "caughtCount": len(caught), "totalBugs": len(BUGS), "numTests": len(tests)})
369
+
370
+ class _H:
371
+ pass
372
+ h = _H()
373
+ h.install = install
374
+ h.run = run
375
+ return h
376
+
377
+ __bb_make()
378
  `;
379
 
380
+ // ===== Decryption of the hidden .dat files =====
381
+ // Must match PASSPHRASE in build_blackbox.py. NOTE: this only raises the bar --
382
+ // the passphrase ships here, so a determined reader can still recover the source.
383
+ const PASSPHRASE = "t2-unsw-bbt-v1-rotate-me";
384
+ let __keyBytes = null;
385
+ async function _sha256(bytes) {
386
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
387
+ }
388
+ async function decryptDat(b64) {
389
+ if (!__keyBytes) __keyBytes = await _sha256(new TextEncoder().encode(PASSPHRASE));
390
+ const cipher = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
391
+ const out = new Uint8Array(cipher.length);
392
+ const blk = new Uint8Array(__keyBytes.length + 8);
393
+ blk.set(__keyBytes, 0);
394
+ const dv = new DataView(blk.buffer);
395
+ let counter = -1, ks = null;
396
+ for (let off = 0; off < cipher.length; off++) {
397
+ const c = Math.floor(off / 32);
398
+ if (c !== counter) { counter = c; dv.setBigUint64(__keyBytes.length, BigInt(c), false); ks = await _sha256(blk); }
399
+ out[off] = cipher[off] ^ ks[off % 32];
400
+ }
401
+ return new TextDecoder("utf-8").decode(out);
402
+ }
403
+
404
  // ===== Load Pyodide + the hidden implementation =====
405
  let pyodide;
406
+ let harness, bbInstall, bbRun; // JS-side proxies; harness state stays in closures
407
 
408
+ // Fetch problem <key>'s encrypted source, decrypt it, and install it. Only the
409
+ // public function is exposed as "blackbox"; the oracle/bugs/reasons stay in the closure.
410
  async function loadProblem(key) {
411
  if (!pyodide) return; // not ready yet; startup will load the current prob
412
  const b64 = (await (await fetch(PROBLEMS[key].data)).text()).trim();
413
+ const src = await decryptDat(b64);
414
+ bbInstall(PROBLEMS[key].public, src);
 
 
 
415
  modinfo.textContent = key + " · " + PROBLEMS[key].sig;
416
  }
417
 
 
422
  stderr: (s) => append(s + "\n", "err"),
423
  });
424
 
425
+ // Build the harness; keep its entry points only as JS proxies, then delete the
426
+ // single global name so nothing about the harness remains in Python globals().
427
+ harness = pyodide.runPython(HARNESS_FACTORY);
428
+ pyodide.runPython("del __bb_make");
429
+ bbInstall = harness.install;
430
+ bbRun = harness.run;
 
 
 
 
 
 
 
431
 
 
432
  await loadProblem(prob); // load the currently selected problem
433
 
434
  statusEl.textContent = "✓ Ready";
 
451
  const code = editor.getValue();
452
  try {
453
  if (mode === "test") {
454
+ // Run the student's code in the (clean) main globals to define TESTS, then
455
+ // grade via the closure proxy -- TESTS is passed in, nothing sensitive is shared.
456
  pyodide.runPython("globals().pop('TESTS', None)");
 
457
  await pyodide.runPythonAsync(code); // defines TESTS (and any prints)
458
+ const tests = pyodide.globals.get("TESTS");
459
+ const rep = JSON.parse(bbRun(code, tests === undefined ? null : tests));
460
+ if (tests && typeof tests.destroy === "function") tests.destroy();
461
  renderReport(rep);
462
  } else {
463
  // Plain run: just execute and show output, no grading