Spaces:
Running
Running
File size: 15,616 Bytes
993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f 553ced5 f4dbf56 553ced5 993988f f4dbf56 553ced5 f4dbf56 553ced5 f4dbf56 553ced5 f4dbf56 993988f 553ced5 f4dbf56 553ced5 993988f f4dbf56 993988f 553ced5 993988f 553ced5 f4dbf56 993988f 553ced5 f4dbf56 553ced5 f4dbf56 553ced5 993988f f4dbf56 993988f 553ced5 f4dbf56 553ced5 f4dbf56 553ced5 993988f f4dbf56 993988f 553ced5 993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f 553ced5 993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f f4dbf56 993988f |
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 |
import hashlib
import json
import os
import pathlib
import tempfile
from enum import Enum
from typing import Optional, Any
import weave
from pydantic import BaseModel, PrivateAttr
from guardrails_genie.guardrails.base import Guardrail
try:
from detect_secrets import SecretsCollection
from detect_secrets.settings import default_settings
import hyperscan
except ImportError:
raise ImportError(
"The `detect-secrets` and the `hyperscan` packages are required for using the SecretsGuardrail. "
"Please install then by running `pip install detect-secrets hyperscan`."
)
class REDACTION(str, Enum):
"""
Enum for different types of redaction modes.
"""
REDACT_PARTIAL = "REDACT_PARTIAL"
REDACT_ALL = "REDACT_ALL"
REDACT_HASH = "REDACT_HASH"
REDACT_NONE = "REDACT_NONE"
def redact_value(value: str, mode: str) -> str:
"""
Redacts the given value based on the specified redaction mode.
Args:
value (str): The string value to be redacted.
mode (str): The redaction mode to be applied. It can be one of the following:
- REDACTION.REDACT_PARTIAL: Partially redacts the value.
- REDACTION.REDACT_ALL: Fully redacts the value.
- REDACTION.REDACT_HASH: Redacts the value by hashing it.
- REDACTION.REDACT_NONE: No redaction is applied.
Returns:
str: The redacted value based on the specified mode.
"""
replacement = value
if mode == REDACTION.REDACT_PARTIAL:
replacement = "[REDACTED:]" + value[:2] + ".." + value[-2:] + "[:REDACTED]"
elif mode == REDACTION.REDACT_ALL:
replacement = "[REDACTED:]" + ("*" * len(value)) + "[:REDACTED]"
elif mode == REDACTION.REDACT_HASH:
replacement = (
"[REDACTED:]" + hashlib.md5(value.encode()).hexdigest() + "[:REDACTED]"
)
return replacement
class SecretsDetectionSimpleResponse(BaseModel):
"""
A simple response model for secrets detection.
Attributes:
contains_secrets (bool): Indicates if secrets were detected.
explanation (str): Explanation of the detection result.
redacted_text (Optional[str]): The redacted text if secrets were found.
risk_score (float): The risk score of the detection result. (0.0, 0.5, 1.0)
"""
contains_secrets: bool
explanation: str
redacted_text: Optional[str] = None
risk_score: float = 0.0
@property
def safe(self) -> bool:
"""
Property to check if the text is safe (no secrets detected).
Returns:
bool: True if no secrets were detected, False otherwise.
"""
return not self.contains_secrets
class SecretsDetectionResponse(SecretsDetectionSimpleResponse):
"""
A detailed response model for secrets detection.
Attributes:
detected_secrets (dict[str, list[str]]): Dictionary of detected secrets.
"""
detected_secrets: dict[str, Any] | None = None
class SecretsInfo(BaseModel):
"""
Model representing information about a detected secret.
Attributes:
secret (str): The detected secret value.
line_number (int): The line number where the secret was found.
"""
secret: str
line_number: int
class ScanResult(BaseModel):
"""
Model representing the result of a secrets scan.
Attributes:
detected_secrets (dict[str, Any] | None): Dictionary of detected secrets, or None if no secrets were found.
modified_prompt (str): The modified prompt with secrets redacted.
has_secret (bool): Indicates if any secrets were detected.
risk_score (float): The risk score of the detection result.
"""
detected_secrets: dict[str, Any] | None = None
modified_prompt: str
has_secret: bool
risk_score: float
class DetectSecretsModel(weave.Model):
"""
Model for detecting secrets using the detect-secrets library.
"""
@staticmethod
def scan(text: str) -> dict[str, list[SecretsInfo]]:
"""
Scans the given text for secrets using the detect-secrets library.
Args:
text (str): The text to scan for secrets.
Returns:
dict[str, list[SecretsInfo]]: A dictionary where the keys are secret types and the values are lists of SecretsInfo objects.
"""
secrets = SecretsCollection()
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(text.encode("utf-8"))
temp_file.close()
with default_settings():
secrets.scan_file(str(temp_file.name))
unique_secrets = {}
for file in secrets.files:
for found_secret in secrets[file]:
if found_secret.secret_value is None:
continue
secret_type = found_secret.type
actual_secret = found_secret.secret_value
line_number = found_secret.line_number
if secret_type not in unique_secrets:
unique_secrets[secret_type] = []
unique_secrets[secret_type].append(
SecretsInfo(secret=actual_secret, line_number=line_number)
)
os.remove(temp_file.name)
return unique_secrets
@weave.op
def invoke(self, text: str) -> dict[str, list[SecretsInfo]]:
"""
Invokes the scan method to detect secrets in the given text.
Args:
text (str): The text to scan for secrets.
Returns:
dict[str, list[SecretsInfo]]: A dictionary where the keys are secret types and the values are lists of SecretsInfo objects.
"""
return self.scan(text)
class HyperScanModel(weave.Model):
"""
Model for detecting secrets using the Hyperscan library.
We use the Hyperscan library to scan for secrets using regex patterns.
The patterns are mined from https://github.com/mazen160/secrets-patterns-db
This model is used in conjunction with the DetectSecretsModel to improve the detection of secrets.
"""
_db: Any = PrivateAttr()
_pattern_map: dict[str, str] = PrivateAttr()
only_high_confidence: bool = False
ids: list[str] = []
def _load_patterns(self) -> dict[str, str]:
"""
Loads the patterns from a JSONL file.
Returns:
dict[str, str]: A dictionary where the keys are pattern names and the values are regex patterns.
"""
patterns = (
pathlib.Path(__file__).parent.resolve() / "secrets_patterns.jsonl"
).open()
patterns_list = [json.loads(line) for line in patterns]
if self.only_high_confidence:
patterns_list = [
pattern for pattern in patterns_list if pattern["confidence"] == "high"
]
return {pattern["name"]: pattern["regex"] for pattern in patterns_list}
def __init__(self, **kwargs: Any):
"""
Initializes the HyperScanModel instance.
"""
super().__init__(**kwargs)
def model_post_init(self, __context: Any) -> None:
"""
Post-initialization method to load patterns and compile the Hyperscan database.
"""
self._pattern_map = self._load_patterns()
self.ids = list(self._pattern_map.keys())
expressions = [pattern.encode() for pattern in self._pattern_map.values()]
self._db = hyperscan.Database()
self._db.compile(expressions=expressions, ids=list(range(len(expressions))))
def scan(self, text: str) -> dict[str, list[SecretsInfo]]:
"""
Scans the given text for secrets using the Hyperscan library.
Args:
text (str): The text to scan for secrets.
Returns:
dict[str, list[SecretsInfo]]: A dictionary where the keys are secret types and the values are lists of SecretsInfo objects.
"""
unique_secrets = {}
def on_match(idx, start, end, flags, context):
"""
Callback function for handling matches found by Hyperscan.
Args:
idx: The index of the matched pattern.
start: The start position of the match.
end: The end position of the match.
flags: The flags associated with the match.
context: The context provided to the scan method.
"""
secret = context["text"][start:end]
line_number = context["line_number"]
current_match = unique_secrets.setdefault(self.ids[idx], [])
if not current_match or len(secret) > len(current_match[0].secret):
unique_secrets[self.ids[idx]] = [
SecretsInfo(line_number=line_number, secret=secret)
]
for line_no, line in enumerate(text.splitlines(), start=1):
self._db.scan(
line.encode(),
match_event_handler=on_match,
context={"text": line, "line_number": line_no},
)
return unique_secrets
@weave.op
def invoke(self, text: str) -> dict[str, list[SecretsInfo]]:
"""
Invokes the scan method to detect secrets in the given text.
Args:
text (str): The text to scan for secrets.
Returns:
dict[str, list[SecretsInfo]]: A dictionary where the keys are secret types and the values are lists of SecretsInfo objects.
"""
return self.scan(text)
class SecretsDetectionGuardrail(Guardrail):
"""
Guardrail class for secrets detection using both detect-secrets and Hyperscan models.
Attributes:
redaction (REDACTION): The redaction mode to be applied.
_detect_secrets_model (Any): Instance of the DetectSecretsModel.
_hyperscan_model (Any): Instance of the HyperScanModel.
"""
redaction: REDACTION
_detect_secrets_model: Any = PrivateAttr()
_hyperscan_model: Any = PrivateAttr()
def model_post_init(self, __context: Any) -> None:
"""
Post-initialization method to initialize the detect-secrets and Hyperscan models.
"""
self._detect_secrets_model = DetectSecretsModel()
self._hyperscan_model = HyperScanModel()
def __init__(
self,
redaction: REDACTION = REDACTION.REDACT_ALL,
**kwargs,
):
"""
Initializes the SecretsDetectionGuardrail instance.
Args:
redaction (REDACTION): The redaction mode to be applied. Defaults to REDACTION.REDACT_ALL.
**kwargs: Additional keyword arguments.
"""
super().__init__(
redaction=redaction,
)
def get_modified_value(
self, unique_secrets: dict[str, Any], lines: list[str]
) -> str:
"""
Redacts the detected secrets in the given lines of text.
Args:
unique_secrets (dict[str, Any]): Dictionary of detected secrets.
lines (list[str]): List of lines of text.
Returns:
str: The modified text with secrets redacted.
"""
for _, secrets_list in unique_secrets.items():
for secret_info in secrets_list:
secret = secret_info.secret
line_number = secret_info.line_number
lines[line_number - 1] = lines[line_number - 1].replace(
secret, redact_value(secret, self.redaction)
)
modified_value = "\n".join(lines)
return modified_value
def get_scan_result(
self, unique_secrets: dict[str, list[SecretsInfo]], lines: list[str]
) -> ScanResult | None:
"""
Generates a ScanResult based on the detected secrets.
Args:
unique_secrets (dict[str, list[SecretsInfo]]): Dictionary of detected secrets.
lines (list[str]): List of lines of text.
Returns:
ScanResult | None: The scan result if secrets are detected, otherwise None.
"""
if unique_secrets:
modified_value = self.get_modified_value(unique_secrets, lines)
detected_secrets = {
k: [i.secret for i in v] for k, v in unique_secrets.items()
}
return ScanResult(
**{
"detected_secrets": detected_secrets,
"modified_prompt": modified_value,
"has_secret": True,
"risk_score": 1.0,
}
)
return None
def scan(self, prompt: str) -> ScanResult:
"""
Scans the given prompt for secrets using both detect-secrets and Hyperscan models.
Args:
prompt (str): The text to scan for secrets.
Returns:
ScanResult: The scan result with detected secrets and redacted text.
"""
if prompt.strip() == "":
return ScanResult(
**{
"detected_secrets": None,
"modified_prompt": prompt,
"has_secret": False,
"risk_score": 0.0,
}
)
unique_secrets = self._detect_secrets_model.invoke(text=prompt)
results = self.get_scan_result(unique_secrets, prompt.splitlines())
if results:
return results
unique_secrets = self._hyperscan_model.invoke(text=prompt)
results = self.get_scan_result(unique_secrets, prompt.splitlines())
if results:
results.risk_score = 0.5
return results
return ScanResult(
**{
"detected_secrets": None,
"modified_prompt": prompt,
"has_secret": False,
"risk_score": 0.0,
}
)
@weave.op
def guard(
self,
prompt: str,
return_detected_secrets: bool = True,
**kwargs,
) -> SecretsDetectionResponse | SecretsDetectionResponse:
"""
Guards the given prompt by scanning for secrets and optionally returning detected secrets.
Args:
prompt (str): The text to scan for secrets.
return_detected_secrets (bool): Whether to return detected secrets in the response. Defaults to True.
**kwargs: Additional keyword arguments.
Returns:
SecretsDetectionResponse | SecretsDetectionSimpleResponse: The response with scan results and redacted text.
"""
results = self.scan(prompt)
explanation_parts = []
if results.has_secret:
explanation_parts.append("Found the following secrets in the text:")
for secret_type, matches in results.detected_secrets.items():
explanation_parts.append(f"- {secret_type}: {len(matches)} instance(s)")
else:
explanation_parts.append("No secrets detected in the text.")
if return_detected_secrets:
return SecretsDetectionResponse(
contains_secrets=results.has_secret,
detected_secrets=results.detected_secrets,
explanation="\n".join(explanation_parts),
redacted_text=results.modified_prompt,
risk_score=results.risk_score,
)
else:
return SecretsDetectionSimpleResponse(
contains_secrets=not results.has_secret,
explanation="\n".join(explanation_parts),
redacted_text=results.modified_prompt,
risk_score=results.risk_score,
)
|