From 79115201d091354a86004de8d7e44c32069a5b08 Mon Sep 17 00:00:00 2001
From: vidit choudhary <153429790+vidit-16@users.noreply.github.com>
Date: Wed, 7 Oct 2026 22:28:19 +0530
Subject: [PATCH] Limits that suit campus Wi-Fi; the map in the README;
handover gaps tested
- Campus Wi-Fi puts a whole class behind one address, and the sixth
sign-up in an hour was being refused. Sign-up now allows 30 an hour per
address and sign-in 60 a minute, while guessing one account's password
is still stopped after 10 tries a minute, counted per account.
- tools/build_campus.py also draws docs/campus_map.svg from the same table
as the app's map, and the README shows it.
- The README describes the two-sided handover and the limits.
- Mutation testing of the handover found five untested cases (receiving a
non-found item, not-received without a hand-in, someone else answering,
staff receiving their own report, returning to the page). Tests added;
all 21 handover mutants are now caught.
---
README.md | 30 ++++++++++----
app.py | 33 +++++++++------
docs/campus_map.svg | 96 +++++++++++++++++++++++++++++++++++++++++++
tests/test_app.py | 68 +++++++++++++++++++++++++++++-
tools/build_campus.py | 37 +++++++++++++++++
5 files changed, 243 insertions(+), 21 deletions(-)
create mode 100644 docs/campus_map.svg
diff --git a/README.md b/README.md
index a2770cd..ee7c04e 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,11 @@ the security desk, and owners collect them with a one-time code.
**Live app:** https://classfind-prod.eba-ttyqcasp.ap-south-1.elasticbeanstalk.com/
+
+
+
+
The campus map ClassFind is built on: 29 places, the paths between them, and the security desk at the front of the Main Block.
+
@@ -58,10 +63,13 @@ the security desk, and owners collect them with a one-time code.
- **Photos** go to S3 through presigned URLs. Amazon Rekognition labels them
("Bottle", "Backpack") and the labels count in matching and Retrace. A Lambda
function makes thumbnails for the home page.
-- **Security desk.** Every found item goes to the desk. A student's found report
- shows as awaiting drop-off until staff mark it received. Each item keeps a
- chain of custody: reported, received, claim approved, released, with who did
- each and when. Valuables left unclaimed for 72 hours move to the admin office.
+- **Security desk.** Every found item goes to the desk, and both sides confirm the
+ hand-over. The finder can mark it "I've handed it in", which puts it at the
+ top of the Desk page for staff to confirm or mark not received. If the desk
+ logs it first, it is held at once and the finder is asked "Was that you?";
+ "That wasn't me" flags it for the admin. Each item keeps a chain of custody:
+ reported, handed in, received, claim approved, released, with who did each
+ and when. Valuables left unclaimed for 72 hours move to the admin office.
- **Claim** with proof only the owner would know; electronics, wallets and keys
need a longer proof such as a serial number. Desk staff, not the finder,
approve or reject claims.
@@ -80,6 +88,10 @@ the security desk, and owners collect them with a one-time code.
accepts from their own account within 7 days.
- **AI check.** One button on the admin page tries every configured model and
shows "working" or the provider's exact error, never the key.
+- **Limits that suit a campus.** A whole class on campus Wi-Fi shares one
+ address, so sign-up allows 30 accounts an hour per address and sign-in 60
+ attempts a minute, while guessing one account's password is stopped after 10
+ tries a minute.
## How sentences and voice are understood
@@ -101,7 +113,8 @@ a current chat model and remembers it.
## How places are matched
-`static/campus.json` holds the places, their outlines, about 300 other names,
+`tools/build_campus.py` writes `static/campus.json` and the README map from one
+table. `static/campus.json` holds the places, their outlines, about 300 other names,
the paths, and a graph of the paths with the door where each building meets
one. `campus.py` turns text into a place: longest name first, a trailing "lab"
or "block" belongs to the name before it, words like "near" or "outside" mark
@@ -204,8 +217,9 @@ check below.
.venv/Scripts/python.exe -m unittest discover -s tests -v
```
-116 tests, with no network or AWS account needed. Besides accounts, reporting,
-the desk flow from drop-off to collection code, admin, CSRF, security headers
+122 tests, with no network or AWS account needed. Besides accounts, reporting,
+the desk flow from drop-off and two-sided hand-over to collection code, admin,
+CSRF, rate limits, security headers
and uploads, they cover place names (aliases, misspellings, Kannada and Hindi,
places that are ambiguous on purpose), the path graph being fully connected,
Retrace, voice in each mode, every model fallback (busy, retired, timed out),
@@ -245,7 +259,7 @@ ClassFind/
├── tools/ build_campus.py, smoke.py, mutate.py
├── tests/ test_app.py, test_campus.py, test_quality.py,
│ test_thumbnail_lambda.py
-├── docs/ AWS setup and screenshots
+├── docs/ AWS setup, campus map image, screenshots
└── .github/workflows/ CI on SQLite and PostgreSQL
```
diff --git a/app.py b/app.py
index c553500..b41f2ae 100644
--- a/app.py
+++ b/app.py
@@ -165,8 +165,10 @@ def protect_csrf():
# memory, which is enough because Gunicorn runs a single process; a restart
# simply starts the counts again.
RATE_LIMITS = {
- "login": (10, 60),
- "register": (5, 60 * 60),
+ # A whole class on campus Wi-Fi shares one address, so these are per
+ # address but generous; guessing one account's password is capped below.
+ "login": (60, 60),
+ "register": (30, 60 * 60),
"report": (20, 60 * 60),
"submit_claim": (20, 60 * 60),
# Collection codes are six digits, so the desk screen caps guesses.
@@ -177,6 +179,9 @@ def protect_csrf():
# Each clip is sent to Gemini.
"voice": (40, 60 * 60),
}
+# Limits per address and per account, for forms where one person attacking one
+# account matters more than how many people share an address.
+ACCOUNT_RATE_LIMITS = {"login": (10, 60)}
app.config["RATE_LIMITS_ENABLED"] = True
_rate_hits = {}
_rate_lock = threading.Lock()
@@ -193,20 +198,24 @@ def rate_limit():
limit = RATE_LIMITS.get(request.endpoint)
if not limit:
return
- count, window = limit
- key = (request.endpoint, request.remote_addr)
+ checks = [((request.endpoint, request.remote_addr), limit)]
+ if request.endpoint in ACCOUNT_RATE_LIMITS:
+ account = request.form.get("email", "").strip().lower()
+ checks.append(((request.endpoint, request.remote_addr, account), ACCOUNT_RATE_LIMITS[request.endpoint]))
now = time.monotonic()
with _rate_lock:
- recent = [t for t in _rate_hits.get(key, ()) if now - t < window]
- if len(recent) >= count:
+ for key, (count, window) in checks:
+ recent = [t for t in _rate_hits.get(key, ()) if now - t < window]
_rate_hits[key] = recent
- retry_after = int(window - (now - recent[0])) + 1
- abort(429, description=f"Too many attempts. Try again in {retry_after} seconds.")
- recent.append(now)
- _rate_hits[key] = recent
- # Drop addresses with nothing left in their window so the table stays small.
+ if len(recent) >= count:
+ retry_after = int(window - (now - recent[0])) + 1
+ abort(429, description=f"Too many attempts. Try again in {retry_after} seconds.")
+ for key, _ in checks:
+ _rate_hits[key].append(now)
+ # Drop keys with nothing left in the longest window so the table stays small.
if len(_rate_hits) > 10000:
- for stale in [k for k, hits in _rate_hits.items() if now - hits[-1] >= RATE_LIMITS[k[0]][1]]:
+ longest = max(window for _, window in [*RATE_LIMITS.values(), *ACCOUNT_RATE_LIMITS.values()])
+ for stale in [k for k, hits in _rate_hits.items() if not hits or now - hits[-1] >= longest]:
del _rate_hits[stale]
diff --git a/docs/campus_map.svg b/docs/campus_map.svg
new file mode 100644
index 0000000..9acf4b2
--- /dev/null
+++ b/docs/campus_map.svg
@@ -0,0 +1,96 @@
+
diff --git a/tests/test_app.py b/tests/test_app.py
index 87fe9a6..46e82e8 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -176,6 +176,27 @@ def test_repeated_failed_logins_are_limited(self):
# Viewing the page is not a POST, so it is never limited.
self.assertEqual(self.client.get("/login").status_code, 200)
+ def test_a_class_on_one_address_can_sign_up_and_sign_in(self):
+ """Campus Wi-Fi puts a whole class behind one address."""
+ self.enable_rate_limits()
+ for n in range(30):
+ response = self.post("/register", data={"name": f"S{n}", "email": f"s{n}@example.com",
+ "password": "secret123"})
+ self.assertNotEqual(response.status_code, 429, n)
+ self.post("/logout")
+ self.assertEqual(self.post("/register", data={"name": "X", "email": "x@example.com",
+ "password": "secret123"}).status_code, 429)
+ _rate_hits.clear()
+ # Many students signing in at once, each once, is fine...
+ for n in range(30):
+ self.assertNotEqual(self.post("/login", data={"email": f"s{n}@example.com", "password": "secret123"}).status_code, 429)
+ self.post("/logout")
+ # ...but guessing one account's password is still stopped after 10 tries.
+ for _ in range(10):
+ self.post("/login", data={"email": "s1@example.com", "password": "wrong"})
+ self.assertEqual(self.post("/login", data={"email": "s1@example.com", "password": "wrong"}).status_code, 429)
+ self.assertNotEqual(self.post("/login", data={"email": "s2@example.com", "password": "wrong"}).status_code, 429)
+
def test_rate_limits_are_counted_per_client_address(self):
self.enable_rate_limits()
bad = {"email": "nobody@example.com", "password": "wrong"}
@@ -481,7 +502,16 @@ def test_desk_receives_first_and_the_finder_confirms_or_disputes(self):
self.login("finder@example.com")
home = self.client.get("/").data
self.assertEqual(home.count(b"Was that you?"), 2)
- self.post(f"/item/{first}/handover-check", data={"answer": "yes", "next": "/"})
+ # Nobody else can answer the finder's question.
+ self.logout()
+ self.register("Someone", "someone@example.com")
+ self.post(f"/item/{first}/handover-check", data={"answer": "no"})
+ with app.app_context():
+ self.assertEqual(db.session.get(Item, first).finder_check, "pending")
+ self.logout()
+ self.login("finder@example.com")
+ response = self.post(f"/item/{first}/handover-check", data={"answer": "yes", "next": "/me"})
+ self.assertTrue(response.headers["Location"].endswith("/me"))
with mock.patch("app.send_email") as sent:
response = self.post(f"/item/{second}/handover-check", data={"answer": "no", "next": "//evil.example"})
self.assertEqual(sent.call_args.args[0], "admin@example.com")
@@ -496,6 +526,42 @@ def test_desk_receives_first_and_the_finder_confirms_or_disputes(self):
self.assertIn(b"not theirs", desk)
self.assertIn(b"Red cap", desk.split(b"not theirs", 1)[1])
+ def test_the_desk_only_receives_found_items_it_is_waiting_for(self):
+ self.register_staff()
+ self.report("Lost scarf", "Red scarf", "Clothing", "Gym", "Lost")
+ self.logout()
+ item_id = self.found_item()
+ self.login("desk@example.com")
+ with app.app_context():
+ scarf = Item.query.filter_by(title="Lost scarf").one()
+ scarf.custody = "awaiting"
+ db.session.commit()
+ scarf_id = scarf.id
+ self.post(f"/desk/item/{scarf_id}/received")
+ # Not received only answers a finder who said they handed it in.
+ self.post(f"/desk/item/{item_id}/not-received")
+ with app.app_context():
+ self.assertEqual(db.session.get(Item, scarf_id).custody, "awaiting")
+ self.assertEqual(db.session.get(Item, item_id).custody, "awaiting")
+ self.assertEqual(len(db.session.get(Item, item_id).events), 1)
+
+ def test_staff_receiving_their_own_report_skip_the_handover_check(self):
+ self.register_staff()
+ with app.app_context():
+ staff = User.query.filter_by(email="desk@example.com").one()
+ item = Item(title="Umbrella", description="Black", category="Accessories", location="Gym",
+ status="Found", reporter_name=staff.name, contact=staff.email, owner_id=staff.id,
+ custody="awaiting")
+ db.session.add(item)
+ db.session.commit()
+ item_id = item.id
+ with mock.patch("app.send_email") as sent:
+ self.post(f"/desk/item/{item_id}/received")
+ sent.assert_not_called()
+ with app.app_context():
+ self.assertIsNone(db.session.get(Item, item_id).finder_check)
+ self.assertNotIn(b"Was that you?", self.client.get("/").data)
+
def test_only_the_finder_can_mark_an_item_handed_in(self):
item_id = self.found_item()
self.register("Someone", "someone@example.com")
diff --git a/tools/build_campus.py b/tools/build_campus.py
index c25088c..e8479a5 100644
--- a/tools/build_campus.py
+++ b/tools/build_campus.py
@@ -324,9 +324,46 @@ def main():
data["roads"].append({"id": road_id, "name": shown, "points": [shift(pt) for pt in points],
"aliases": [name.lower(), *words, *(w.replace("road", "path") for w in words)]})
OUT.write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
+ draw_map(data)
print(f"{OUT.name}: {len(data['places'])} places, {len(data['roads'])} roads, "
f"{len(nodes)} nodes, {len(edges)} edges")
+MAP_IMAGE = OUT.parents[1] / "docs" / "campus_map.svg"
+COLOURS = {"bit": ("#d2e6d9", "#4f8a6b"), "block": ("#e8eae6", "#a9b0a8"), "parking": ("#f1f2ef", "#a9b0a8"),
+ "small": ("#e8eae6", "#a9b0a8"), "gate": ("#f2d48d", "#b8923b")}
+
+
+def draw_map(data):
+ """docs/campus_map.svg for the README: the same places and paths the app draws, labelled."""
+ w, h = data["viewBox"][2], data["viewBox"][3]
+ out = [f'")
+ MAP_IMAGE.write_text("\n".join(out) + "\n", encoding="utf-8")
+
+
if __name__ == "__main__":
main()