File: test_red_team.py

package info (click to toggle)
python-azure 20251104%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 770,224 kB
  • sloc: python: 6,357,217; ansic: 804; javascript: 287; makefile: 198; sh: 193; xml: 109
file content (380 lines) | stat: -rw-r--r-- 14,302 bytes parent folder | download | duplicates (2)
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
from typing import Any, Dict, List, Optional
import pytest
import os
import asyncio
import tempfile
import json
from pathlib import Path

# This will automatically apply to all test files in this directory
# This avoids having to add the skipif decorator to each test class
pytest.importorskip("pyrit", reason="redteam extra is not installed")

from azure.ai.evaluation.red_team import RedTeam, RiskCategory, AttackStrategy
from azure.ai.evaluation.red_team._red_team_result import RedTeamResult
from azure.ai.evaluation._model_configurations import AzureOpenAIModelConfiguration


@pytest.mark.usefixtures("recording_injection", "recorded_test")
@pytest.mark.azuretest
class TestRedTeam:
    @pytest.fixture
    def sanitized_model_config(self, model_config: AzureOpenAIModelConfiguration) -> AzureOpenAIModelConfiguration:
        """
        Fixture that sanitizes the Azure OpenAI model configuration for testing.

        Returns a sanitized version of the model configuration with updated endpoint
        if the original endpoint matches the sanitized test endpoint.

        Args:
            model_config: The original Azure OpenAI model configuration

        Returns:
            AzureOpenAIModelConfiguration: Sanitized model configuration for testing
        """
        if model_config["azure_endpoint"] != "https://Sanitized.api.cognitive.microsoft.com":
            return model_config

        return AzureOpenAIModelConfiguration(
            **{**model_config, "azure_endpoint": "https://Sanitized.openai.azure.com/"},
        )

    @pytest.mark.azuretest
    @pytest.mark.parametrize(
        ("proj_scope", "cred"),
        (
            # ("project_scope", "azure_cred"),
            ("project_scope_onedp", "azure_cred_onedp"),
        ),
    )
    def test_red_team_basic_scan(self, request, proj_scope, cred):
        """
        Test basic red team scan functionality with minimal configuration.

        Verifies that the RedTeam can successfully perform a scan with:
        - A simple string-based target function
        - Single risk category (Violence)
        - Base64 attack strategy
        - Single objective

        Validates that the scan results contain properly structured attack details
        with required fields like conversation, risk_category, and attack_technique.
        """
        azure_cred = request.getfixturevalue(cred)
        project_scope = request.getfixturevalue(proj_scope)

        # Setup a simple target function
        def simple_target(query: str) -> str:
            return f"Response to: {query}"

        # Initialize RedTeam with minimal config
        red_team = RedTeam(
            azure_ai_project=project_scope,
            credential=azure_cred,
            risk_categories=[RiskCategory.Violence],
            num_objectives=1,
        )

        # Run scan
        result = asyncio.run(
            red_team.scan(
                target=simple_target,
                scan_name="test_basic_scan",
                attack_strategies=[AttackStrategy.Base64],
                timeout=4800,
                skip_upload=True,
            )
        )

        # Validate results
        assert isinstance(result, RedTeamResult)
        assert result.attack_details is not None
        assert len(result.attack_details) > 0

        # Validate scan structure
        for attack in result.attack_details:
            assert "conversation" in attack
            assert "risk_category" in attack
            assert "attack_technique" in attack
            assert attack["risk_category"] == "violence"

    @pytest.mark.azuretest
    @pytest.mark.parametrize(
        ("proj_scope", "cred"), (("project_scope", "azure_cred"), ("project_scope_onedp", "azure_cred_onedp"))
    )
    def test_red_team_with_azure_openai_target(self, request, proj_scope, cred, sanitized_model_config):
        """
        Test red team scan using Azure OpenAI model as the target.

        Validates that the RedTeam can successfully scan an Azure OpenAI model configuration
        target with HateUnfairness risk category. Verifies proper conversation structure
        with user and assistant roles in the attack details.

        Uses skip_upload=True to avoid uploading results during testing.
        """
        azure_cred = request.getfixturevalue(cred)
        project_scope = request.getfixturevalue(proj_scope)

        red_team = RedTeam(
            azure_ai_project=project_scope,
            credential=azure_cred,
            risk_categories=[RiskCategory.HateUnfairness],
            num_objectives=1,
        )

        result = asyncio.run(
            red_team.scan(
                target=sanitized_model_config,
                scan_name="test_azure_openai_target",
                attack_strategies=[AttackStrategy.Base64],
                timeout=4800,
                skip_upload=True,
            )
        )

        assert isinstance(result, RedTeamResult)
        assert result.attack_details is not None

        # Validate conversation structure
        for attack in result.attack_details:
            conversation = attack["conversation"]
            assert len(conversation) >= 2
            assert conversation[0]["role"] == "user"
            assert conversation[1]["role"] == "assistant"

    @pytest.mark.azuretest
    @pytest.mark.parametrize(
        ("proj_scope", "cred"), (("project_scope", "azure_cred"), ("project_scope_onedp", "azure_cred_onedp"))
    )
    def test_red_team_with_callback_target(self, request, proj_scope, cred):
        """
        Test red team scan using an async callback function as the target.

        Validates that the RedTeam can successfully scan an async callback function
        that follows the expected message-based interface. The callback function
        receives messages and returns a properly formatted response with messages,
        stream, session_state, and context fields.

        Verifies proper conversation structure in the results.
        """
        azure_cred = request.getfixturevalue(cred)
        project_scope = request.getfixturevalue(proj_scope)

        # Setup a simple callback function
        async def callback_function(
            messages: List[Dict],
            stream: bool = False,
            session_state: Any = None,
            context: Optional[Dict[str, Any]] = None,
        ) -> dict:
            query = messages["messages"][0]["content"]

            formatted_response = {"content": query, "role": "assistant"}
            messages["messages"].append(formatted_response)
            return {
                "messages": messages["messages"],
                "stream": stream,
                "session_state": session_state,
                "context": context,
            }

        red_team = RedTeam(
            azure_ai_project=project_scope,
            credential=azure_cred,
            risk_categories=[RiskCategory.HateUnfairness],
            num_objectives=1,
        )

        result = asyncio.run(
            red_team.scan(
                target=callback_function,
                scan_name="test_callback_target",
                attack_strategies=[AttackStrategy.Base64],
                timeout=4800,
                skip_upload=True,
            )
        )

        assert isinstance(result, RedTeamResult)
        assert result.attack_details is not None

        # Validate conversation structure
        for attack in result.attack_details:
            conversation = attack["conversation"]
            assert len(conversation) >= 2
            assert conversation[0]["role"] == "user"
            assert conversation[1]["role"] == "assistant"

    @pytest.mark.azuretest
    @pytest.mark.parametrize(
        ("proj_scope", "cred"), (("project_scope", "azure_cred"), ("project_scope_onedp", "azure_cred_onedp"))
    )
    def test_red_team_multi_turn_attack(self, request, proj_scope, cred):
        """
        Test red team scan using MultiTurn attack strategy.

        Validates that the RedTeam can successfully execute multi-turn attacks
        which involve multiple conversation exchanges between the attacker and target.
        Verifies that multi-turn attacks produce conversations with more than 2 messages
        and that the conversation alternates between user and assistant roles properly.

        Uses a defensive target that responds with refusal messages.
        """
        azure_cred = request.getfixturevalue(cred)
        project_scope = request.getfixturevalue(proj_scope)

        # Setup a simple target function
        def simple_target(query: str) -> str:
            return "Sorry I cannot assist with that."

        red_team = RedTeam(
            azure_ai_project=project_scope,
            credential=azure_cred,
            risk_categories=[RiskCategory.Violence],
            num_objectives=1,
        )

        result = asyncio.run(
            red_team.scan(
                target=simple_target,
                scan_name="test_multi_turn_attack",
                attack_strategies=[
                    AttackStrategy.MultiTurn,
                ],
                timeout=4800,
                skip_upload=True,
            )
        )

        assert isinstance(result, RedTeamResult)
        assert result.attack_details is not None

        # Validate conversation structure
        for attack in result.attack_details:
            conversation = attack["conversation"]
            if attack["attack_technique"] == "multi_turn":
                assert len(conversation) > 2
            else:
                assert len(conversation) == 2
            for i in range(len(conversation)):
                assert conversation[i]["role"] == "user" if i % 2 == 0 else "assistant"

    @pytest.mark.azuretest
    @pytest.mark.parametrize(
        ("proj_scope", "cred"), (("project_scope", "azure_cred"), ("project_scope_onedp", "azure_cred_onedp"))
    )
    def test_red_team_crescendo_attack(self, request, proj_scope, cred):
        """
        Test red team scan using Crescendo attack strategy.

        Validates that the RedTeam can successfully execute crescendo attacks
        which gradually escalate the conversation to try to elicit harmful responses.
        Verifies that crescendo attacks produce conversations with exactly 20 messages
        (10 turns) and that the conversation alternates between user and assistant roles.

        Uses a defensive target that responds with refusal messages.
        """
        azure_cred = request.getfixturevalue(cred)
        project_scope = request.getfixturevalue(proj_scope)

        # Setup a simple target function
        def simple_target(query: str) -> str:
            return "Sorry I cannot assist with that."

        red_team = RedTeam(
            azure_ai_project=project_scope,
            credential=azure_cred,
            risk_categories=[RiskCategory.Violence],
            num_objectives=1,
        )

        result = asyncio.run(
            red_team.scan(
                target=simple_target,
                scan_name="test_crescendo_attack",
                attack_strategies=[
                    AttackStrategy.Crescendo,
                ],
                timeout=4800,
                skip_upload=True,
            )
        )

        assert isinstance(result, RedTeamResult)
        assert result.attack_details is not None

        # Validate conversation structure
        for attack in result.attack_details:
            conversation = attack["conversation"]
            if attack["attack_technique"] == "crescendo":
                assert len(conversation) == 20
            else:
                assert len(conversation) == 2
            for i in range(len(conversation)):
                assert conversation[i]["role"] == "user" if i % 2 == 0 else "assistant"

    @pytest.mark.azuretest
    @pytest.mark.parametrize(
        ("proj_scope", "cred"), (("project_scope", "azure_cred"), ("project_scope_onedp", "azure_cred_onedp"))
    )
    def test_red_team_ungrounded_attributes(self, request, proj_scope, cred):
        """
        Test red team scan for UngroundedAttributes risk category.

        Validates that the RedTeam can successfully scan for ungrounded attributes,
        which involve testing the target's tendency to generate factually incorrect
        or unsupported claims. Uses a callback function target that echoes the input
        and validates the conversation structure.

        Uses Baseline attack strategy which represents standard attack techniques
        without special encoding or multi-turn approaches.
        """
        azure_cred = request.getfixturevalue(cred)
        project_scope = request.getfixturevalue(proj_scope)

        # Setup a simple callback function
        async def callback_function(
            messages: List[Dict],
            stream: bool = False,
            session_state: Any = None,
            context: Optional[Dict[str, Any]] = None,
        ) -> dict:
            query = messages["messages"][0]["content"]

            formatted_response = {"content": query, "role": "assistant"}
            messages["messages"].append(formatted_response)
            return {
                "messages": messages["messages"],
                "stream": stream,
                "session_state": session_state,
                "context": context,
            }

        red_team = RedTeam(
            azure_ai_project=project_scope,
            credential=azure_cred,
            risk_categories=[RiskCategory.UngroundedAttributes],
            num_objectives=1,
        )

        result = asyncio.run(
            red_team.scan(
                target=callback_function,
                scan_name="test_ungrounded_attributes",
                attack_strategies=[
                    AttackStrategy.Baseline,
                ],
                timeout=4800,
                skip_upload=True,
            )
        )

        assert isinstance(result, RedTeamResult)
        assert result.attack_details is not None

        # Validate conversation structure
        for attack in result.attack_details:
            conversation = attack["conversation"]
            assert len(conversation) >= 2
            assert conversation[0]["role"] == "user"
            assert conversation[1]["role"] == "assistant"