Module 2 · APIs, Reports and the Detector Project · Lesson 7 of 9
Guided project: build a failed-login detector
Validate timestamps, group failures, slide a five-minute window with a deque, alert once per burst, and test the edge cases.
In this lesson · about 50 minutes
- Parse time-zone-aware timestamps and normalise to UTC
- Implement a sliding window with clear boundary rules
- Test the detector against fixtures, including shuffled input
Setup: Python 3 with the standard library: csv, datetime, collections and json. The fixture cyber-login.csv already has what you need: normal events, failure bursts, malformed rows and records out of order.
The six steps
- Fixture. Columns
timestamp,user,source_ip,outcome, with UTC ISO timestamps like2026-11-10T09:00:00+00:00. - Parse and validate with
csv.DictReaderanddatetime.fromisoformat. Require time-zone-aware timestamps (a time with no zone is ambiguous), normalise to UTC, and count rejected rows. - Group failures by
(user, source_ip), sort each group by time, and keep adequeof recent failures. Drop events older than five minutes relative to the current one. - Alert when five or more failures are in the window. Boundary rule: an event exactly five minutes old is included. Suppression rule: one alert per burst; a new alert needs the window to drop below the threshold first.
- Output JSON with account, source IP, count, window start and end, plus processing totals. Add configurable threshold and window once the core works.
- Test: five failures in the window alert; four don't; five spread over ten minutes don't; successes are ignored; malformed rows are counted; shuffled input gives the same result.
Look at the fixture
Before writing logic, read the data. Find the two root bursts, carol's slow failures, dave's four, and the three rows that should be rejected.
Exercise
Step 2: parse and validate
Write parse_rows(path) returning (events, rejected). Each event is a dict with ts (an aware datetime in UTC), user, source_ip and outcome (lower-cased). Reject (and count) a row if: a field is blank, the outcome isn't success/failure, the timestamp doesn't parse, or it has no time zone.
Exercise
Steps 3 and 4: the sliding window
parse_rows and events are ready. Write detect(events, threshold=5, window=timedelta(minutes=5)) returning a list of alerts. Each alert is a dict with user, source_ip, count, window_start and window_end (ISO strings via .isoformat()). Process groups in sorted (user, source_ip) order. Include events exactly five minutes old, and alert once per burst.
Code that runs before yours
import csv
from collections import defaultdict, deque
from datetime import datetime, timezone, timedelta
def parse_rows(path):
events, rejected = [], 0
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
try:
user = (row.get("user") or "").strip()
ip = (row.get("source_ip") or "").strip()
outcome = (row.get("outcome") or "").strip().lower()
ts = datetime.fromisoformat((row.get("timestamp") or "").strip())
if not user or not ip or outcome not in ("success", "failure"):
raise ValueError("missing or bad field")
if ts.tzinfo is None:
raise ValueError("timestamp has no time zone")
except ValueError:
rejected += 1
continue
events.append({"ts": ts.astimezone(timezone.utc), "user": user,
"source_ip": ip, "outcome": outcome})
return events, rejected
events, rejected = parse_rows("cyber-login.csv")
Step 6: the full detector with its tests
Here's the complete detector with the test cases from step 6. Run it. Then break something on purpose (change > to >= in the window, or remove .lower()) and watch which test fails.
Exercises solved: 0 of 2
Noviq Academy is free and for learning. All data in this course is synthetic and uses documentation IP ranges. Never paste real authentication logs or credentials into online tools. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.