Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
302 changes: 230 additions & 72 deletions crates/design-http/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use design_harness::{
encode_env_into_extras, harness_from_zip, harness_id, validate_bundle, HarnessBundle,
};
use design_prompts::{load_prompt_set, prompt_set_digest, select_prompts_for_round};
use design_sanitize::viewer_headers;
use design_store::{
DesignStore, HarnessRow, RoundAward, RunStage, RunState, StageEvent, StoreError, StorePatch,
};
Expand Down Expand Up @@ -99,6 +98,10 @@ pub fn design_router(state: Arc<AppState>) -> Router {
.route("/v1/annotate", post(post_annotate))
.route("/v1/admin/rounds/{id}/candidates", get(admin_candidates))
.route("/v1/admin/rounds/{id}/winners", post(admin_winners))
.route(
"/v1/admin/rounds/current/requeue",
post(admin_requeue_current),
)
.route("/v1/rounds/{id}/leaderboard", get(leaderboard))
.with_state(state)
}
Expand Down Expand Up @@ -738,30 +741,32 @@ async fn get_pages(State(st): State<Arc<AppState>>, Path(id): Path<String>) -> R
}
}

async fn get_bundle_json(State(st): State<Arc<AppState>>, Path(id): Path<String>) -> Response {
match st.store.list_pages(&id).await {
Ok(pages) => {
let mut map = BTreeMap::new();
for p in pages {
map.insert(p.path, p.sanitized_html);
}
Json(json!({"run_id": id, "pages": map})).into_response()
}
Err(e) => json_err(StatusCode::INTERNAL_SERVER_ERROR, "store", &e.to_string()),
}
/// `bundle.json` used to embed every page's produced HTML. The viewer is
/// screenshots-only now, so the route is retired with a pointer instead of
/// serving a silently hollow bundle.
async fn get_bundle_json() -> Response {
json_err(
StatusCode::GONE,
"gone",
"bundle.json no longer embeds produced HTML; use /v1/runs/{id}/pages for page metadata and /v1/view/{id}/index.png for the screenshot",
)
}

/// Screenshots-only viewer: produced HTML is never served. Only captured PNG
/// artifacts (`index.png`) are public; any non-PNG page request is 410 Gone.
async fn view_page(
State(st): State<Arc<AppState>>,
Path((id, page)): Path<(String, String)>,
) -> Response {
let path = if page.ends_with(".html") || page.ends_with(".png") {
page
} else {
format!("{page}.html")
};
match st.store.get_page(&id, &path).await {
Ok(Some(body)) if path.ends_with(".png") => {
if !page.ends_with(".png") {
return json_err(
StatusCode::GONE,
"gone",
"produced HTML is never served; fetch the index.png screenshot instead",
);
}
Comment on lines +761 to +767

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Allow only index.png.

Line 761 accepts every path ending in .png. A stored non-screenshot artifact can then become public through the viewer. This breaks the screenshots-only contract.

Proposed fix
-    if !page.ends_with(".png") {
+    if page != "index.png" {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if !page.ends_with(".png") {
return json_err(
StatusCode::GONE,
"gone",
"produced HTML is never served; fetch the index.png screenshot instead",
);
}
if page != "index.png" {
return json_err(
StatusCode::GONE,
"gone",
"produced HTML is never served; fetch the index.png screenshot instead",
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/design-http/src/api.rs` around lines 761 - 767, Update the PNG
validation in the surrounding viewer handler so it allows only the exact
`index.png` artifact, rejecting every other path or filename with the existing
gone response; preserve successful serving for `index.png`.

match st.store.get_page(&id, &page).await {
Ok(Some(body)) => {
let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(body.trim()) else {
return json_err(StatusCode::INTERNAL_SERVER_ERROR, "artifact", "bad png b64");
};
Expand All @@ -780,22 +785,6 @@ async fn view_page(
);
(StatusCode::OK, headers, bytes).into_response()
}
Ok(Some(html)) => {
let mut headers = HeaderMap::new();
for (k, v) in viewer_headers(&st.frame_ancestors) {
if let (Ok(name), Ok(val)) = (
header::HeaderName::try_from(k),
header::HeaderValue::try_from(v),
) {
headers.insert(name, val);
}
}
headers.insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/html; charset=utf-8"),
);
(StatusCode::OK, headers, html).into_response()
}
Ok(None) => json_err(StatusCode::NOT_FOUND, "not_found", "page"),
Err(e) => json_err(StatusCode::INTERNAL_SERVER_ERROR, "store", &e.to_string()),
}
Expand Down Expand Up @@ -949,6 +938,48 @@ struct WinnersBody {
harness_ids: Vec<String>,
}

/// Manually schedule every active harness into the CURRENT open round.
///
/// Operator escape hatch when a round opened with no/few runs (e.g. challenge
/// restart). Idempotent for the current round: `schedule_harness_for_round`
/// returns the existing run ids for a `(harness, round)` pair that already has
/// runs, so a repeated call creates nothing and consumes no quota. Harnesses
/// that fail scheduling (daily quota) are reported under `skipped`; one bad
/// harness never blocks the rest.
async fn admin_requeue_current(State(st): State<Arc<AppState>>, headers: HeaderMap) -> Response {
if let Err(r) = check_admin(&st, &headers) {
return r;
}
let rid = round_id_at(now_secs());
let harnesses = match st.store.list_active_harnesses(rid).await {
Ok(h) => h,
Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, "store", &e.to_string()),
};
let epoch = st.epoch.load(std::sync::atomic::Ordering::Relaxed);
let mut scheduled = Vec::new();
let mut skipped = Vec::new();
for harness in &harnesses {
match schedule_harness_for_round(st.store.as_ref(), harness, rid, st.netuid, epoch).await {
Ok(run_ids) => scheduled.push(json!({
"harness_id": harness.id,
"miner_hotkey": harness.miner_hotkey,
"run_ids": run_ids,
})),
Err(e) => skipped.push(json!({
"harness_id": harness.id,
"miner_hotkey": harness.miner_hotkey,
"reason": e,
})),
}
}
Json(json!({
"round_id": rid,
"scheduled": scheduled,
"skipped": skipped,
}))
.into_response()
}
Comment on lines +949 to +981

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

fd -t f -e rs . crates | while IFS= read -r file; do
  ast-grep outline "$file" --items all --match 'DesignStore|insert_run|runs_for_round' || true
done

rg -n -C 5 'trait\s+DesignStore|fn\s+insert_run|fn\s+runs_for_round|INSERT INTO.*run|UNIQUE.*run' crates

Repository: BaseIntelligence/base

Length of output: 26201


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== api schedule_harness_for_round and admin_requeue_current =="
fd -a api.rs crates | while IFS= read -r file; do
  echo "--- $file"
  rg -n -C 8 'fn schedule_harness_for_round|admin_requeue_current|check_.*runs|#\(.*run' "$file" || true
done

echo "== db schema constraints for design_run =="
sed -n '1,120p' crates/db/migrations/0006_design_challenge.sql

echo "== design-db insert_design_run and runs_for_round =="
sed -n '440,540p' crates/design-db/src/lib.rs
sed -n '590,700p' crates/design-db/src/lib.rs

echo "== design-store implementations and errors =="
sed -n '300,365p' crates/design-store/src/store.rs
sed -n '230,285p' crates/design-store/src/dbstore.rs

echo "== deterministic schema/behavior probe =="
python3 - <<'PY'
import pathlib
p = pathlib.Path('crates/db/migrations/0006_design_challenge.sql')
text = p.read_text()
print('CREATE TABLE design_run exists:', 'CREATE TABLE design_run' in text)
print('CREATE TABLE design_run lines:')
tbl = []
collect = False
for line in text.splitlines():
    if line.startswith('CREATE TABLE design_run'):
        collect = True
    if collect:
        tbl.append(line)
        if ');' in line:
            break
print('\n'.join(tbl))
print('contains UNIQUE:', any('UNIQUE' in l for l in tbl))
print('contains PRIMARY KEY:', any('PRIMARY KEY' in l for l in tbl))
print('constraints:', [l.strip() for l in tbl if any(k in l for k in ('PRIMARY KEY', 'UNIQUE', 'CONSTRAINT', 'FOREIGN KEY', 'REFERENCES', 'NOT NULL'))])
for key in ('CREATE TABLE design_round', 'CREATE TABLE design_artifact', 'CREATE TABLE design_stage_event'):
    print(f'{key} exists:', key in text)
PY

Repository: BaseIntelligence/base

Length of output: 21444


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== schedule_harness_for_round implementation =="
sed -n '441,580p' crates/design-http/src/api.rs

echo "== StoreError variants and DB error mapping =="
rg -n -C 6 'enum StoreError|StoreError::.*Duplicate|map_db|impl From<DbError>|Backend' crates/design-store/src crates/design-http/src/api.rs

echo "== quota helpers =="
rg -n -C 5 'quota|daily|runs_allowed|quota_get|quota_bump|DesignStore' crates/design-http/src/api.rs crates/design-store/src/dbstore.rs crates/design-db/src/lib.rs

Repository: BaseIntelligence/base

Length of output: 50377


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

api = Path('crates/design-http/src/api.rs').read_text()
schema = Path('crates/db/migrations/0006_design_challenge.sql').read_text()
dbstore = Path('crates/design-store/src/dbstore.rs').read_text()
dbs_lib = Path('crates/design-db/src/lib.rs').read_text()

def between(s, start, end):
    return s[s.index(start)+len(start):s.index(end)].strip()

schedule = between(api, 'pub async fn schedule_harness_for_round(', 'pub async fn get_harness')
print('schedule calls runs_for_round:', 'run_ids' in schedule and 'runs_for_round' in schedule)
print('schedule calls get_run before insert:', 'if store\n            .get_run' in schedule)
print('schedule calls insert_run:', 'store.insert_run' in schedule)
print('schedule handles insert error:', re.search(r'store\.insert_run\(&row\)\.await\.map_err\(.*\)\?;', schedule) is not None)
print('insert handles duplicate later via get_run?', 'continue;' in schedule and 'return Err("' in schedule)

design_run = between(schema, 'CREATE TABLE design_run (', ');')
unique_ids = re.findall(r'UNIQUE\s*\((.*?)\)', design_run)
pk_ids = re.findall(r'PRIMARY\s+KEY(?:\s*\((.*?)(?:\)|\s+NOT))?', design_run)
print('design_run primary key:', 'id' in pk_ids)
print('design_run unique constraints:', unique_ids)

db_insert_call = re.search(r'impl\s+DesignStore\s+for\s+DbDesignStore\n\s*{(?P<body>.*?)\n}', dbstore, re.S).group('body')
print('DbDesignStore insert_run calls insert_design_run:', 'async fn insert_run' in db_insert_call and 'insert_design_run' in db_insert_call)
print('DbDesignStore insert_run maps errors:', '.map_err(map_db)' in db_insert_call)

map_db = re.search(r'fn\s+map_db\(.*?\n\{(?P<body>.*?)\n\}', dbstore, re.S).group('body')
print('map_db treats duplicate/unique as StoreError::Duplicate:', 'duplicate' in map_db and 'unique' in map_db and 'StoreError::Duplicate' in map_db)

insert_design_run_call = re.search(r'pub\s+async\s+fn\s+insert_design_run\([^;]+;', dbs_lib).group(0)
print('insert_design_run INSERT id only:', 'VALUES ($1' in insert_design_run_call and not 'ON CONFLICT' in insert_design_run_call)
PY

Repository: BaseIntelligence/base

Length of output: 303


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== insert_design_run body =="
python3 - <<'PY'
from pathlib import Path
import re
dbs = Path('crates/design-db/src/lib.rs').read_text()
m = re.search(r'pub async fn insert_design_run\(.*?\n\}\n', dbs, re.S)
if not m:
    # broader until next pub fn
    start = dbs.index('pub async fn insert_design_run')
    search = dbs[start:]
    nexts = [search.index(p, 1) for p in ('\npub ', '\n[', '\n///')]
    end = min(n for n in nexts if n > 0) if any(n > 0 for n in nexts) else len(search)
    print('`#BEGIN`')
    print(search[:end])
    print('`#END`')
else:
    print('`#BEGIN`')
    print(m.group(0))
    print('`#END`')
PY

echo "== behavior probe from source text =="
python3 - <<'PY'
from pathlib import Path
import re
api = Path('crates/design-http/src/api.rs').read_text()
schema = Path('crates/db/migrations/0006_design_challenge.sql').read_text()
dbstore = Path('crates/design-store/src/dbstore.rs').read_text()
dbs_lib = Path('crates/design-db/src/lib.rs').read_text()

start = api.index('pub async fn schedule_harness_for_round(')
end = api.index('\npub async fn get_harness(', start)
schedule = api[start:end]
print('schedule_checks_run_ids_from_round:', 'run_ids: Vec<String> = existing' in schedule and '..filter(|r| r.harness_id == harness.id)' in schedule)
print('schedule_returns_existing_run_ids:', 'if !run_ids.is_empty()' in schedule and 'return Ok(run_ids)' in schedule)
print('schedule_rechecks_each_run_id_before_insert:', re.search(r'if\s+store\s*\.[^\n]*get_run\(&run_id\).*?\.is_some\(\)\s*\{\s*run_ids\.push\(run_id\);', schedule, re.S) is not None)
print('schedule_inserts_run:', 'store.insert_run(&row).await.map_err' in schedule)
print('schedule_promotes_on_insert_success:', 'run_ids.push(run_id)' in schedule and 'store.quota_bump' in schedule)

run = schema[schema.index('CREATE TABLE design_run ('): schema.index('\n\nCREATE TABLE design_artifact', schema.index('CREATE TABLE design_run ('))]
print('design_run_primary_key_id:', re.search(r'id\s+TEXT\s+PRIMARY\s+KEY', run) is not None)
print('design_run_unique_constraints:', ',\n'.join(re.findall(r',?\s*(?:CONSTRAINT\s+\w+\s+)?\s*UNIQUE\s*\([^)]+\)', run, re.S)))

print('DbDesignStore_insert_run_uses_insert_design_run:', 'async fn insert_run' in dbstore and 'insert_design_run' in dbstore[dbstore.index('async fn insert_run'):dbstore.index('async fn get_run')])
print('DbDesignStore_maps_duplicate_errors:', 'if s.contains("duplicate") || s.contains("unique")' in dbstore and 'StoreError::Duplicate' in dbstore[dbstore.index('fn map_db'):dbstore.index('fn extras_from_value')])

print('insert_design_run_plain_insert_no_upsert:', 'fn map_db' not in dbs_lib[dbs_lib.index('pub async fn insert_design_run'):dbs_lib.index('/// Fetch run.')])
PY

Repository: BaseIntelligence/base

Length of output: 715


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

api = Path('crates/design-http/src/api.rs').read_text()
schema = Path('crates/db/migrations/0006_design_challenge.sql').read_text()
dbstore = Path('crates/design-store/src/dbstore.rs').read_text()
dbs_lib = Path('crates/design-db/src/lib.rs').read_text()

start = re.search(r'pub async fn schedule_harness_for_round\(', api).start()
end = re.search(r'(?::#\s*async fn get_harness)', api[start:]) or re.search(r'\n\nasync fn get_harness', api[start:])
schedule = api[start:api.index('\n\nasync fn get_harness', start)]

print('schedule_checks_run_ids_from_round:', 'run_ids: Vec<String> = existing' in schedule and 'filter(|r| r.harness_id == harness.id)' in schedule)
print('schedule_returns_existing_run_ids:', 'if !run_ids.is_empty()' in schedule and 'return Ok(run_ids)' in schedule)
print('schedule_rechecks_each_run_id_before_insert:', re.search(r'if\s+store\s*\.[^\n]*get_run\(&run_id\).*?\.is_some\(\)\s*\{\s*run_ids\.push\(run_id\);', schedule, re.S) is not None)
print('schedule_inserts_run:', 'store.insert_run(&row).await.map_err' in schedule)
print('schedule_promotes_on_insert_success:', 'run_ids.push(run_id)' in schedule and 'store.quota_bump' in schedule)

run = schema[schema.index('CREATE TABLE design_run ('): schema.index('\n\nCREATE TABLE design_artifact', schema.index('CREATE TABLE design_run ('))]
print('design_run_primary_key_id:', re.search(r'id\s+TEXT\s+PRIMARY\s+KEY', run) is not None)
print('design_run_unique_constraints:', ',\n'.join(re.findall(r',?\s*(?:CONSTRAINT\s+\w+\s+)?\s*UNIQUE\s*\([^)]+\)', run, re.S)))

insert_start = dbstore.index('async fn insert_run')
insert_end = dbstore.index('async fn get_run')
insert_chunk = dbstore[insert_start:insert_end]
print('DbDesignStore_insert_run_uses_insert_design_run:', 'insert_design_run' in insert_chunk)
print('DbDesignStore_maps_duplicate_errors:', 'if s.contains("duplicate") || s.contains("unique")' in dbstore[dbstore.index('fn map_db'):dbstore.index('fn extras_from_value')])

ins_start = dbs_lib.index('pub async fn insert_design_run')
ins_end = dbs_lib.index('/// Fetch run.', ins_start)
print('insert_design_run_plain_insert_no_upsert:', 'ON CONFLICT' not in dbs_lib[ins_start:ins_end])
PY

Repository: BaseIntelligence/base

Length of output: 566


Handle run-insert races by reading existing runs after a duplicate error.

design_run only has id as a key, so insert_design_run is a plain insert and concurrent /requeue calls can both pass the empty per-round check. insert_run maps duplicate/unique DB errors to StoreError::Duplicate, but schedule_harness_for_round treats that as scheduling failure and reports the harness as skipped. On that error, re-read runs for (harness, round) instead of returning the error so the endpoint stays idempotent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/design-http/src/api.rs` around lines 949 - 981, Update
schedule_harness_for_round to handle StoreError::Duplicate from insert_run by
re-reading the existing runs for the harness and round and returning their run
IDs as a successful scheduling result. Preserve normal success behavior and
continue propagating non-duplicate errors, so concurrent requeue requests remain
idempotent instead of marking the harness skipped.


async fn admin_candidates(
State(st): State<Arc<AppState>>,
headers: HeaderMap,
Expand Down Expand Up @@ -1204,21 +1235,30 @@ mod tests {
}

#[tokio::test]
async fn view_page_serves_lockdown_headers_and_no_cookies() {
async fn view_page_serves_screenshots_only() {
let (st, _g) = app_state(None);
let run_id = "a".repeat(64);
// Store a script-laden page directly: even if sanitization were
// bypassed, the response headers must keep the payload inert.
// index.html exists in the store, but produced HTML is never served.
let png_bytes = [0x89, 0x50, 0x4E, 0x47];
st.store
.put_artifacts(
&run_id,
&[(
"index.html".to_owned(),
"<html><script>alert(1)</script>miner</html>".to_owned(),
"raw".to_owned(),
"00".repeat(32),
42_u32,
)],
&[
(
"index.html".to_owned(),
"<html><script>alert(1)</script>miner</html>".to_owned(),
"raw".to_owned(),
"00".repeat(32),
42_u32,
),
(
"index.png".to_owned(),
base64::engine::general_purpose::STANDARD.encode(png_bytes),
"raw".to_owned(),
"11".repeat(32),
4_u32,
),
],
)
.await
.unwrap();
Expand All @@ -1232,35 +1272,153 @@ mod tests {
.oneshot(Request::get(&url).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK, "{url}");
let h = res.headers().clone();
let csp = h
.get(header::CONTENT_SECURITY_POLICY)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
assert!(csp.starts_with("sandbox;"), "{csp}");
assert!(!csp.contains("allow-scripts"), "{csp}");
assert!(!csp.contains("allow-same-origin"), "{csp}");
assert!(csp.contains("default-src 'none'"), "{csp}");
// app_state pins 'none'; prod default allows the public site.
assert!(csp.contains("frame-ancestors 'none'"), "{csp}");
assert_eq!(
h.get(header::X_CONTENT_TYPE_OPTIONS)
.and_then(|v| v.to_str().ok()),
Some("nosniff")
);
assert_eq!(
h.get(header::REFERRER_POLICY).and_then(|v| v.to_str().ok()),
Some("no-referrer")
);
assert_eq!(
h.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()),
Some("text/html; charset=utf-8")
);
assert!(h.get(header::SET_COOKIE).is_none(), "{url} sets a cookie");
assert_eq!(res.status(), StatusCode::GONE, "{url}");
assert!(res.headers().get(header::SET_COOKIE).is_none());
let bytes = res.into_body().collect().await.unwrap().to_bytes();
assert!(std::str::from_utf8(&bytes).unwrap().contains("miner"));
let v: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["error"], "gone", "{url}");
// The stored HTML must not leak into the 410 body.
assert!(!String::from_utf8_lossy(&bytes).contains("miner"), "{url}");
}
// The PNG screenshot is served as image/png.
let res = app
.clone()
.oneshot(
Request::get(format!("/v1/view/{run_id}/index.png"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(
res.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok()),
Some("image/png")
);
assert_eq!(
res.headers()
.get(header::X_CONTENT_TYPE_OPTIONS)
.and_then(|v| v.to_str().ok()),
Some("nosniff")
);
let bytes = res.into_body().collect().await.unwrap().to_bytes();
assert_eq!(bytes.as_ref(), &png_bytes);
// Unknown png → 404.
let (s, v) = call(
app,
Request::get(format!("/v1/view/{run_id}/missing.png"))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(s, StatusCode::NOT_FOUND, "{v}");
}

#[tokio::test]
async fn bundle_json_is_gone() {
let (st, _g) = app_state(None);
let run_id = "b".repeat(64);
st.store
.put_artifacts(
&run_id,
&[(
"index.html".to_owned(),
"<html>miner</html>".to_owned(),
"raw".to_owned(),
"00".repeat(32),
7_u32,
)],
)
.await
.unwrap();
let app = design_router(Arc::clone(&st));
let (s, v) = call(
app,
Request::get(format!("/v1/runs/{run_id}/bundle.json"))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(s, StatusCode::GONE, "{v}");
assert_eq!(v["error"], "gone");
// The stored HTML must not leak into the response body.
assert!(!v.to_string().contains("miner"));
}

#[tokio::test]
async fn admin_requeue_schedules_current_round_once() {
let admin_token = "test-admin-token";
let gating = Arc::new(MemoryGatingStore::new());
let st = Arc::new(AppState {
store: Arc::new(MemoryDesignStore::new()),
epoch: std::sync::atomic::AtomicU64::new(0),
netuid: 541,
backend_mode: "memory",
annotator_token_hashes: vec![],
admin_token_hashes: vec![token_hash(admin_token)],
frame_ancestors: "'none'".into(),
retry_max: 2,
award_hook: None,
gating: Some(Arc::clone(&gating) as Arc<dyn GatingStore>),
metagraph: None,
});
Comment on lines +1351 to +1366

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Remove the literal bearer token.

Line 1352 embeds an operator bearer token in source. Generate a test-only value at runtime and do not print it.

As per coding guidelines, “Never log, document, or include evidence containing private keys, wallet mnemonics, API tokens, or full secret values.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/design-http/src/api.rs` around lines 1351 - 1366, Replace the
hard-coded admin token in admin_requeue_schedules_current_round_once with a
test-only value generated at runtime, and use that value consistently when
hashing and authenticating the request. Do not log, document, or otherwise
expose the generated token or any full secret value.

Source: Coding guidelines

let app = design_router(Arc::clone(&st));

// Operator-protected like the other admin routes.
let (s, v) = call(
app.clone(),
Request::post("/v1/admin/rounds/current/requeue")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(s, StatusCode::UNAUTHORIZED, "{v}");

// Two active harnesses, each auto-scheduled into the NEXT round.
let (s, v) = post(app.clone(), submit_body(&hk(0xAA), "a")).await;
assert_eq!(s, StatusCode::ACCEPTED, "{v}");
let (s, v) = post(app.clone(), submit_body(&hk(0xBB), "b")).await;
assert_eq!(s, StatusCode::ACCEPTED, "{v}");
let current = round_id_at(now_secs());
assert!(st.store.runs_for_round(current).await.unwrap().is_empty());

// First requeue schedules both harnesses into the current round.
let requeue = || {
Request::post("/v1/admin/rounds/current/requeue")
.header(header::AUTHORIZATION, format!("Bearer {admin_token}"))
.body(Body::empty())
.unwrap()
};
let (s, v) = call(app.clone(), requeue()).await;
assert_eq!(s, StatusCode::OK, "{v}");
assert_eq!(v["round_id"], current);
assert_eq!(v["scheduled"].as_array().unwrap().len(), 2, "{v}");
assert!(v["skipped"].as_array().unwrap().is_empty(), "{v}");
let runs = st.store.runs_for_round(current).await.unwrap();
assert_eq!(runs.len(), 2 * design_challenge_task::prompts_per_round());
assert!(runs.iter().all(|r| r.status == RunStage::Queued));

// Second call is a no-op: same run ids, no new runs, quota untouched.
let (s, v2) = call(app.clone(), requeue()).await;
assert_eq!(s, StatusCode::OK, "{v2}");
assert_eq!(
v["scheduled"].as_array().unwrap(),
v2["scheduled"].as_array().unwrap(),
"idempotent requeue returns the same run ids"
);
assert_eq!(
st.store.runs_for_round(current).await.unwrap().len(),
runs.len()
);
let day = utc_day(now_secs());
let used = st.store.quota_get(&hk(0xAA), &day).await.unwrap();
assert_eq!(
usize::try_from(used).unwrap(),
2 * design_challenge_task::prompts_per_round(),
"next-round + current-round schedule only"
);
}

#[tokio::test]
Expand Down
Loading
Loading