-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
Expand file tree
/
Copy pathtest_bedrock_guardrails.py
More file actions
1901 lines (1625 loc) · 67.4 KB
/
test_bedrock_guardrails.py
File metadata and controls
1901 lines (1625 loc) · 67.4 KB
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Unit tests for Bedrock Guardrails
"""
import json
import os
import sys
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import HTTPException
sys.path.insert(0, os.path.abspath("../../../../../.."))
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import (
BedrockGuardrail,
_redact_pii_matches,
)
from litellm.types.utils import ModelResponse
@pytest.mark.asyncio
async def test__redact_pii_matches_function():
"""Test the _redact_pii_matches function directly"""
# Test case 1: Response with PII entities
response_with_pii = {
"action": "GUARDRAIL_INTERVENED",
"assessments": [
{
"sensitiveInformationPolicy": {
"piiEntities": [
{"type": "NAME", "match": "John Smith", "action": "BLOCKED"},
{
"type": "US_SOCIAL_SECURITY_NUMBER",
"match": "324-12-3212",
"action": "BLOCKED",
},
{"type": "PHONE", "match": "607-456-7890", "action": "BLOCKED"},
]
}
}
],
"outputs": [{"text": "Input blocked by PII policy"}],
}
# Call the redaction function
redacted_response = _redact_pii_matches(response_with_pii)
# Verify that PII matches are redacted
pii_entities = redacted_response["assessments"][0]["sensitiveInformationPolicy"][
"piiEntities"
]
assert pii_entities[0]["match"] == "[REDACTED]", "Name should be redacted"
assert pii_entities[1]["match"] == "[REDACTED]", "SSN should be redacted"
assert pii_entities[2]["match"] == "[REDACTED]", "Phone should be redacted"
# Verify other fields remain unchanged
assert pii_entities[0]["type"] == "NAME"
assert pii_entities[1]["type"] == "US_SOCIAL_SECURITY_NUMBER"
assert pii_entities[2]["type"] == "PHONE"
assert redacted_response["action"] == "GUARDRAIL_INTERVENED"
assert redacted_response["outputs"][0]["text"] == "Input blocked by PII policy"
print("PII redaction function test passed")
@pytest.mark.asyncio
async def test__redact_pii_matches_no_pii():
"""Test _redact_pii_matches with response that has no PII"""
response_no_pii = {"action": "NONE", "assessments": [], "outputs": []}
# Call the redaction function
redacted_response = _redact_pii_matches(response_no_pii)
# Should return the same response unchanged
assert redacted_response == response_no_pii
print("No PII redaction test passed")
@pytest.mark.asyncio
async def test__redact_pii_matches_empty_assessments():
"""Test _redact_pii_matches with empty assessments"""
response_empty_assessments = {
"action": "GUARDRAIL_INTERVENED",
"assessments": [{"sensitiveInformationPolicy": {"piiEntities": []}}],
"outputs": [{"text": "Some output"}],
}
# Call the redaction function
redacted_response = _redact_pii_matches(response_empty_assessments)
# Should return the same response unchanged
assert redacted_response == response_empty_assessments
print("Empty assessments redaction test passed")
@pytest.mark.asyncio
async def test__redact_pii_matches_malformed_response():
"""Test _redact_pii_matches with malformed response (should not crash)"""
# Test with completely malformed response
malformed_response = {
"action": "GUARDRAIL_INTERVENED",
"assessments": "not_a_list", # This should cause an exception
}
# Should not crash and return original response
redacted_response = _redact_pii_matches(malformed_response)
assert redacted_response == malformed_response
# Test with missing keys
missing_keys_response = {
"action": "GUARDRAIL_INTERVENED"
# Missing assessments key
}
redacted_response = _redact_pii_matches(missing_keys_response)
assert redacted_response == missing_keys_response
print("Malformed response redaction test passed")
@pytest.mark.asyncio
async def test__redact_pii_matches_multiple_assessments():
"""Test _redact_pii_matches with multiple assessments containing PII"""
response_multiple_assessments = {
"action": "GUARDRAIL_INTERVENED",
"assessments": [
{
"sensitiveInformationPolicy": {
"piiEntities": [
{
"type": "EMAIL",
"match": "john@example.com",
"action": "ANONYMIZED",
}
]
}
},
{
"sensitiveInformationPolicy": {
"piiEntities": [
{
"type": "CREDIT_DEBIT_CARD_NUMBER",
"match": "1234-5678-9012-3456",
"action": "BLOCKED",
},
{
"type": "ADDRESS",
"match": "123 Main St, Anytown USA",
"action": "ANONYMIZED",
},
]
}
},
],
"outputs": [{"text": "Multiple PII detected"}],
}
# Call the redaction function
redacted_response = _redact_pii_matches(response_multiple_assessments)
# Verify all PII in all assessments are redacted
assessment1_pii = redacted_response["assessments"][0]["sensitiveInformationPolicy"][
"piiEntities"
]
assessment2_pii = redacted_response["assessments"][1]["sensitiveInformationPolicy"][
"piiEntities"
]
assert assessment1_pii[0]["match"] == "[REDACTED]", "Email should be redacted"
assert assessment2_pii[0]["match"] == "[REDACTED]", "Credit card should be redacted"
assert assessment2_pii[1]["match"] == "[REDACTED]", "Address should be redacted"
# Verify types remain unchanged
assert assessment1_pii[0]["type"] == "EMAIL"
assert assessment2_pii[0]["type"] == "CREDIT_DEBIT_CARD_NUMBER"
assert assessment2_pii[1]["type"] == "ADDRESS"
print("Multiple assessments redaction test passed")
@pytest.mark.asyncio
async def test_bedrock_guardrail_logging_uses_redacted_response():
"""Test that the Bedrock guardrail uses redacted response for logging"""
# Create proper mock objects
mock_user_api_key_dict = UserAPIKeyAuth()
guardrail = BedrockGuardrail(
guardrailIdentifier="test-guardrail", guardrailVersion="DRAFT"
)
# Mock the Bedrock API response with PII
mock_bedrock_response = MagicMock()
mock_bedrock_response.status_code = 200
mock_bedrock_response.json.return_value = {
"action": "GUARDRAIL_INTERVENED",
"outputs": [{"text": "Hello, my phone number is {PHONE}"}],
"assessments": [
{
"sensitiveInformationPolicy": {
"piiEntities": [
{
"type": "PHONE",
"match": "+1 412 555 1212", # This should be redacted in logs
"action": "ANONYMIZED",
}
]
}
}
],
}
request_data = {
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Hello, my phone number is +1 412 555 1212"},
],
}
# Mock AWS credentials to avoid credential loading issues in CI
mock_credentials = MagicMock()
mock_credentials.access_key = "test-access-key"
mock_credentials.secret_key = "test-secret-key"
mock_credentials.token = None
# Mock AWS-related methods to ensure test runs without external dependencies
with (
patch.object(
guardrail.async_handler, "post", new_callable=AsyncMock
) as mock_post,
patch(
"litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails.verbose_proxy_logger.debug"
) as mock_debug,
patch.object(
guardrail, "_load_credentials", return_value=(mock_credentials, "us-east-1")
) as mock_load_creds,
patch.object(
guardrail, "_prepare_request", return_value=MagicMock()
) as mock_prepare_request,
):
mock_post.return_value = mock_bedrock_response
# Call the method that should log the redacted response
await guardrail.make_bedrock_api_request(
source="INPUT",
messages=request_data.get("messages"),
request_data=request_data,
)
# Verify that debug logging was called
mock_debug.assert_called()
# Get the logged response (second argument to debug call)
logged_calls = mock_debug.call_args_list
bedrock_response_log_call = None
for call in logged_calls:
args, kwargs = call
if len(args) >= 2 and "Bedrock AI response" in str(args[0]):
bedrock_response_log_call = call
break
assert (
bedrock_response_log_call is not None
), "Should have logged Bedrock AI response"
# Extract the logged response data
logged_response = bedrock_response_log_call[0][
1
] # Second argument to debug call
# Verify that the logged response has redacted PII
assert (
logged_response["assessments"][0]["sensitiveInformationPolicy"][
"piiEntities"
][0]["match"]
== "[REDACTED]"
)
# Verify other fields are preserved
assert logged_response["action"] == "GUARDRAIL_INTERVENED"
assert (
logged_response["assessments"][0]["sensitiveInformationPolicy"][
"piiEntities"
][0]["type"]
== "PHONE"
)
print("Bedrock guardrail logging redaction test passed")
@pytest.mark.asyncio
async def test_bedrock_guardrail_original_response_not_modified():
"""Test that the original response is not modified by redaction, only the logged version"""
# Create proper mock objects
mock_user_api_key_dict = UserAPIKeyAuth()
guardrail = BedrockGuardrail(
guardrailIdentifier="test-guardrail", guardrailVersion="DRAFT"
)
# Mock the Bedrock API response with PII
original_response_data = {
"action": "GUARDRAIL_INTERVENED",
"outputs": [{"text": "Hello, my phone number is {PHONE}"}],
"assessments": [
{
"sensitiveInformationPolicy": {
"piiEntities": [
{
"type": "PHONE",
"match": "+1 412 555 1212", # This should NOT be modified in original
"action": "ANONYMIZED",
}
]
}
}
],
}
mock_bedrock_response = MagicMock()
mock_bedrock_response.status_code = 200
mock_bedrock_response.json.return_value = original_response_data
request_data = {
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Hello, my phone number is +1 412 555 1212"},
],
}
# Mock AWS credentials to avoid credential loading issues in CI
mock_credentials = MagicMock()
mock_credentials.access_key = "test-access-key"
mock_credentials.secret_key = "test-secret-key"
mock_credentials.token = None
# Mock AWS-related methods to ensure test runs without external dependencies
with (
patch.object(
guardrail.async_handler, "post", new_callable=AsyncMock
) as mock_post,
patch.object(
guardrail, "_load_credentials", return_value=(mock_credentials, "us-east-1")
) as mock_load_creds,
patch.object(
guardrail, "_prepare_request", return_value=MagicMock()
) as mock_prepare_request,
):
mock_post.return_value = mock_bedrock_response
# Call the method
result = await guardrail.make_bedrock_api_request(
source="INPUT",
messages=request_data.get("messages"),
request_data=request_data,
)
# Verify that the original response data was not modified
# (The json() method should return the original data)
original_data = mock_bedrock_response.json()
assert (
original_data["assessments"][0]["sensitiveInformationPolicy"][
"piiEntities"
][0]["match"]
== "+1 412 555 1212"
)
# Verify that the returned BedrockGuardrailResponse contains original data
assert (
result["assessments"][0]["sensitiveInformationPolicy"]["piiEntities"][0][
"match"
]
== "+1 412 555 1212"
)
print("Original response not modified test passed")
@pytest.mark.asyncio
async def test__redact_pii_matches_preserves_non_pii_entities():
"""Test that _redact_pii_matches only affects PII-related entities and preserves other assessment data"""
response_with_mixed_data = {
"action": "GUARDRAIL_INTERVENED",
"assessments": [
{
"sensitiveInformationPolicy": {
"piiEntities": [
{
"type": "EMAIL",
"match": "user@example.com",
"action": "ANONYMIZED",
"confidence": "HIGH",
}
],
"regexes": [
{
"name": "custom_pattern",
"match": "some_pattern_match",
"action": "BLOCKED",
}
],
},
"contentPolicy": {
"filters": [
{
"type": "VIOLENCE",
"confidence": "MEDIUM",
"action": "BLOCKED",
}
]
},
"topicPolicy": {
"topics": [
{
"name": "Restricted Topic",
"type": "DENY",
"action": "BLOCKED",
}
]
},
}
],
"outputs": [{"text": "Content blocked"}],
}
# Call the redaction function
redacted_response = _redact_pii_matches(response_with_mixed_data)
# Verify that PII entity matches are redacted
pii_entities = redacted_response["assessments"][0]["sensitiveInformationPolicy"][
"piiEntities"
]
assert pii_entities[0]["match"] == "[REDACTED]", "PII match should be redacted"
assert pii_entities[0]["type"] == "EMAIL", "PII type should be preserved"
assert pii_entities[0]["action"] == "ANONYMIZED", "PII action should be preserved"
assert pii_entities[0]["confidence"] == "HIGH", "PII confidence should be preserved"
# Verify that regex matches are also redacted (updated behavior)
regexes = redacted_response["assessments"][0]["sensitiveInformationPolicy"][
"regexes"
]
assert regexes[0]["match"] == "[REDACTED]", "Regex match should be redacted"
assert regexes[0]["name"] == "custom_pattern", "Regex name should be preserved"
assert regexes[0]["action"] == "BLOCKED", "Regex action should be preserved"
# Verify that other policies are completely unchanged
content_policy = redacted_response["assessments"][0]["contentPolicy"]
assert content_policy["filters"][0]["type"] == "VIOLENCE"
assert content_policy["filters"][0]["confidence"] == "MEDIUM"
topic_policy = redacted_response["assessments"][0]["topicPolicy"]
assert topic_policy["topics"][0]["name"] == "Restricted Topic"
# Verify top-level fields are unchanged
assert redacted_response["action"] == "GUARDRAIL_INTERVENED"
assert redacted_response["outputs"][0]["text"] == "Content blocked"
print("Preserves non-PII entities test passed")
@pytest.mark.asyncio
async def test_pii_redaction_matches_debug_output_format():
"""Test that demonstrates the exact behavior shown in your debug output"""
# This matches the structure from your debug output
original_response = {
"action": "GUARDRAIL_INTERVENED",
"actionReason": "Guardrail blocked.",
"assessments": [
{
"invocationMetrics": {
"guardrailCoverage": {
"textCharacters": {"guarded": 84, "total": 84}
},
"guardrailProcessingLatency": 322,
"usage": {
"contentPolicyImageUnits": 0,
"contentPolicyUnits": 0,
"contextualGroundingPolicyUnits": 0,
"sensitiveInformationPolicyFreeUnits": 0,
"sensitiveInformationPolicyUnits": 1,
"topicPolicyUnits": 0,
"wordPolicyUnits": 0,
},
},
"sensitiveInformationPolicy": {
"piiEntities": [
{
"action": "BLOCKED",
"detected": True,
"match": "John Smith",
"type": "NAME",
},
{
"action": "BLOCKED",
"detected": True,
"match": "324-12-3212",
"type": "US_SOCIAL_SECURITY_NUMBER",
},
{
"action": "BLOCKED",
"detected": True,
"match": "607-456-7890",
"type": "PHONE",
},
]
},
}
],
"blockedResponse": "Input blocked by PII policy",
"guardrailCoverage": {"textCharacters": {"guarded": 84, "total": 84}},
"output": [{"text": "Input blocked by PII policy"}],
"outputs": [{"text": "Input blocked by PII policy"}],
"usage": {
"contentPolicyImageUnits": 0,
"contentPolicyUnits": 0,
"contextualGroundingPolicyUnits": 0,
"sensitiveInformationPolicyFreeUnits": 0,
"sensitiveInformationPolicyUnits": 1,
"topicPolicyUnits": 0,
"wordPolicyUnits": 0,
},
}
# Apply redaction
redacted_response = _redact_pii_matches(original_response)
# Verify the redacted response matches your expected debug output
pii_entities = redacted_response["assessments"][0]["sensitiveInformationPolicy"][
"piiEntities"
]
# All PII matches should be redacted
assert pii_entities[0]["match"] == "[REDACTED]", "NAME should be redacted"
assert pii_entities[1]["match"] == "[REDACTED]", "SSN should be redacted"
assert pii_entities[2]["match"] == "[REDACTED]", "PHONE should be redacted"
# But all other fields should be preserved
assert pii_entities[0]["type"] == "NAME"
assert pii_entities[1]["type"] == "US_SOCIAL_SECURITY_NUMBER"
assert pii_entities[2]["type"] == "PHONE"
assert pii_entities[0]["action"] == "BLOCKED"
assert pii_entities[0]["detected"] == True
# Verify that the original response is unchanged
original_pii_entities = original_response["assessments"][0][
"sensitiveInformationPolicy"
]["piiEntities"]
assert (
original_pii_entities[0]["match"] == "John Smith"
), "Original should be unchanged"
assert (
original_pii_entities[1]["match"] == "324-12-3212"
), "Original should be unchanged"
assert (
original_pii_entities[2]["match"] == "607-456-7890"
), "Original should be unchanged"
# Verify all other metadata is preserved in redacted response
assert redacted_response["action"] == "GUARDRAIL_INTERVENED"
assert redacted_response["actionReason"] == "Guardrail blocked."
assert redacted_response["blockedResponse"] == "Input blocked by PII policy"
assert (
redacted_response["assessments"][0]["invocationMetrics"][
"guardrailProcessingLatency"
]
== 322
)
print("PII redaction matches debug output format test passed")
print(
f"Original PII values preserved: {[e['match'] for e in original_pii_entities]}"
)
print(f"Redacted PII values: {[e['match'] for e in pii_entities]}")
@pytest.mark.asyncio
async def test__redact_pii_matches_with_regex_matches():
"""Test redaction of regex matches in sensitive information policy"""
response_with_regex = {
"action": "GUARDRAIL_INTERVENED",
"assessments": [
{
"sensitiveInformationPolicy": {
"regexes": [
{
"name": "SSN_PATTERN",
"match": "123-45-6789",
"action": "BLOCKED",
},
{
"name": "CREDIT_CARD_PATTERN",
"match": "4111-1111-1111-1111",
"action": "ANONYMIZED",
},
]
}
}
],
"outputs": [{"text": "Regex patterns detected"}],
}
# Call the redaction function
redacted_response = _redact_pii_matches(response_with_regex)
# Verify that regex matches are redacted
regexes = redacted_response["assessments"][0]["sensitiveInformationPolicy"][
"regexes"
]
assert regexes[0]["match"] == "[REDACTED]", "SSN regex match should be redacted"
assert (
regexes[1]["match"] == "[REDACTED]"
), "Credit card regex match should be redacted"
# Verify other fields are preserved
assert regexes[0]["name"] == "SSN_PATTERN", "Regex name should be preserved"
assert regexes[0]["action"] == "BLOCKED", "Regex action should be preserved"
assert regexes[1]["name"] == "CREDIT_CARD_PATTERN", "Regex name should be preserved"
assert regexes[1]["action"] == "ANONYMIZED", "Regex action should be preserved"
# Verify original response is unchanged
original_regexes = response_with_regex["assessments"][0][
"sensitiveInformationPolicy"
]["regexes"]
assert original_regexes[0]["match"] == "123-45-6789", "Original should be unchanged"
assert (
original_regexes[1]["match"] == "4111-1111-1111-1111"
), "Original should be unchanged"
print("Regex matches redaction test passed")
@pytest.mark.asyncio
async def test__redact_pii_matches_with_custom_words():
"""Test redaction of custom word matches in word policy"""
response_with_custom_words = {
"action": "GUARDRAIL_INTERVENED",
"assessments": [
{
"wordPolicy": {
"customWords": [
{
"match": "confidential_data",
"action": "BLOCKED",
},
{
"match": "secret_information",
"action": "ANONYMIZED",
},
]
}
}
],
"outputs": [{"text": "Custom words detected"}],
}
# Call the redaction function
redacted_response = _redact_pii_matches(response_with_custom_words)
# Verify that custom word matches are redacted
custom_words = redacted_response["assessments"][0]["wordPolicy"]["customWords"]
assert (
custom_words[0]["match"] == "[REDACTED]"
), "First custom word match should be redacted"
assert (
custom_words[1]["match"] == "[REDACTED]"
), "Second custom word match should be redacted"
# Verify other fields are preserved
assert (
custom_words[0]["action"] == "BLOCKED"
), "Custom word action should be preserved"
assert (
custom_words[1]["action"] == "ANONYMIZED"
), "Custom word action should be preserved"
# Verify original response is unchanged
original_custom_words = response_with_custom_words["assessments"][0]["wordPolicy"][
"customWords"
]
assert (
original_custom_words[0]["match"] == "confidential_data"
), "Original should be unchanged"
assert (
original_custom_words[1]["match"] == "secret_information"
), "Original should be unchanged"
print("Custom words redaction test passed")
@pytest.mark.asyncio
async def test__redact_pii_matches_with_managed_words():
"""Test redaction of managed word matches in word policy"""
response_with_managed_words = {
"action": "GUARDRAIL_INTERVENED",
"assessments": [
{
"wordPolicy": {
"managedWordLists": [
{
"match": "inappropriate_word",
"action": "BLOCKED",
"type": "PROFANITY",
},
{
"match": "offensive_term",
"action": "ANONYMIZED",
"type": "HATE_SPEECH",
},
]
}
}
],
"outputs": [{"text": "Managed words detected"}],
}
# Call the redaction function
redacted_response = _redact_pii_matches(response_with_managed_words)
# Verify that managed word matches are redacted
managed_words = redacted_response["assessments"][0]["wordPolicy"][
"managedWordLists"
]
assert (
managed_words[0]["match"] == "[REDACTED]"
), "First managed word match should be redacted"
assert (
managed_words[1]["match"] == "[REDACTED]"
), "Second managed word match should be redacted"
# Verify other fields are preserved
assert (
managed_words[0]["action"] == "BLOCKED"
), "Managed word action should be preserved"
assert (
managed_words[0]["type"] == "PROFANITY"
), "Managed word type should be preserved"
assert (
managed_words[1]["action"] == "ANONYMIZED"
), "Managed word action should be preserved"
assert (
managed_words[1]["type"] == "HATE_SPEECH"
), "Managed word type should be preserved"
# Verify original response is unchanged
original_managed_words = response_with_managed_words["assessments"][0][
"wordPolicy"
]["managedWordLists"]
assert (
original_managed_words[0]["match"] == "inappropriate_word"
), "Original should be unchanged"
assert (
original_managed_words[1]["match"] == "offensive_term"
), "Original should be unchanged"
print("Managed words redaction test passed")
@pytest.mark.asyncio
async def test__redact_pii_matches_comprehensive_coverage():
"""Test redaction across all supported policy types in a single response"""
comprehensive_response = {
"action": "GUARDRAIL_INTERVENED",
"assessments": [
{
"sensitiveInformationPolicy": {
"piiEntities": [
{
"type": "EMAIL",
"match": "user@example.com",
"action": "ANONYMIZED",
}
],
"regexes": [
{
"name": "PHONE_PATTERN",
"match": "555-123-4567",
"action": "BLOCKED",
}
],
},
"wordPolicy": {
"customWords": [
{
"match": "confidential",
"action": "BLOCKED",
}
],
"managedWordLists": [
{
"match": "inappropriate",
"action": "ANONYMIZED",
"type": "PROFANITY",
}
],
},
}
],
"outputs": [{"text": "Multiple policy violations detected"}],
}
# Call the redaction function
redacted_response = _redact_pii_matches(comprehensive_response)
# Verify all match fields are redacted
assessment = redacted_response["assessments"][0]
# PII entities
pii_entities = assessment["sensitiveInformationPolicy"]["piiEntities"]
assert (
pii_entities[0]["match"] == "[REDACTED]"
), "PII entity match should be redacted"
# Regex matches
regexes = assessment["sensitiveInformationPolicy"]["regexes"]
assert regexes[0]["match"] == "[REDACTED]", "Regex match should be redacted"
# Custom words
custom_words = assessment["wordPolicy"]["customWords"]
assert (
custom_words[0]["match"] == "[REDACTED]"
), "Custom word match should be redacted"
# Managed words
managed_words = assessment["wordPolicy"]["managedWordLists"]
assert (
managed_words[0]["match"] == "[REDACTED]"
), "Managed word match should be redacted"
# Verify all other fields are preserved
assert pii_entities[0]["type"] == "EMAIL"
assert regexes[0]["name"] == "PHONE_PATTERN"
assert managed_words[0]["type"] == "PROFANITY"
# Verify original response is unchanged
original_assessment = comprehensive_response["assessments"][0]
assert (
original_assessment["sensitiveInformationPolicy"]["piiEntities"][0]["match"]
== "user@example.com"
)
assert (
original_assessment["sensitiveInformationPolicy"]["regexes"][0]["match"]
== "555-123-4567"
)
assert (
original_assessment["wordPolicy"]["customWords"][0]["match"] == "confidential"
)
assert (
original_assessment["wordPolicy"]["managedWordLists"][0]["match"]
== "inappropriate"
)
print("Comprehensive coverage redaction test passed")
@pytest.mark.asyncio
async def test_bedrock_guardrail_respects_custom_runtime_endpoint(monkeypatch):
"""Test that BedrockGuardrail respects aws_bedrock_runtime_endpoint when set"""
# Clear any existing environment variable to ensure clean test
monkeypatch.delenv("AWS_BEDROCK_RUNTIME_ENDPOINT", raising=False)
# Create guardrail with custom runtime endpoint
custom_endpoint = "https://custom-bedrock.example.com"
guardrail = BedrockGuardrail(
guardrailIdentifier="test-guardrail",
guardrailVersion="DRAFT",
aws_bedrock_runtime_endpoint=custom_endpoint,
)
# Mock credentials
mock_credentials = MagicMock()
mock_credentials.access_key = "test-access-key"
mock_credentials.secret_key = "test-secret-key"
mock_credentials.token = None
# Test data
data = {"source": "INPUT", "content": [{"text": {"text": "test content"}}]}
optional_params = {}
aws_region_name = "us-east-1"
# Mock the _load_credentials method to avoid actual AWS credential loading
with patch.object(
guardrail, "_load_credentials", return_value=(mock_credentials, aws_region_name)
):
# Call _prepare_request which internally calls get_runtime_endpoint
prepped_request = guardrail._prepare_request(
credentials=mock_credentials,
data=data,
optional_params=optional_params,
aws_region_name=aws_region_name,
)
# Verify that the custom endpoint is used in the URL
expected_url = f"{custom_endpoint}/guardrail/{guardrail.guardrailIdentifier}/version/{guardrail.guardrailVersion}/apply"
assert (
prepped_request.url == expected_url
), f"Expected URL to contain custom endpoint. Got: {prepped_request.url}"
print(f"Custom runtime endpoint test passed. URL: {prepped_request.url}")
@pytest.mark.asyncio
async def test_bedrock_guardrail_respects_env_runtime_endpoint(monkeypatch):
"""Test that BedrockGuardrail respects AWS_BEDROCK_RUNTIME_ENDPOINT environment variable"""
custom_endpoint = "https://env-bedrock.example.com"
# Set the environment variable
monkeypatch.setenv("AWS_BEDROCK_RUNTIME_ENDPOINT", custom_endpoint)
# Create guardrail without explicit aws_bedrock_runtime_endpoint
guardrail = BedrockGuardrail(
guardrailIdentifier="test-guardrail", guardrailVersion="DRAFT"
)
# Mock credentials
mock_credentials = MagicMock()
mock_credentials.access_key = "test-access-key"
mock_credentials.secret_key = "test-secret-key"
mock_credentials.token = None
# Test data
data = {"source": "INPUT", "content": [{"text": {"text": "test content"}}]}
optional_params = {}
aws_region_name = "us-east-1"
# Mock the _load_credentials method
with patch.object(
guardrail, "_load_credentials", return_value=(mock_credentials, aws_region_name)
):
# Call _prepare_request which internally calls get_runtime_endpoint
prepped_request = guardrail._prepare_request(
credentials=mock_credentials,
data=data,
optional_params=optional_params,
aws_region_name=aws_region_name,
)
# Verify that the custom endpoint from environment is used in the URL
expected_url = f"{custom_endpoint}/guardrail/{guardrail.guardrailIdentifier}/version/{guardrail.guardrailVersion}/apply"
assert (
prepped_request.url == expected_url
), f"Expected URL to contain env endpoint. Got: {prepped_request.url}"
print(f"Environment runtime endpoint test passed. URL: {prepped_request.url}")
@pytest.mark.asyncio
async def test_bedrock_guardrail_uses_default_endpoint_when_no_custom_set(monkeypatch):
"""Test that BedrockGuardrail uses default endpoint when no custom endpoint is set"""
# Ensure no environment variable is set
monkeypatch.delenv("AWS_BEDROCK_RUNTIME_ENDPOINT", raising=False)
# Create guardrail without any custom endpoint
guardrail = BedrockGuardrail(
guardrailIdentifier="test-guardrail", guardrailVersion="DRAFT"
)
# Mock credentials
mock_credentials = MagicMock()
mock_credentials.access_key = "test-access-key"
mock_credentials.secret_key = "test-secret-key"
mock_credentials.token = None
# Test data
data = {"source": "INPUT", "content": [{"text": {"text": "test content"}}]}
optional_params = {}
aws_region_name = "us-west-2"
# Mock the _load_credentials method
with patch.object(
guardrail, "_load_credentials", return_value=(mock_credentials, aws_region_name)
):
# Call _prepare_request which internally calls get_runtime_endpoint
prepped_request = guardrail._prepare_request(
credentials=mock_credentials,
data=data,
optional_params=optional_params,