Skip to content

allowlist

๐Ÿค– AI-Generated Content

This documentation was generated with AI assistance and is still being audited. Some, or potentially a lot, of this information may be inaccurate. Learn more.

wrknv.security.allowlist

Security Allowlist Manager

Generate security scanner configuration files from a unified allowlist.

Classes

SecurityAllowlistManager

SecurityAllowlistManager(
    project_dir: Path | None = None,
    config: SecurityConfig | None = None,
)

Manages security scanner allowlist configurations.

Generates configuration files for: - TruffleHog (.trufflehog-exclude-paths.txt) - Gitleaks (.gitleaks.toml) - GitGuardian (.gitguardian.yaml)

Initialize the manager.

Parameters:

Name Type Description Default
project_dir Path | None

Project directory to work with

None
config SecurityConfig | None

Security configuration (optional, can be set later)

None
Source code in wrknv/security/allowlist.py
def __init__(
    self,
    project_dir: Path | None = None,
    config: SecurityConfig | None = None,
) -> None:
    """Initialize the manager.

    Args:
        project_dir: Project directory to work with
        config: Security configuration (optional, can be set later)
    """
    self.project_dir = Path(project_dir) if project_dir else Path.cwd()
    self.config = config

    logger.debug(f"SecurityAllowlistManager initialized for: {self.project_dir}")
Functions
generate_gitguardian
generate_gitguardian() -> str

Generate .gitguardian.yaml content.

Returns:

Type Description
str

Content for GitGuardian configuration file

Source code in wrknv/security/allowlist.py
    def generate_gitguardian(self) -> str:
        """Generate .gitguardian.yaml content.

        Returns:
            Content for GitGuardian configuration file
        """
        if not self.config:
            msg = "No security configuration set"
            raise ValueError(msg)

        config_dict = {
            "version": 2,
            "secret": {
                "ignored_paths": self.config.allowed_paths,
            },
        }
        header = f"""\
# GitGuardian configuration
# {self.config.description}
# Auto-generated by wrknv security.generate
# https://docs.gitguardian.com/ggshield-docs/configuration

"""
        return header + str(yaml.dump(config_dict, default_flow_style=False, sort_keys=False))
generate_gitleaks
generate_gitleaks() -> str

Generate .gitleaks.toml content.

Returns:

Type Description
str

Content for Gitleaks configuration file

Source code in wrknv/security/allowlist.py
def generate_gitleaks(self) -> str:
    """Generate .gitleaks.toml content.

    Returns:
        Content for Gitleaks configuration file
    """
    if not self.config:
        msg = "No security configuration set"
        raise ValueError(msg)

    lines = [
        "# Gitleaks configuration",
        f"# {self.config.description}",
        "# Auto-generated by wrknv security.generate",
        "# https://github.com/gitleaks/gitleaks",
        "",
        "[extend]",
        "useDefault = true",
        "",
        "[[allowlists]]",
        f'description = "{self.config.description}"',
        "paths = [",
    ]
    for path in self.config.allowed_paths:
        regex = glob_to_regex(path)
        lines.append(f"    '''{regex}''',")
    lines.append("]")
    return "\n".join(lines) + "\n"
generate_trufflehog
generate_trufflehog() -> str

Generate .trufflehog-exclude-paths.txt content.

Returns:

Type Description
str

Content for TruffleHog exclusion file

Source code in wrknv/security/allowlist.py
def generate_trufflehog(self) -> str:
    """Generate .trufflehog-exclude-paths.txt content.

    Returns:
        Content for TruffleHog exclusion file
    """
    if not self.config:
        msg = "No security configuration set"
        raise ValueError(msg)

    lines = [
        "# TruffleHog path exclusions",
        f"# {self.config.description}",
        "# Auto-generated by wrknv security.generate",
        "",
    ]
    for path in self.config.allowed_paths:
        lines.append(glob_to_regex(path))
    return "\n".join(lines) + "\n"
preview
preview(tool: str | None = None) -> str

Preview generated configuration.

Parameters:

Name Type Description Default
tool str | None

Specific tool to preview (trufflehog, gitleaks, gitguardian) If None, preview all

None

Returns:

Type Description
str

Preview content

Source code in wrknv/security/allowlist.py
def preview(self, tool: str | None = None) -> str:
    """Preview generated configuration.

    Args:
        tool: Specific tool to preview (trufflehog, gitleaks, gitguardian)
              If None, preview all

    Returns:
        Preview content
    """
    if not self.config:
        return "No security configuration set"

    if tool:
        tool_lower = tool.lower()
        if tool_lower == "trufflehog":
            return self.generate_trufflehog()
        elif tool_lower == "gitleaks":
            return self.generate_gitleaks()
        elif tool_lower == "gitguardian":
            return self.generate_gitguardian()
        else:
            return f"Unknown tool: {tool}. Use: trufflehog, gitleaks, gitguardian"

    # Preview all
    sections = []
    sections.append("=== .trufflehog-exclude-paths.txt ===")
    sections.append(self.generate_trufflehog())
    sections.append("\n=== .gitleaks.toml ===")
    sections.append(self.generate_gitleaks())
    sections.append("\n=== .gitguardian.yaml ===")
    sections.append(self.generate_gitguardian())
    return "\n".join(sections)
set_config
set_config(config: SecurityConfig) -> None

Set the security configuration.

Parameters:

Name Type Description Default
config SecurityConfig

Security configuration object

required
Source code in wrknv/security/allowlist.py
def set_config(self, config: SecurityConfig) -> None:
    """Set the security configuration.

    Args:
        config: Security configuration object
    """
    self.config = config
validate
validate() -> tuple[bool, list[str]]

Validate the security configuration.

Returns:

Type Description
tuple[bool, list[str]]

Tuple of (is_valid, list of error messages)

Source code in wrknv/security/allowlist.py
def validate(self) -> tuple[bool, list[str]]:
    """Validate the security configuration.

    Returns:
        Tuple of (is_valid, list of error messages)
    """
    errors = []

    if not self.config:
        errors.append("No security configuration set")
        return False, errors

    if not self.config.allowed_paths:
        errors.append("No allowed_paths defined in security configuration")

    # Validate glob patterns
    for path in self.config.allowed_paths:
        if not path:
            errors.append("Empty path in allowed_paths")
            continue
        # Check for invalid characters
        if "\n" in path or "\r" in path:
            errors.append(f"Invalid characters in path: {path!r}")

    return len(errors) == 0, errors
write_all
write_all(dry_run: bool = False) -> dict[str, bool]

Write all security scanner configuration files.

Parameters:

Name Type Description Default
dry_run bool

If True, don't write files, just report what would be done

False

Returns:

Type Description
dict[str, bool]

Dict mapping filename to success status

Source code in wrknv/security/allowlist.py
def write_all(self, dry_run: bool = False) -> dict[str, bool]:
    """Write all security scanner configuration files.

    Args:
        dry_run: If True, don't write files, just report what would be done

    Returns:
        Dict mapping filename to success status
    """
    if not self.config:
        msg = "No security configuration set"
        raise ValueError(msg)

    files = {
        ".trufflehog-exclude-paths.txt": self.generate_trufflehog(),
        ".gitleaks.toml": self.generate_gitleaks(),
        ".gitguardian.yaml": self.generate_gitguardian(),
    }

    results = {}
    for filename, content in files.items():
        filepath = self.project_dir / filename
        if dry_run:
            logger.info(f"[DRY-RUN] Would write {filepath}")
            results[filename] = True
        else:
            try:
                filepath.write_text(content)
                logger.info(f"Generated {filepath}")
                results[filename] = True
            except OSError as e:
                logger.error(f"Failed to write {filepath}: {e}")
                results[filename] = False

    return results

Functions

glob_to_regex

glob_to_regex(pattern: str) -> str

Convert glob pattern to regex pattern.

Parameters:

Name Type Description Default
pattern str

Glob pattern (e.g., "tests/certs/.key", "docs/**/.md")

required

Returns:

Type Description
str

Regex pattern suitable for TruffleHog and Gitleaks

Source code in wrknv/security/allowlist.py
def glob_to_regex(pattern: str) -> str:
    """Convert glob pattern to regex pattern.

    Args:
        pattern: Glob pattern (e.g., "tests/certs/*.key", "docs/**/*.md")

    Returns:
        Regex pattern suitable for TruffleHog and Gitleaks
    """
    # Escape regex special chars except * and ?
    result = re.escape(pattern)
    # Convert glob wildcards to regex
    # Handle **/ (zero or more directories) - must come before ** replacement
    result = result.replace(r"\*\*/", "(.*/)?")  # **/ matches zero or more dirs
    result = result.replace(r"\*\*", ".*")  # ** matches anything including /
    result = result.replace(r"\*", "[^/]*")  # * matches anything except /
    result = result.replace(r"\?", ".")  # ? matches single char
    return f"{result}$"