Ch 08Capstone Project: Build Inbox Guardian
Chapter 08 of 08·35 min

Capstone Project: Build Inbox Guardian

You have arrived at the flagship capstone milestone of Workshop 1. Rather than writing disconnected toy scripts, you will now synthesize all 7 chapters—variables, types, string methods, branching conditions, loops, structured collections, and modular functions—into an end-to-end command-line application: INBOX GUARDIAN. You will architect, implement, test, and debug a rule-based email threat scanner capable of parsing raw messages, extracting structural heuristics, computing weighted risk scores, and generating security quarantine verdicts.

Learning objectives
  • 01Synthesize all Workshop 1 competencies into a complete, modular, command-line Python application
  • 02Implement an end-to-end heuristic pipeline: text normalization, keyword matching, structural anomaly detection, and classification
  • 03Calculate structural threat heuristics including uppercase character density and exclamation mark frequency with zero-division safeguards
  • 04Manage in-memory datasets using lists of dictionaries to log scan histories and generate executive summary statistics
  • 05Differentiate deterministic rule-based heuristic engineering from future statistical machine learning classification models
  • 06Handle critical production edge cases: zero-alphabetic strings, empty inboxes, and case-obfuscation attacks

8.1 System Architecture: The Heuristic Rule-Based Pipeline

Before machine learning models (like Naive Bayes, Random Forests, or Transformers) were invented, cybersecurity systems relied entirely on **deterministic, rule-based heuristic engines**. ### The Inbox Guardian Pipeline: 1. **Ingestion & Sanitization**: Raw email messages are stripped of extraneous whitespace and normalized to lowercase. 2. **Keyword Threat Scoring**: The text is scanned against dictionaries of known phishing, credential-harvesting, and financial-lure keywords. 3. **Structural Heuristic Analysis**: The engine computes structural anomalies: uppercase character density (spammers frequently SHOUT) and excessive punctuation. 4. **Risk Aggregation**: All feature scores are aggregated into a composite risk score (0 to 100). 5. **Classification**: Threshold logic categorizes the message into **CLEAN**, **SUSPICIOUS**, or **QUARANTINE**. 6. **Batch Auditing & Reporting**: In-memory historical logs accumulate threat statistics.
The Pedagogical Boundary: Why Heuristics Precede Machine Learning
Inbox Guardian is deliberately built as a **purely rule-based Python application**. Understanding explicit heuristic decision boundaries teaches you the exact features that machine learning models learn to extract automatically in subsequent workshops.

8.2 Module 1 & 2: Text Normalization & Keyword Matching

Attackers frequently obfuscate keywords using erratic casing (e.g. `uRgEnT` or `F-R-E-E`). The first stage of the engine normalizes incoming strings using `.strip()` and `.lower()`, and scans across a dictionary of threat terms. ```python def scan_keywords(text, keyword_weights): score = 0 matched = [] cleaned = text.lower() for kw, weight in keyword_weights.items(): if kw in cleaned: matched.append(kw) score += weight return score, matched ```
Module 1 & 2: Keyword Heuristics Engine

Scanning normalized text against weighted threat categories.

def scan_keywords(text, keyword_weights):
    """Scans text for keywords and returns accumulated weight and matched terms."""
    cleaned = text.strip().lower()
    score = 0
    matched = []
    
    for keyword, weight in keyword_weights.items():
        if keyword in cleaned:
            matched.append(keyword)
            score += weight
            
    return score, matched

# Threat dictionary with weighted risks
RULES = {
    "urgent": 25,
    "verify account": 30,
    "free prize": 35,
    "wire transfer": 40,
    "password expired": 25
}

sample = "  URGENT: Please verify account access to claim prize!  "
pts, terms = scan_keywords(sample, RULES)
print("Detected Terms :", terms)
print("Keyword Points :", pts)
Execution walkthrough
  1. 1.Line 3: Strips and converts sample to lowercase.
  2. 2.Lines 7-10: Checks each keyword; finds 'urgent' (+25) and 'verify account' (+30).
  3. 3.Line 12: Returns accumulated score 55 and list of matched terms.
Expected output
Detected Terms : ['urgent', 'verify account']
Keyword Points : 55
Edge cases

• Substring collision: 'free' would match 'freeze'. In production regex or token matching, word boundaries are checked. For our foundations workshop, phrase matching handles multi-word triggers like 'verify account'.

Why it happens: The 'in' operator tests substring presence in O(n) time.

8.3 Module 3 & 4: Structural Anomaly Detection & Risk Classification

Phishing emails frequently exhibit distinct structural anomalies: 1. **Excessive Uppercase Ratio**: Spammers use caps to convey artificial urgency (`CLAIM YOUR REWARD NOW`). 2. **Exclamation Density**: Overuse of exclamation marks (`!!!`). ### The Uppercase Ratio Formula with Zero-Division Guard: $$\text{Uppercase Ratio} = \frac{\text{Count of Uppercase Letters}}{\text{Total Alphabetic Letters}}$$ *Critical Guard: If an email consists entirely of numbers or punctuation (`123456 !!!`), total alphabetic letters is 0! Dividing by zero will crash the application with a `ZeroDivisionError`. You MUST check `if total_letters > 0:` first!*
Module 3 & 4: Structural Heuristics with Zero-Division Protection

Calculating uppercase ratio and exclamation density safely.

def calculate_structural_risk(text):
    """Calculates structural risk points based on caps ratio and exclamation marks."""
    points = 0
    letters = [c for c in text if c.isalpha()]
    total_letters = len(letters)
    
    # Zero-division defensive guard!
    if total_letters > 0:
        upper_count = len([c for c in letters if c.isupper()])
        caps_ratio = upper_count / total_letters
        if caps_ratio > 0.30:   # Over 30% uppercase
            points += 20
    else:
        caps_ratio = 0.0
        
    exclamation_count = text.count("!")
    if exclamation_count >= 2:
        points += 15
        
    return points, caps_ratio, exclamation_count

# Test on shouting email
sample_shouting = "URGENT ACTION NEEDED IMMEDIATELY!!!"
pts, ratio, ex_count = calculate_structural_risk(sample_shouting)
print(f"Caps Ratio : {ratio:.1%} (+{pts} pts, {ex_count} exclamations)")
Execution walkthrough
  1. 1.Line 4: Extracts all alphabetic characters.
  2. 2.Line 8: Verifies total_letters > 0 before dividing.
  3. 3.Line 10: Caps ratio is 100% (> 30%) -> adds 20 points.
  4. 4.Line 17: Exclamation count is 3 (>= 2) -> adds 15 points.
  5. 5.Line 24: Outputs 100.0% ratio and 35 risk points.
Expected output
Caps Ratio : 100.0% (+35 pts, 3 exclamations)
Edge cases

• Non-alphabetic input: If text is '123456789', total_letters is 0. Without the guard, upper_count / total_letters causes ZeroDivisionError: division by zero.

Why it happens: Heuristic rules combine text statistics with keyword scores to create resilient multi-factor classifiers.

8.4 Module 5: Batch Scanning & Summary Statistics

Enterprise security tools do not scan messages one at a time; they process batch streams of hundreds of messages and maintain an in-memory audit log. In this module, you iterate over a **List of Dictionaries** representing simulated incoming emails, run the multi-factor scoring engine on each, log the results, and calculate summary statistics: total scanned, quarantine rate percentage, and average risk score.
Module 5: In-Memory Batch Inspection & Reporting

Batch scanning email records and accumulating departmental statistics.

inbox_batch = [
    {"id": "MSG-01", "sender": "support@datacorp.com", "body": "Meeting agenda for today at 3pm."},
    {"id": "MSG-02", "sender": "billing@external.xyz", "body": "URGENT: Verify account or access suspended immediately!!!"},
    {"id": "MSG-03", "sender": "colleague@datacorp.com", "body": "Please review the attached project slide draft."}
]

def classify_risk(total_score):
    if total_score >= 60:
        return "QUARANTINE"
    elif total_score >= 30:
        return "SUSPICIOUS"
    return "CLEAN"

# Batch audit
history = []
for msg in inbox_batch:
    # Simulated score for demonstration
    score = 85 if "urgent" in msg["body"].lower() else 5
    verdict = classify_risk(score)
    
    # Log record
    history.append({
        "id": msg["id"],
        "sender": msg["sender"],
        "score": score,
        "verdict": verdict
    })

print("=== BATCH AUDIT REPORT ===")
for rec in history:
    print(f"[{rec['id']}] {rec['verdict']:<12} | Score: {rec['score']:>2} | Sender: {rec['sender']}")
Execution walkthrough
  1. 1.Lines 1-5: Defines batch dataset of simulated incoming messages.
  2. 2.Lines 15-26: Loops over batch, computes scores, and logs to history list of dictionaries.
  3. 3.Lines 28-30: Emits formatted tabular report.
Expected output
=== BATCH AUDIT REPORT ===
[MSG-01] CLEAN        | Score:  5 | Sender: support@datacorp.com
[MSG-02] QUARANTINE   | Score: 85 | Sender: billing@external.xyz
[MSG-03] CLEAN        | Score:  5 | Sender: colleague@datacorp.com
Edge cases

• Empty batch stream: If inbox_batch is empty `[]`, calculating average score by dividing by `len(inbox_batch)` raises ZeroDivisionError! Always verify `if len(inbox_batch) > 0:` before computing averages.

Why it happens: Lists of dictionaries provide a clean in-memory database representation.

8.5 Module 6: The Interactive Terminal Menu Loop

To make Inbox Guardian a truly standalone tool, we wrap the engine in a **`while True` command-line interface (CLI) menu loop**. ### The CLI Menu Pattern: 1. Print the menu options (1: Scan Email, 2: Batch Scan, 3: View History, 4: View Statistics, 0: Exit). 2. Accept user input using `input('Choose option: ').strip()`. 3. Dispatch to the corresponding function using an `if-elif-else` ladder. 4. If user chooses `'0'`, print an exit message and call **`break`** to terminate the loop.

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 8: Classification Decision Boundary

basic

Modify the starter code to implement classify_message(score) which returns 'QUARANTINE' if score >= 60, 'SUSPICIOUS' if score >= 30, and 'CLEAN' otherwise. Test with score = 75 and print the returned status.

Chapter 08 assignmentMilestone

Inbox Guardian Enterprise: Heuristic Threat Auditor

Scenario

You are the lead security software engineer at the Center of Excellence. You have been commissioned to build the production engine for INBOX GUARDIAN. The tool must parse raw incoming messages, compute multi-factor threat scores (combining weighted keywords, uppercase density, and exclamation marks), assign quarantine verdicts, log scan histories in memory, and generate an executive risk report.

Implementation requirements
  • Define multi-tier keyword dictionary: {'urgent': 25, 'verify account': 30, 'free prize': 35, 'wire transfer': 40, 'suspended': 25}.
  • Implement scan_message(text: str, keyword_rules: dict) -> dict:
  • - Normalize text with .strip() and .lower().
  • - Accumulate keyword score and store matched terms in a list.
  • - Calculate uppercase ratio safely (guarding against zero-division): +20 pts if caps ratio > 0.30.
  • - Calculate exclamation density: +15 pts if text.count('!') >= 2.
  • - Compute total_risk = keyword_score + structural_score (capped at 100).
  • - Determine verdict: 'QUARANTINE' if total_risk >= 60, 'SUSPICIOUS' if total_risk >= 30, else 'CLEAN'.
  • - Return result dictionary: {'text': text[:45], 'score': total_risk, 'matched': matched, 'verdict': verdict}.
  • Batch process a sample list of 4 simulated emails:
  • 1. 'Reminder: Data Science workshop begins at 10 AM in Lab 3.'
  • 2. 'URGENT: Your account has been suspended! Please verify credentials immediately!'
  • 3. 'Congratulations! You won a free prize. Claim your wire transfer now.'
  • 4. 'Please review the attached project draft when you have a moment.'
  • Store all result dictionaries into an in-memory scan_history list.
  • Generate an Executive Security Summary: Total Scanned, Quarantine Count, Suspicious Count, Clean Count, and Threat Ratio percentage.
Edge cases to handle
  • 1.Zero alphabetic characters: Message '123456789 !!!' must not crash with ZeroDivisionError when computing uppercase ratio.
  • 2.Empty text: Blank input '' must return score = 0, verdict = 'CLEAN'.
  • 3.Capping risk score: Ensure total_risk does not exceed 100.
Starter template
# Chapter 8 Capstone Assignment: INBOX GUARDIAN ENTERPRISE
# Center of Excellence: Data Science & AI

KEYWORDS = {
    "urgent": 25,
    "verify account": 30,
    "free prize": 35,
    "wire transfer": 40,
    "suspended": 25
}

SAMPLE_EMAILS = [
    "Reminder: Data Science workshop begins at 10 AM in Lab 3.",
    "URGENT: Your account has been suspended! Please verify credentials immediately!",
    "Congratulations! You won a free prize. Claim your wire transfer now.",
    "Please review the attached project draft when you have a moment."
]

# TODO: Step 1 - Define scan_message(text, keyword_rules)
# TODO: Step 2 - Implement keyword matching and structural heuristics with zero-division guard
# TODO: Step 3 - Assign verdict (QUARANTINE, SUSPICIOUS, CLEAN)
# TODO: Step 4 - Batch scan SAMPLE_EMAILS and append results to scan_history list
# TODO: Step 5 - Print formatted audit roster and executive summary metrics
Progressive hints

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01Rule-based systems use deterministic heuristic logic (keywords + structural thresholds) to make automated decisions.
  • 02Always guard against zero-division when calculating ratios like uppercase density: verify denominator > 0.
  • 03The modular architecture separates sanitization, keyword scoring, structural features, and classification.
  • 04In-memory datasets (lists of dictionaries) enable high-throughput batch inspection and statistical summaries.
  • 05Heuristic rule engineering provides the foundation for feature engineering in modern machine learning.
Syntax reference
result = scan_message(text, rules)Encapsulating multi-factor security heuristics into pure modular functions.
ratio = upper_count / len(letters) if len(letters) > 0 else 0.0Zero-division guarded density formula.
history.append({'score': total, 'verdict': verdict})Appending structured audit dictionaries to historical logs.

Knowledge check

Verify your grasp of the chapter concepts

What mathematical protection is essential when calculating text character ratios?

What is the primary architectural difference between heuristics and machine learning?

How is an email audit history best represented in native Python memory?

Further reading

Programiz Python programming guide

Visit Programiz for additional Python syntax examples and language reference

Open Programiz