File size: 13,958 Bytes
57c1397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
"""Task definitions, baseline trajectories, and grader logic."""

from __future__ import annotations

from copy import deepcopy

try:
    from ..models import (
        BaselineActionStep,
        BaselineCatalog,
        BaselineDefinition,
        GraderCheck,
        GraderReport,
        PatchOption,
        TaskCatalog,
        TaskDefinition,
    )
except ImportError:
    from models import (  # type: ignore
        BaselineActionStep,
        BaselineCatalog,
        BaselineDefinition,
        GraderCheck,
        GraderReport,
        PatchOption,
        TaskCatalog,
        TaskDefinition,
    )

ENVIRONMENT_NAME = "websec_repair_env"
DEFAULT_TASK_ID = "sqli_login"

_PATCH_WEIGHTS = {
    "classification": 0.25,
    "patch": 0.35,
    "exploit": 0.20,
    "functionality": 0.15,
    "submit": 0.05,
}

TASKS = {
    "sqli_login": {
        "definition": TaskDefinition(
            id="sqli_login",
            difficulty="easy",
            title="Patch the vulnerable login query",
            instruction=(
                "Inspect the login handler, classify the vulnerability, choose one patch, "
                "verify exploit blocking and functionality preservation, then submit."
            ),
            code_snippet=(
                "def login(username, password):\n"
                "    query = (\n"
                "        \"SELECT id FROM users WHERE username = '\" + username + \"' \"\n"
                "        \"AND password = '\" + password + \"'\"\n"
                "    )\n"
                "    return db.execute(query).fetchone()\n"
            ),
            scanner_hint=(
                "Scanner warning: SQL injection risk detected in login query due to "
                "string concatenation with user-controlled input."
            ),
            patch_options=[
                PatchOption(id="parameterized_query", label="Use parameterized query"),
                PatchOption(id="strip_quotes", label="Strip quotes from input"),
                PatchOption(id="disable_login", label="Disable login route"),
            ],
        ),
        "correct_vulnerability": "sql_injection",
        "correct_patch": "parameterized_query",
        "verify": {
            "parameterized_query": (
                True,
                True,
                "Exploit is blocked and valid logins still work with bound parameters.",
            ),
            "strip_quotes": (
                False,
                True,
                "Input filtering is incomplete; the injection path is still reachable.",
            ),
            "disable_login": (
                True,
                False,
                "Attack path is gone because login is disabled, but legitimate users are locked out.",
            ),
        },
    },
    "xss_comments": {
        "definition": TaskDefinition(
            id="xss_comments",
            difficulty="medium",
            title="Stop script execution in comment rendering",
            instruction=(
                "Inspect the comment renderer, classify the vulnerability, choose one patch, "
                "verify exploit blocking and functionality preservation, then submit."
            ),
            code_snippet=(
                "def render_comment(comment):\n"
                '    return f"<div class=\\"comment\\">{comment}</div>"\n'
            ),
            scanner_hint=(
                "Scanner warning: Cross-site scripting risk detected because comment text is "
                "rendered into HTML without escaping."
            ),
            patch_options=[
                PatchOption(id="html_escape", label="Escape comment before rendering"),
                PatchOption(id="remove_script_substring", label="Remove 'script' substring"),
                PatchOption(id="disable_comment_rendering", label="Hide comments completely"),
            ],
        ),
        "correct_vulnerability": "xss",
        "correct_patch": "html_escape",
        "verify": {
            "html_escape": (
                True,
                True,
                "Malicious payloads render as text and normal comments still display.",
            ),
            "remove_script_substring": (
                False,
                True,
                "Substring filtering misses alternate payloads; comments still render.",
            ),
            "disable_comment_rendering": (
                True,
                False,
                "No script runs because comments are removed, but legitimate content is gone too.",
            ),
        },
    },
    "broken_auth_admin": {
        "definition": TaskDefinition(
            id="broken_auth_admin",
            difficulty="hard",
            title="Restore admin-only access control",
            instruction=(
                "Inspect the admin route, classify the vulnerability, choose one patch, "
                "verify exploit blocking and functionality preservation, then submit."
            ),
            code_snippet=(
                "@app.get('/admin')\n"
                "def admin_panel(current_user):\n"
                "    if not current_user:\n"
                "        raise UnauthorizedError()\n"
                "    return render_admin_dashboard()\n"
            ),
            scanner_hint=(
                "Scanner warning: Broken access control. Authenticated non-admin users can reach "
                "the admin route because role enforcement is missing."
            ),
            patch_options=[
                PatchOption(id="require_admin_role", label="Enforce admin role server-side"),
                PatchOption(id="hide_admin_link", label="Hide the admin link in UI"),
                PatchOption(id="deny_all_admin_access", label="Block all admin route traffic"),
            ],
        ),
        "correct_vulnerability": "broken_auth",
        "correct_patch": "require_admin_role",
        "verify": {
            "require_admin_role": (
                True,
                True,
                "Non-admin users are denied while legitimate admins still reach the dashboard.",
            ),
            "hide_admin_link": (
                False,
                True,
                "The UI hides the link, but direct requests still bypass authorization.",
            ),
            "deny_all_admin_access": (
                True,
                False,
                "The bypass is gone, but valid admins are blocked too.",
            ),
        },
    },
}

BASELINES = {
    task_id: BaselineDefinition(
        task_id=task_id,
        title=f"{task['definition'].title} baseline",
        description="Inspect, classify correctly, apply the safe patch, verify, then submit.",
        actions=[
            BaselineActionStep(action_type="inspect"),
            BaselineActionStep(
                action_type="classify",
                vulnerability_type=task["correct_vulnerability"],
            ),
            BaselineActionStep(
                action_type="apply_patch",
                patch_id=task["correct_patch"],
            ),
            BaselineActionStep(action_type="verify"),
            BaselineActionStep(action_type="submit"),
        ],
    )
    for task_id, task in TASKS.items()
}


def _blank_progress(task_id: str) -> dict[str, object]:
    try:
        task = TASKS[task_id]["definition"]
    except KeyError as exc:
        valid = ", ".join(sorted(TASKS))
        raise ValueError(f"Unknown task_id {task_id!r}. Expected one of: {valid}") from exc
    return {
        "task_id": task.id,
        "difficulty": task.difficulty,
        "inspected": False,
        "selected_vulnerability": "",
        "applied_patch_id": "",
        "exploit_test_passed": False,
        "functionality_test_passed": False,
        "submitted": False,
        "score": 0.0,
    }


_CURRENT_PROGRESS = _blank_progress(DEFAULT_TASK_ID)


def get_task(task_id: str) -> TaskDefinition:
    """Resolve one public task definition."""
    try:
        return TASKS[task_id]["definition"]
    except KeyError as exc:
        valid = ", ".join(sorted(TASKS))
        raise ValueError(f"Unknown task_id {task_id!r}. Expected one of: {valid}") from exc


def list_tasks() -> TaskCatalog:
    """Return the task catalog."""
    return TaskCatalog(
        environment=ENVIRONMENT_NAME,
        default_task_id=DEFAULT_TASK_ID,
        tasks=[TASKS["sqli_login"]["definition"], TASKS["xss_comments"]["definition"], TASKS["broken_auth_admin"]["definition"]],
    )


def list_baselines(task_id: str | None = None) -> BaselineCatalog:
    """Return all baseline trajectories or one filtered trajectory."""
    if task_id is None:
        baselines = [BASELINES["sqli_login"], BASELINES["xss_comments"], BASELINES["broken_auth_admin"]]
    else:
        get_task(task_id)
        baselines = [BASELINES[task_id]]
    return BaselineCatalog(environment=ENVIRONMENT_NAME, baselines=baselines)


def get_baseline(task_id: str) -> BaselineDefinition:
    """Return one baseline trajectory."""
    get_task(task_id)
    return BASELINES[task_id]


def reset_runtime_progress(task_id: str) -> dict[str, object]:
    """Reset the shared runtime snapshot for the requested task."""
    global _CURRENT_PROGRESS
    _CURRENT_PROGRESS = _blank_progress(task_id)
    return deepcopy(_CURRENT_PROGRESS)


def set_runtime_progress(progress: dict[str, object]) -> dict[str, object]:
    """Replace the shared runtime snapshot with the provided progress."""
    global _CURRENT_PROGRESS
    task_id = str(progress.get("task_id", DEFAULT_TASK_ID))
    get_task(task_id)
    merged = _blank_progress(task_id)
    merged.update(progress)
    _CURRENT_PROGRESS = merged
    return deepcopy(_CURRENT_PROGRESS)


def current_runtime_progress() -> dict[str, object]:
    """Return the current shared runtime snapshot."""
    return deepcopy(_CURRENT_PROGRESS)


def verification_outcome(task_id: str, patch_id: str | None) -> tuple[bool, bool, str]:
    """Evaluate exploit and functionality checks for the selected patch."""
    get_task(task_id)
    if not patch_id:
        return False, False, "No patch has been applied yet, so both checks fail."
    try:
        return TASKS[task_id]["verify"][patch_id]
    except KeyError as exc:
        valid = ", ".join(option.id for option in TASKS[task_id]["definition"].patch_options)
        raise ValueError(f"Unknown patch_id {patch_id!r}. Expected one of: {valid}") from exc


def grade_task(
    task_id: str | None = None,
    progress: dict[str, object] | None = None,
) -> GraderReport:
    """Grade either the provided progress snapshot or the shared runtime state."""
    if progress is None:
        if task_id is None:
            working = current_runtime_progress()
        else:
            get_task(task_id)
            working = current_runtime_progress()
            if working["task_id"] != task_id:
                working = _blank_progress(task_id)
    else:
        working = deepcopy(progress)
        task_id = str(working.get("task_id", task_id or DEFAULT_TASK_ID))
        get_task(task_id)

    resolved_task_id = str(task_id or working["task_id"])
    task = TASKS[resolved_task_id]

    classification_correct = working.get("selected_vulnerability") == task["correct_vulnerability"]
    patch_correct = working.get("applied_patch_id") == task["correct_patch"]
    exploit_blocked = bool(working.get("exploit_test_passed", False))
    functionality_preserved = bool(working.get("functionality_test_passed", False))
    successful_submit = (
        bool(working.get("submitted", False))
        and classification_correct
        and patch_correct
        and exploit_blocked
        and functionality_preserved
    )

    score = 0.0
    if classification_correct:
        score += _PATCH_WEIGHTS["classification"]
    if patch_correct:
        score += _PATCH_WEIGHTS["patch"]
    if exploit_blocked:
        score += _PATCH_WEIGHTS["exploit"]
    if functionality_preserved:
        score += _PATCH_WEIGHTS["functionality"]
    if successful_submit:
        score += _PATCH_WEIGHTS["submit"]

    checks = [
        GraderCheck(
            name="classification_correct",
            passed=classification_correct,
            detail=(
                f"Expected {task['correct_vulnerability']!r}; "
                f"received {working.get('selected_vulnerability', '')!r}."
            ),
        ),
        GraderCheck(
            name="patch_correct",
            passed=patch_correct,
            detail=(
                f"Expected {task['correct_patch']!r}; "
                f"received {working.get('applied_patch_id', '')!r}."
            ),
        ),
        GraderCheck(
            name="exploit_blocked",
            passed=exploit_blocked,
            detail=(
                "Verify step confirms the exploit is blocked."
                if exploit_blocked
                else "Exploit is still possible or verify has not been run."
            ),
        ),
        GraderCheck(
            name="functionality_preserved",
            passed=functionality_preserved,
            detail=(
                "Verify step confirms legitimate behavior still works."
                if functionality_preserved
                else "Legitimate behavior is broken or verify has not been run."
            ),
        ),
        GraderCheck(
            name="submitted",
            passed=successful_submit,
            detail=(
                "Task was submitted after all required checks passed."
                if successful_submit
                else "Submit bonus only applies after the correct verified repair is submitted."
            ),
        ),
    ]

    passed = all(check.passed for check in checks)
    message = "Task solved." if passed else "Task is not solved yet."
    return GraderReport(
        task_id=resolved_task_id,
        passed=passed,
        score=round(score, 2),
        message=message,
        checks=checks,
    )