websec-repair-env / server /websec_repair_environment.py
Daksh Verma
Upload folder using huggingface_hub
57c1397 verified
Raw History Blame Contribute Delete
8.14 kB
"""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(),
},
)