Spaces:
Sleeping
Sleeping
File size: 8,137 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 | """Environment implementation for deterministic web security repair tasks."""
from __future__ import annotations
from typing import Any
from uuid import uuid4
from openenv.core.env_server.interfaces import Environment
from openenv.core.env_server.types import EnvironmentMetadata
try:
from ..models import WebSecRepairAction, WebSecRepairObservation, WebSecRepairState
from .challenge import (
DEFAULT_TASK_ID,
TASKS,
get_task,
grade_task,
reset_runtime_progress,
set_runtime_progress,
verification_outcome,
)
except ImportError:
from models import WebSecRepairAction, WebSecRepairObservation, WebSecRepairState # type: ignore
from server.challenge import ( # type: ignore
DEFAULT_TASK_ID,
TASKS,
get_task,
grade_task,
reset_runtime_progress,
set_runtime_progress,
verification_outcome,
)
MAX_STEPS = 6
class WebSecRepairEnvironment(
Environment[WebSecRepairAction, WebSecRepairObservation, WebSecRepairState]
):
"""Lean deterministic environment for vulnerability classification and repair."""
SUPPORTS_CONCURRENT_SESSIONS: bool = False
def __init__(self) -> None:
super().__init__()
default_task = get_task(DEFAULT_TASK_ID)
self._state = WebSecRepairState(
episode_id=str(uuid4()),
step_count=0,
task_id=default_task.id,
difficulty=default_task.difficulty,
inspected=False,
selected_vulnerability="",
applied_patch_id="",
exploit_test_passed=False,
functionality_test_passed=False,
submitted=False,
score=0.0,
)
set_runtime_progress(self._state.model_dump())
def reset(
self,
seed: int | None = None,
episode_id: str | None = None,
**kwargs: Any,
) -> WebSecRepairObservation:
del seed
task_id = kwargs.get("task_id", DEFAULT_TASK_ID)
task = get_task(task_id)
reset_runtime_progress(task_id)
self._state = WebSecRepairState(
episode_id=episode_id or str(uuid4()),
step_count=0,
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,
)
set_runtime_progress(self._state.model_dump())
return self._build_observation(
status_message="Task loaded. Use inspect to reveal the snippet, hint, and patch options.",
reward=0.0,
done=False,
)
def step(
self,
action: WebSecRepairAction,
timeout_s: float | None = None,
**kwargs: Any,
) -> WebSecRepairObservation:
del timeout_s, kwargs
previous_score = self._state.score
self._state.step_count += 1
status_message = ""
if self._state.submitted:
status_message = "Episode already submitted. Reset before taking more actions."
elif action.action_type == "inspect":
self._state.inspected = True
status_message = "Inspection complete. The vulnerable snippet, scanner hint, and patch options are now visible."
elif action.action_type == "classify":
if not action.vulnerability_type:
status_message = "Classification failed: vulnerability_type is required."
else:
self._state.selected_vulnerability = action.vulnerability_type
status_message = f"Stored vulnerability classification {action.vulnerability_type!r}."
elif action.action_type == "apply_patch":
if not action.patch_id:
status_message = "Patch application failed: patch_id is required."
else:
valid_patch_ids = {option.id for option in TASKS[self._state.task_id]["definition"].patch_options}
if action.patch_id not in valid_patch_ids:
status_message = f"Patch application failed: unknown patch_id {action.patch_id!r}."
else:
self._state.applied_patch_id = action.patch_id
self._state.exploit_test_passed = False
self._state.functionality_test_passed = False
status_message = f"Applied patch template {action.patch_id!r}."
elif action.action_type == "verify":
exploit, functionality, verify_message = verification_outcome(
self._state.task_id,
self._state.applied_patch_id or None,
)
self._state.exploit_test_passed = exploit
self._state.functionality_test_passed = functionality
status_message = verify_message
elif action.action_type == "submit":
self._state.submitted = True
status_message = "Submission recorded."
else:
status_message = f"Unsupported action_type {action.action_type!r}."
report = grade_task(progress=self._state.model_dump())
self._state.score = report.score
set_runtime_progress(self._state.model_dump())
done = self._state.submitted or self._state.step_count >= MAX_STEPS
if self._state.submitted:
if report.passed:
status_message = "Submission recorded. Task solved."
else:
status_message = "Submission recorded, but the grader still reports an incomplete repair."
elif self._state.step_count >= MAX_STEPS:
status_message = f"{status_message} Max steps reached."
reward = round(self._state.score - previous_score, 2)
return self._build_observation(
status_message=status_message.strip(),
reward=reward,
done=done,
grader_report=report,
)
@property
def state(self) -> WebSecRepairState:
"""Return the current environment state."""
return self._state
def get_metadata(self) -> EnvironmentMetadata:
"""Return environment metadata for the OpenEnv UI."""
return EnvironmentMetadata(
name="WebSecRepairEnvironment",
description=(
"Deterministic OpenEnv environment with three web vulnerability repair tasks "
"covering SQL injection, XSS, and broken access control."
),
version="0.1.0",
author="Codex",
)
def _build_observation(
self,
status_message: str,
reward: float,
done: bool,
grader_report: Any | None = None,
) -> WebSecRepairObservation:
task = get_task(self._state.task_id)
if grader_report is None:
grader_report = grade_task(progress=self._state.model_dump())
visible_patch_options = task.patch_options if self._state.inspected else []
visible_code = task.code_snippet if self._state.inspected else ""
visible_hint = task.scanner_hint if self._state.inspected else ""
return WebSecRepairObservation(
task_id=task.id,
instruction=task.instruction,
code_snippet=visible_code,
scanner_hint=visible_hint,
status_message=status_message,
selected_vulnerability=self._state.selected_vulnerability,
applied_patch_id=self._state.applied_patch_id,
patch_options=visible_patch_options,
exploit_test_passed=self._state.exploit_test_passed,
functionality_test_passed=self._state.functionality_test_passed,
grader_passed=grader_report.passed,
reward=reward,
done=done,
metadata={
"step_count": self._state.step_count,
"score": self._state.score,
"max_steps": MAX_STEPS,
"grader": grader_report.model_dump(),
},
)
|