File size: 13,536 Bytes
8c486a8
 
 
 
7529adc
 
 
8c486a8
 
 
 
 
ad5992a
8c486a8
 
 
 
ad5992a
 
 
 
 
 
 
 
 
 
 
 
8c486a8
 
 
 
ad5992a
 
 
 
 
 
 
 
 
7d5c3bd
 
ad5992a
 
 
 
 
8c486a8
 
 
 
 
 
 
 
7529adc
8c486a8
 
7529adc
8c486a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7529adc
8c486a8
 
 
 
 
 
 
 
 
7529adc
 
8c486a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7529adc
8c486a8
 
 
 
 
 
7529adc
 
8c486a8
 
 
 
 
 
 
 
 
 
7529adc
 
8c486a8
7529adc
8c486a8
 
 
7529adc
8c486a8
 
 
 
 
 
 
 
 
7529adc
 
8c486a8
 
 
 
7529adc
 
 
 
8c486a8
 
 
7529adc
8c486a8
 
 
 
7529adc
8c486a8
 
 
 
7529adc
8c486a8
 
 
 
7529adc
 
 
8c486a8
 
 
 
7529adc
 
 
 
8c486a8
 
 
 
 
 
7529adc
 
8c486a8
 
 
 
 
 
 
 
 
7529adc
8c486a8
 
 
 
 
 
7529adc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c486a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7529adc
 
 
 
8c486a8
 
 
 
 
 
7529adc
8c486a8
 
 
 
 
 
7529adc
 
8c486a8
 
 
 
 
7529adc
8c486a8
 
 
 
 
 
 
7529adc
 
 
 
 
8c486a8
 
 
7529adc
8c486a8
 
 
 
 
 
 
7529adc
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
395
396
397
398
"""Tests for the FastAPI application endpoints and WebSocket.

Uses Starlette's TestClient which wraps httpx for sync HTTP testing
and provides WebSocket testing support. No Docker dependency.

OpenEnv HTTP endpoints are stateless (new env per request).
Stateful tests use WebSocket sessions.
"""

from __future__ import annotations

import json
from unittest.mock import patch

import pytest
from starlette.testclient import TestClient

from open_range.protocols import SnapshotSpec


_TEST_SNAPSHOT = SnapshotSpec(
    topology={"hosts": ["attacker", "siem"]},
    flags=[],
    golden_path=[],
    task={
        "red_briefing": "Test mode — app endpoint tests.",
        "blue_briefing": "Test mode — app endpoint tests.",
    },
)


@pytest.fixture()
def client():
    """Create a TestClient against a fresh app instance.

    Patches ``_select_snapshot`` so HTTP /reset works without a
    ManagedSnapshotRuntime (which requires a manifest and snapshot
    store on disk).
    """
    with patch(
        "open_range.server.environment.RangeEnvironment._select_snapshot",
        return_value=_TEST_SNAPSHOT,
    ), patch(
        "open_range.server.environment.RangeEnvironment._ensure_clean_reset_path",
    ):
        from open_range.server.app import create_app

        app = create_app()
        yield TestClient(app)


# ===================================================================
# GET /health
# ===================================================================


class TestHealth:
    def test_returns_healthy(self, client: TestClient):
        resp = client.get("/health")
        assert resp.status_code == 200
        assert resp.json()["status"] == "healthy"


# ===================================================================
# GET /metadata
# ===================================================================


class TestMetadata:
    def test_returns_metadata(self, client: TestClient):
        resp = client.get("/metadata")
        assert resp.status_code == 200
        data = resp.json()
        assert data["name"] == "open_range"
        assert "version" in data
        assert "description" in data


# ===================================================================
# GET /schema
# ===================================================================


class TestSchema:
    def test_returns_schemas(self, client: TestClient):
        resp = client.get("/schema")
        assert resp.status_code == 200
        data = resp.json()
        assert "action" in data
        assert "observation" in data
        assert "state" in data

    def test_action_schema_has_command(self, client: TestClient):
        resp = client.get("/schema")
        data = resp.json()
        props = data["action"].get("properties", {})
        assert "command" in props
        assert "mode" in props

    def test_observation_schema_has_stdout(self, client: TestClient):
        resp = client.get("/schema")
        data = resp.json()
        props = data["observation"].get("properties", {})
        assert "stdout" in props

    def test_state_schema_has_episode_id(self, client: TestClient):
        resp = client.get("/schema")
        data = resp.json()
        props = data["state"].get("properties", {})
        assert "episode_id" in props


# ===================================================================
# POST /reset (HTTP -- stateless, just checks response format)
# ===================================================================


class TestReset:
    def test_reset_returns_observation(self, client: TestClient):
        resp = client.post("/reset", json={})
        assert resp.status_code == 200
        data = resp.json()
        assert "observation" in data
        assert "reward" in data
        assert "done" in data
        obs = data["observation"]
        assert "stdout" in obs
        assert "Range ready" in obs["stdout"]

    def test_reset_with_seed(self, client: TestClient):
        resp = client.post("/reset", json={"seed": 42})
        assert resp.status_code == 200
        assert "observation" in resp.json()

    def test_reset_no_body(self, client: TestClient):
        """Reset with no request body should work (defaults)."""
        resp = client.post("/reset")
        assert resp.status_code == 200
        assert "observation" in resp.json()


# ===================================================================
# POST /step (HTTP -- stateless, just checks response format)
# ===================================================================


class TestStep:
    def test_step_returns_observation(self, client: TestClient):
        resp = client.post(
            "/step",
            json={"action": {"command": "nmap -sV web", "mode": "red"}},
        )
        assert resp.status_code == 200
        data = resp.json()
        assert "observation" in data
        assert "reward" in data
        assert "done" in data

    def test_step_invalid_mode_rejected(self, client: TestClient):
        """Invalid mode value should be rejected by Pydantic validation."""
        resp = client.post(
            "/step",
            json={"action": {"command": "nmap", "mode": "invalid_mode"}},
        )
        assert resp.status_code == 422


# ===================================================================
# WS /ws -- stateful tests via WebSocket
# ===================================================================


class TestWebSocket:
    def test_ws_reset(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(json.dumps({"type": "reset"}))
            resp = ws.receive_json()
            assert resp["type"] == "observation"
            obs = resp["data"]["observation"]
            assert "Range ready" in obs["stdout"]

    def test_ws_reset_with_episode_id(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(
                json.dumps({
                    "type": "reset",
                    "data": {"episode_id": "ws_ep_1"},
                })
            )
            resp = ws.receive_json()
            assert resp["type"] == "observation"
            assert "ws_ep_1" in resp["data"]["observation"]["stdout"]

    def test_ws_step(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(json.dumps({"type": "reset"}))
            ws.receive_json()

            ws.send_text(
                json.dumps({
                    "type": "step",
                    "data": {"command": "nmap -sV web", "mode": "red"},
                })
            )
            resp = ws.receive_json()
            assert resp["type"] == "observation"
            assert "stdout" in resp["data"]["observation"]
            assert "reward" in resp["data"]
            assert "done" in resp["data"]

    def test_ws_state(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(
                json.dumps({
                    "type": "reset",
                    "data": {"episode_id": "ws_state_test"},
                })
            )
            ws.receive_json()

            ws.send_text(json.dumps({"type": "state"}))
            resp = ws.receive_json()
            assert resp["type"] == "state"
            assert resp["data"]["episode_id"] == "ws_state_test"
            assert resp["data"]["step_count"] == 0

    def test_ws_step_increments_state(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(json.dumps({"type": "reset"}))
            ws.receive_json()

            ws.send_text(
                json.dumps({
                    "type": "step",
                    "data": {"command": "curl http://web", "mode": "red"},
                })
            )
            ws.receive_json()

            ws.send_text(json.dumps({"type": "state"}))
            resp = ws.receive_json()
            assert resp["data"]["step_count"] == 1

    def test_ws_reset_clears_step_count(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            # Reset and step
            ws.send_text(json.dumps({"type": "reset"}))
            ws.receive_json()
            ws.send_text(
                json.dumps({
                    "type": "step",
                    "data": {"command": "nmap web", "mode": "red"},
                })
            )
            ws.receive_json()

            # Verify step count
            ws.send_text(json.dumps({"type": "state"}))
            state = ws.receive_json()
            assert state["data"]["step_count"] == 1

            # Reset again
            ws.send_text(json.dumps({"type": "reset"}))
            ws.receive_json()

            ws.send_text(json.dumps({"type": "state"}))
            state = ws.receive_json()
            assert state["data"]["step_count"] == 0

    def test_ws_red_and_blue_mode(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(json.dumps({"type": "reset"}))
            ws.receive_json()

            # Red step
            ws.send_text(
                json.dumps({
                    "type": "step",
                    "data": {"command": "nmap -sV web", "mode": "red"},
                })
            )
            resp = ws.receive_json()
            assert resp["type"] == "observation"

            # Blue step
            ws.send_text(
                json.dumps({
                    "type": "step",
                    "data": {"command": "tail_log /var/log/syslog", "mode": "blue"},
                })
            )
            resp = ws.receive_json()
            assert resp["type"] == "observation"

            ws.send_text(json.dumps({"type": "state"}))
            state = ws.receive_json()
            assert state["data"]["step_count"] == 2

    def test_ws_submit_finding(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(json.dumps({"type": "reset"}))
            ws.receive_json()

            ws.send_text(
                json.dumps({
                    "type": "step",
                    "data": {
                        "command": "submit_finding SQL injection on web host",
                        "mode": "blue",
                    },
                })
            )
            resp = ws.receive_json()
            assert resp["type"] == "observation"
            stdout = resp["data"]["observation"]["stdout"].lower()
            assert "submitted" in stdout or "recorded" in stdout

    def test_ws_empty_command(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(json.dumps({"type": "reset"}))
            ws.receive_json()

            ws.send_text(
                json.dumps({
                    "type": "step",
                    "data": {"command": "", "mode": "red"},
                })
            )
            resp = ws.receive_json()
            assert resp["type"] == "observation"
            assert resp["data"]["observation"]["stderr"] != ""

    def test_ws_invalid_json(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text("not valid json {{{")
            resp = ws.receive_json()
            assert resp["type"] == "error"

    def test_ws_unknown_type(self, client: TestClient):
        with client.websocket_connect("/ws") as ws:
            ws.send_text(json.dumps({"type": "explode"}))
            resp = ws.receive_json()
            assert resp["type"] == "error"

    def test_ws_session_isolation(self, client: TestClient):
        """Each WebSocket session should have its own environment."""
        with client.websocket_connect("/ws") as ws1:
            ws1.send_text(
                json.dumps({
                    "type": "reset",
                    "data": {"episode_id": "session_A"},
                })
            )
            ws1.receive_json()

            ws1.send_text(
                json.dumps({
                    "type": "step",
                    "data": {"command": "nmap web", "mode": "red"},
                })
            )
            ws1.receive_json()

            ws1.send_text(json.dumps({"type": "state"}))
            resp1 = ws1.receive_json()
            assert resp1["data"]["episode_id"] == "session_A"
            assert resp1["data"]["step_count"] == 1

        # A new WebSocket session starts fresh
        with client.websocket_connect("/ws") as ws2:
            ws2.send_text(json.dumps({"type": "state"}))
            resp2 = ws2.receive_json()
            assert resp2["data"]["step_count"] == 0

    def test_ws_multiple_steps(self, client: TestClient):
        """Run a short sequence of steps over WebSocket."""
        with client.websocket_connect("/ws") as ws:
            ws.send_text(json.dumps({"type": "reset"}))
            ws.receive_json()

            for cmd in [
                "nmap -sV web",
                "curl http://web",
                "curl http://web/login",
            ]:
                ws.send_text(
                    json.dumps({
                        "type": "step",
                        "data": {"command": cmd, "mode": "red"},
                    })
                )
                resp = ws.receive_json()
                assert resp["type"] == "observation"

            ws.send_text(json.dumps({"type": "state"}))
            state_resp = ws.receive_json()
            assert state_resp["data"]["step_count"] == 3