API Reference

The API Reference page provides detailed information about each API interface, including its purpose, required parameters, optional parameters, and expected response format.

Interface

pysast.is_rule_file(file_path: str) bool

Returns whether the file path looks like a supported rule definition.

pysast.get_mime_type(file_path: str) str | None

Retrieve the MIME type of a file.

Parameters:

file_path (str) – The path to the file.

Return type:

str | None

Returns:

The MIME type of the file, or None if it couldn’t be determined.

pysast.extract_filter_keys(filters: dict[str, str], is_meta=False) dict[str, str]

Extracts valid filter keys from a dictionary of filters.

This function iterates through the filters dictionary and selects only the keys that are considered valid filter keys based on a predefined list of valid keys (VALID_FILTER_KEYS). If is_meta is True, it treats filters as a nested dictionary and extracts the filter keys from the nested “`filters”` dictionary.

Parameters:
  • filters (dict[str, str]) – A dictionary of filters, where the keys are filter names and the values are corresponding filter values

  • is_meta (bool, optional) – Flag indicating whether the filters dictionary should be treated as a nested dictionary with a "filters" key., defaults to False

Returns:

A dictionary containing only the valid filter keys and their corresponding values.

Return type:

dict[str, str]

pysast.load_sast_rules(file_path: str) list[SastRule]

Loads SAST (Static Application Security Testing) rules from a file.

The method takes a file path as input and returns a list of SastRule objects. The file can be in either JSON or YAML format.

Example:

>>> rules = load_sast_rules("sast_rules.json")
>>> for rule in rules:
...     print(rule.rule_id, rule.meta["severity"])
example-rule INFO
param file_path:

The path to the file containing the SAST rules.

type file_path:

str

return:

A list of SastRule objects representing the loaded rules.

rtype:

list[SastRule]

pysast.run(cmd: list[str] = None)

Runs a scan by using the incoming command line arguments.

Parameters:

cmd (str, optional) – the command to execute, defaults to None

Classes

class pysast.FileFilter

A utility class for filtering files based on specific criteria.

The FileFilter class allows you to create filters for file matching. It supports basic string matching and regular expression matching. Filters can be inverted and combined to create complex filtering logic.

Usage:

>>> f = FileFilter()
>>> f.with_re()  # Enable regular expression matching
>>> f = ~f  # Invert the filter
>>> result = f.apply("jpg, png", "image.jpg")  # Apply the filter
apply(value: str, target: str) bool

Apply the filter to a target value.

This method applies the filter to the target value and determines whether it matches the filter criteria.

Parameters:
  • value (str) – The filter criteria. It can contain multiple values separated by commas.

  • target (str) – The target value to match against the filter.

Returns:

True if the target value matches the filter criteria, False otherwise.

Return type:

bool

reset()

Resets this filter.

with_re() None

Enable regular expression matching.

This method enables regular expression matching when applying the filter. After calling this method, the apply(...) method will use regular expressions to match files against the filter criteria.

class pysast.SupportsFilter

A mixin class for supporting filtering based on predefined criteria.

The SupportsFilter class provides a method for applying filters to a file based on various criteria such as file extension, file name, full path, and MIME type. It utilizes the FileFilter class for applying individual filters.

Usage:

>>> instance = SupportsFilter()
>>> result = instance.apply_filters(
...     filters={"file_ext": "jpg", "file_name": "image", "mime_type": "image/jpeg"},
...     file_path="/path/to/image.jpg",
...     mime_type="image/jpeg"
... )

You can also pass spacial directives to filter values:

  • ! inverts the filter logic.

  • re: will treat the following string as a regular expression

apply_filters(filters: dict[str, str], file_path: str, mime_type: str) bool

Apply filters to a file based on predefined criteria.

This method iterates through the filters dictionary and applies the filters to the file_path and mime_type values. It uses the FileFilter class to apply individual filters based on predefined criteria. If any filter fails, it returns False. If all filters pass, it returns True.

Parameters:
  • filters (dict[str, str]) – A dictionary of filters, where the keys are filter directives and the values are corresponding filter criteria.

  • file_path (str) – The path of the file to be filtered.

  • mime_type (str) – The MIME type of the file.

Returns:

True if the file passes all filters, False otherwise.

Return type:

bool

class pysast.SastPattern(text=None, engine=None, mode=None, modes=None)

A class representing a static application security testing (SAST) pattern.

The SastPattern class encapsulates a pattern used for SAST matching. It provides functionality to compile the pattern using a specified regular expression engine and supports different modes of pattern matching.

Note

All patterns will be converted to byte-patterns before compilation.

Each pattern can use a different compile engine that produces a re.Pattern. To specify a custom engine, use the "engine" directive in a pattern declaration within a rule:

1"rule-id": {
2    "pattern": {
3        "text": "...",
4        "engine": "mymodule"
5    }
6}

or with YAML:

- rule-id: ...
  pattern:
    text: ...
    engine: mymodule

To apply custom pattern matching you can specify whether the pattern is optional or the matching logic should be inverted. You can do that by adding the "mode" directive, which can take the following values:

  • and (default): The default setting implies that the pattern must be found in a file

  • or: The pattern is optional and may occur in the scanned file

  • not: The matching logic will be inverted so that the pattern must not be found

Hint

You can use multiple modes separated with a +:

- rule-id: sample-rule
  pattern:
    text: ...
    mode: not+and
compile()

Compile the pattern using the specified regular expression engine.

This method compiles the pattern using the regular expression engine specified in self.engine. It handles potential errors during module import and checks if the target module has the compile() function. By default, the built-in module re is used.

engine: str

The regular expression engine to be used for pattern compilation. Defaults to "re".

modes: list

Additional modes to be applied for pattern matching. Defaults to ["and"].

text: str

The text pattern to be compiled. Defaults to None.

class pysast.SastRule(rule_id: str, rule_content: dict)

A class to describe a single SAST rule.

It extends the SupportsFilter class. The purpose of this class is to encapsulate a rule with its associated content, filters, and patterns. It also provides methods to add patterns and reset its internal state.

Parameters:
  • rule_id (str) – The ID of the rule.

  • rule_content (dict) – The content of the rule.

Variables:
  • filters – A dictionary of filter directives

  • patterns – A list of SAST patterns.

add_pattern(pattern: str | dict[str, str])

Adds a pattern to this rule.

Note

You can use either a regular expression string or a custom object that contains special attributes as defined in SastRule.

Parameters:

pattern (dict[str, str] | str) – The pattern to add.

property meta: dict[str, str | dict]

Returns the meta information of this rule

Returns:

meta information like severity or description

Return type:

dict[str, str | dict]

property must_not_patterns: list[SastPattern]

Get a list of patterns that must not match for this rule.

Returns:

A list of patterns that must not match for this rule.

Return type:

list[SastPattern]

property required_patterns: list[SastPattern]

Get a list of patterns that are required to match for this rule.

Returns:

A list of patterns that are required to match for this rule.

Return type:

list[SastPattern]

class pysast.SastContext(sast_rules: list[SastRule])

Represents the context for performing a SAST scan on a given file.

It manages a collection of SastRule objects and provides methods to match the rules against file contents and generate results.

Parameters:

sast_rules (list[SastRule]) – A list of SastRule objects representing the SAST rules to be applied in the context. If not provided, an empty list is assigned as the default value.

match(file_path: str) list[dict]

Matches the SAST rules against the contents of a file and returns the results.

Parameters:

file_path (str) – A string representing the path to the file to be analyzed.

Returns:

A list of dictionaries representing the results of rule matches.

Return type:

list[dict]

class pysast.SastScanner(rules_dir: str = None, rules_path: str = None, rules: list[SastRule] = None, recursive_dir: bool = False, disable_prefilter: bool = False, disable_postfilter: bool = True, max_bytes=104857600, use_mime_type: bool = True)

A class representing a static application security scanner.

Parameters:
  • rules_dir (str) – Optional. Path to a directory containing SAST rule files.

  • rules_path (str) – Optional. Path to a specific SAST rule file.

  • rules (list[SastRule]) – Optional. A list of SastRule objects to be loaded.

  • recursive_dir (bool) – Optional. Specifies whether to recursively scan rule files in a directory. Default is False.

  • disable_prefilter (bool) – Optional. Specifies whether to disable pre-filtering of rules. Default is False.

  • disable_postfilter (bool) – Optional. Specifies whether to disable post-filtering of scan results. Default is True.

  • max_bytes (int) – Optional. Maximum number of bytes to read from a file during scanning. Default is DEFAULT_MAX_BYTES.

Patam use_mime_type:

Specifies whether the MIME-type should be loaded

filter_scan_results(file_path: str, mime_type: str, sast_matches: list) bool

Filter the scan results based on the specified file path, MIME type, and SAST matches.

Parameters:
  • file_path (str) – the scanned file path

  • mime_type (str) – MIME type of the scanned file

  • sast_matches (list) – a list of matches

Returns:

True if there are scan results, False otherwise.

Return type:

bool

get_context(file_path: str, mime_type: str) SastContext

Get the SastContext object for the specified file.

Parameters:
  • file_path (str) – Path to the file to be scanned.

  • mime_type (str) – MIME type of the file.

Returns:

the newly created context

Return type:

SastContext

property has_matches: bool

Check if there are any scan results.

Returns:

True if there are scan results, False otherwise.

Return type:

bool

property json: str

Get the scan results in JSON format.

Returns:

A string representing the scan results in JSON format.

load_rule_directory(dir_path: str, recursive: bool) None

Load SAST rule files from a directory.

Parameters:
  • dir_path (str) – Path to the directory containing the rule files.

  • recursive (bool) – Specifies whether to recursively scan rule files in subdirectories.

load_rule_file(file_path: str) None

Load a specific SAST rule file.

Parameters:

file_path (str) – Path to the rule file.

property rules: list[SastRule]

Get the loaded SAST rules.

scan(file_path: str) bool

Perform the scanning process on the specified file.

Parameters:

file_path (str) – the file to be scanned

Returns:

whether there are any scan results

Return type:

bool

property scan_results: list

Get the scan results as a list.