### Set Up Development Environment with Poetry for Splunk SOAR App Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command uses Poetry to set up the virtual environment and install all necessary dependencies for your Splunk SOAR application, preparing it for development. ```shell poetry install ``` -------------------------------- ### Create Splunk SOAR App Installation Package (TGZ) Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command creates a `.tgz` tarball of your app directory, excluding the `.git` directory. This compressed archive serves as the final installation package that can be uploaded and installed on the Splunk SOAR platform. It should be run from outside the app directory or with adjusted paths. ```shell tar --exclude='.git' -zcvf MY_APP.tgz MY_APP/ ``` -------------------------------- ### Install Pre-Commit Hooks for Splunk SOAR App Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command installs the pre-commit hooks within your Splunk SOAR app directory. These hooks automate code quality checks before commits. ```shell pre-commit install ``` -------------------------------- ### Create New Splunk SOAR App Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command initializes a new, empty Splunk SOAR application using the `soarapps` CLI tool. It sets up the basic directory structure for development. ```shell soarapps init ``` -------------------------------- ### Generate Splunk SOAR App Manifest File Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command creates the `my_app.json` manifest file, which is crucial for app installation on the SOAR platform. It defines app information, actions, and parameters, and integrates with `pyproject.toml` and action metadata. The trailing dot specifies the current directory as the build context. ```shell soarapps manifests create my_app.json . ``` -------------------------------- ### Export Poetry Dependencies to requirements.txt Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command converts dependencies defined in `pyproject.toml` into a `requirements.txt` file. This step is necessary because the current wheel-building tool only supports `requirements.txt` for listing dependencies, enabling the creation of wheel files for offline app installation. ```shell poetry export --without-hashes --format=requirements.txt > requirements.txt ``` -------------------------------- ### Build Splunk SOAR App Dependency Wheels with pre-commit Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command uses `pre-commit` to run the `package-app-dependencies` hook, which builds wheel files for all app dependencies. It creates a `wheels` directory containing the wheel files and updates the app's manifest file to reference these dependencies. This step requires `pre-commit` to be installed and configured with the app's `.pre-commit-config.yml`. ```shell pre-commit run package-app-dependencies --all-files ``` -------------------------------- ### Splunk SOAR App Directory Structure Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This snippet illustrates the standard directory and file structure created when initializing or converting a Splunk SOAR application using the SDK. It includes source code, tests, configuration, and static assets. ```shell my_app/ ├─ src/ │ ├─ __init__.py │ ├─ app.py ├─ tests/ │ ├─ __init__.py │ ├─ test_app.py ├─ .pre-commit-config.yaml ├─ logo.svg ├─ logo_dark.svg ├─ pyproject.toml ``` -------------------------------- ### Run Pytest for SOAR App Testing in Shell Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command executes all defined tests for the SOAR app using `pytest`. It should be run from within the Poetry virtual environment to ensure all dependencies are correctly resolved. ```shell poetry run pytest ``` -------------------------------- ### Migrate Existing Splunk SOAR App Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This command converts an existing Splunk SOAR app written in the old `BaseConnector` framework to the new SDK format. It migrates asset configurations, action metadata, parameters, and outputs, but requires manual re-implementation of action code and certain features. ```shell soarapps convert myapp ``` -------------------------------- ### Enter Poetry Virtual Environment Shell Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md Use this command to enter the Poetry virtual environment's shell. Once inside, you can directly execute `soarapps` commands from the SDK CLI and run `pytest` without the `poetry run` prefix. ```shell poetry shell ``` -------------------------------- ### Run Pytest from Poetry Shell Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md After entering the Poetry virtual environment shell, `pytest` can be run directly to execute the SOAR app's tests. This simplifies the command execution by removing the need for `poetry run`. ```shell pytest ``` -------------------------------- ### Declare Action Function Signature in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md Every SOAR action function must define `params` and `client` as arguments with proper type hints. The `params` argument should inherit from `soar_sdk.params.Params`, while the `client` is automatically injected by the SOAR engine. ```python def my_action(params: Params, client: SOARClient): ``` -------------------------------- ### Install Splunk SOAR SDK as CLI Tool Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/README.md This snippet shows how to install the Splunk SOAR SDK as a command-line interface tool using `uv`. It also includes a command to verify the installation by displaying the `soarapps` help message, enabling direct use of SDK utilities. ```Shell uv tool install splunk-soar-sdk soarapps --help ``` -------------------------------- ### Example Splunk SOAR App `app.py` Implementation Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/README.md This Python code provides a comprehensive example of a Splunk SOAR app's `app.py` file. It demonstrates defining an `App` instance, configuring an `Asset` with sensitive fields, implementing a connectivity test, and creating a custom action with defined input parameters and output structure. ```Python from soar_sdk.abstract import SOARClient from soar_sdk.app import App from soar_sdk.asset import AssetField, BaseAsset from soar_sdk.params import Params from soar_sdk.action_results import ActionOutput class Asset(BaseAsset): base_url: str api_key: str = AssetField(sensitive=True, description="API key for authentication") app = App(name="test_app", asset_cls=Asset, appid="1e1618e7-2f70-4fc0-916a-f96facc2d2e4", app_type="sandbox", logo="logo.svg", logo_dark="logo_dark.svg", product_vendor="Splunk", product_name="Example App", publisher="Splunk") @app.test_connectivity() def test_connectivity(client: SOARClient, asset: Asset) -> None: client.debug(f"testing connectivity against {asset.base_url}") class ReverseStringParams(Params): input_string: str class ReverseStringOutput(ActionOutput): reversed_string: str @app.action(action_type="test", verbose="Reverses a string.") def reverse_string( param: ReverseStringParams, client: SOARClient ) -> ReverseStringOutput: reversed_string = param.input_string[::-1] return ReverseStringOutput(reversed_string=reversed_string) if __name__ == "__main__": app.cli() ``` -------------------------------- ### Add Docstring for SOAR Action Description in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md Providing a docstring for an action function is crucial for code readability and maintenance. By default, the `App.action` decorator uses this docstring to generate the action's description in the SOAR platform's documentation. ```python """This is the first custom action in the app""" ``` -------------------------------- ### Understand the App.action Decorator in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md The `@app.action()` decorator connects a Python function to the SOAR app instance, handling registration, configuration, and validation of action parameters. It abstracts away many underlying complexities, allowing developers to focus on action logic. ```python @app.action() ``` -------------------------------- ### Example `pyproject.toml` for Splunk SOAR App Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/pyproject.toml.md This `pyproject.toml` example demonstrates the structure for a Splunk SOAR application. It defines basic project metadata, Python dependencies (including `splunk-soar-sdk` and development tools like `pytest` and `ruff`), and specific SOAR app configuration under `[tool.soar.app]` for manifest generation. ```toml [tool.poetry] name = "Example Application" version = "0.0.1" description = "This is the basic example SOAR app" license = "Copyright" authors = [ "John Doe ", ] readme = "README.md" homepage = "https://www.splunk.com/en_us/products/splunk-security-orchestration-and-automation.html" packages = [{include = "src"}] [tool.poetry.dependencies] python = ">=3.9, <3.10" splunk-soar-sdk = "^0.0.0" [tool.poetry.group.dev.dependencies] pre-commit = "3.7.0" coverage = "^7.6.7" mypy = "1.2.0" pytest = "7.4.2" pytest-mock = "^3.14.0" pytest-watch = "^4.2.0" ruff = "^0.7.4" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" [virtualenvs] in-project = true [tool.soar.app] appid = "1e1618e7-2f70-4fc0-916a-f96facc2d2e4" type = "sandbox" product_vendor = "Splunk" logo = "logo.svg" logo_dark = "logo_dark.svg" product_name = "Example App" python_version = "3" product_version_regex = ".*" publisher = "Splunk" min_phantom_version = "6.2.2.134" app_wizard_version = "1.0.0" fips_compliant = false main_module = "src.app:app" ``` -------------------------------- ### Define a Simple SOAR App Action in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md This snippet demonstrates the most basic structure of a custom action in the Splunk SOAR SDK. It uses the `@app.action()` decorator to register the Python function as an action, accepting `params` and `client` arguments, and returning a boolean success status and a descriptive message. ```python @app.action() def my_action(params: Params, client: SOARClient): """This is the first custom action in the app""" return True, "Action run successful" ``` -------------------------------- ### Return Action Results in SOAR App in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/getting_started.md Actions in the SOAR SDK must return at least one result, typically as a two-element tuple. The first element is a boolean indicating success (`True`) or failure (`False`), and the second is a string comment useful for logging and debugging. ```python return True, "Action run successful" ``` -------------------------------- ### Example SOAR Widget Template for Service Status Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/templates.md A complete example of a Jinja2 HTML template (`templates/service_status.html`) extending `base/logo_header.html`. This template iterates through a list of `services` to display their name, status, and uptime within the `widget_content` block, demonstrating dynamic content generation. ```Jinja2 {% extends 'base/logo_header.html' %} {% block widget_content %}

Service Status

{% for service in services %}

{{ service.name }}

Status: {{ service.status }}

Uptime: {{ service.uptime }}

{% endfor %} {% endblock %} ``` -------------------------------- ### Example Splunk SOAR App Project Structure Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/README.md This snippet illustrates the recommended file and directory structure for a Splunk SOAR application developed with the SDK. It highlights the organization of source code, tests, and configuration files, providing a clear blueprint for new projects. ```Text string_reverser/ ├─ src/ │ ├─ __init__.py │ ├─ app.py ├─ tests/ │ ├─ __init__.py │ ├─ test_app.py ├─ .pre-commit-config.yaml ├─ logo.svg ├─ logo_dark.svg ├─ pyproject.toml ``` -------------------------------- ### Complete Default `app.py` File Structure Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/app.py.md This comprehensive snippet presents the entire default `app.py` file, illustrating the setup of a Splunk SOAR app. It includes importing necessary SDK modules, initializing the `App` instance, defining a `test_connectivity` action with its decorator, and the standard entry point for script execution. ```python #!/usr/bin/python from soar_sdk.abstract import SOARClient from soar_sdk.app import App from soar_sdk.params import Params app = App() @app.action(action_type="test") def test_connectivity(params: Params, client: SOARClient) -> tuple[bool, str]: """Testing the connectivity service.""" client.save_progress("Connectivity checked!") return True, "Connectivity checked!" if __name__ == "__main__": app.run() ``` -------------------------------- ### Use Docstring for Action Description Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/app.py.md This example illustrates that the docstring of an action function is automatically used by the SOAR SDK. It populates the action's description in the manifest and within the SOAR platform's web UI, providing essential documentation for users. ```python """Testing the connectivity service.""" ``` -------------------------------- ### Define SOAR App Action Decorator Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/app.py.md This code shows how to use the `@app.action` decorator to register a Python function as an action. It highlights the use of `action_type="test"` for specific action types, which is essential for the `test_connectivity` action required for app installation. ```python @app.action(action_type="test") ``` -------------------------------- ### Inflate Action Output Models from Python Dictionaries Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_outputs.md Provides an example of 'inflating' an `ActionOutput` model instance from a standard Python dictionary. This technique is particularly useful for mapping responses from external APIs (e.g., JSON) directly into structured output objects. ```Python @app.action() def list_users(params: ListUsersParams, client: SOARClient) -> ListUsersOutput: """The following returns a dictionary: { "count": 1, "users": [ { "username": "jsmith", "first_name": "John", "last_name": "Smith", "active": True, "email_addresses": [ "jsmith@example.com", ], "location": "San Jose", } ] } """ result = remote_api.list_users() return ListUsersOutput(**result) ``` -------------------------------- ### Render Data Labels and Values with Jinja2 Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/components/pie_chart.html This Jinja2 template snippet iterates through 'labels' and 'values' arrays to display them as key-value pairs within an HTML structure. It's commonly used for rendering dynamic data passed from the backend into a web page. ```Jinja2 {% for i in range(labels|length) %} {{ labels\[i\] }}: {{ values\[i\] }} {% endfor %} ``` -------------------------------- ### Extending Base Template with Standard Header Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/templates.md Example of extending `base/header.html` for a widget template with text-based titles. This snippet demonstrates how to override the `title`, `subtitle`, and `widget_content` blocks to customize the header and main content area. ```Jinja2 {% extends 'base/header.html' %} {% block title %}My Custom Title{% endblock %} {% block subtitle %}Secondary Text{% endblock %} {% block widget_content %}

Results

{{ my_data }}

{% endblock %} ``` -------------------------------- ### Extending Base Template with Logo Header Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/templates.md Example of extending `base/logo_header.html` to create a widget template that includes the app's logo in the header. The main content is placed within the `widget_content` block, which is a required block for all custom views. ```Jinja2 {% extends 'base/logo_header.html' %} {% block widget_content %}

Results

{{ my_data }}

{% endblock %} ``` -------------------------------- ### Asynchronous Splunk SOAR Action Definition Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_anatomy.md This example demonstrates how to define an asynchronous action within the Splunk SOAR Apps SDK using Python's `async def` syntax. It illustrates making an asynchronous HTTP request using `httpx.AsyncClient` and returning a structured output, highlighting the support for non-blocking operations. ```python @app.action() async def async_action(params: MyParams, client: SOARClient) -> MyOutput: """An asynchronous action""" async with httpx.AsyncClient() as http_client: response = await http_client.get(params.url) return MyOutput(data=response.json()) ``` -------------------------------- ### Add Metadata to Action Output Fields with OutputField in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_outputs.md Explains how to enrich action output fields with additional metadata using the `OutputField` function. This allows specifying properties like CEF types for security information and example values for documentation or validation. ```Python class GetUserOutput(ActionOutput): username: str = OutputField(cef_types=["username"]) first_name: str last_name: str groups: list[str] = OutputField(example_values=["wheel", "docker"]) ``` -------------------------------- ### Manage Asset State in Splunk SOAR SDK with Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_anatomy.md This Python code demonstrates how to manage asset state within the Splunk SOAR SDK. It shows how to access and update `client.auth_state` to store and retrieve a session token, ensuring state persistence across action runs. The example highlights checking for an existing token and fetching a new one if necessary, then performing an API call using the retrieved token. ```python @app.action() def my_stateful_action(params: Params, asset: Asset, client: SOARClient) -> MyActionOutput: if not (session_token := client.auth_state.get("session_token")): session_token = my_api.get_session_token(asset.client_id, asset.client_secret) client.auth_state["session_token"] = session_token result = my_api.do_something(session_token) return MyActionOutput(**result) ``` -------------------------------- ### Draw Interactive Pie Chart on HTML Canvas with JavaScript Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/components/pie_chart.html This JavaScript IIFE (Immediately Invoked Function Expression) draws a dynamic pie chart on an HTML canvas element. It calculates slice angles based on provided 'labels', 'values', and 'colors', and includes hover functionality to display tooltips with slice details. The chart size is responsive to its container. ```JavaScript (function() { const canvas = document.querySelector('canvas\[id^="pie-chart-"\]'); const tooltip = document.getElementById('tooltip'); if (!canvas) return; const ctx = canvas.getContext('2d'); const labels = {{ labels | to_json | safe }}; const values = {{ values | to_json | safe }}; const colors = {{ colors | to_json | safe }}; const container = canvas.parentElement; const size = Math.min(container.clientWidth - 40, container.clientHeight - 40, 300); canvas.width = size; canvas.height = size; const total = values.reduce((sum, value) => sum + value, 0); if (total === 0) return; const centerX = size / 2; const centerY = size / 2; const radius = Math.min(centerX, centerY) - 10; let currentAngle = -Math.PI / 2; const slices = \[]; // Draw pie chart values.forEach((value, index) => { const sliceAngle = (value / total) * 2 * Math.PI; slices.push({ startAngle: currentAngle, endAngle: currentAngle + sliceAngle, color: colors\[index\], label: labels\[index\], value: value }); ctx.beginPath(); ctx.moveTo(centerX, centerY); ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle); ctx.closePath(); ctx.fillStyle = colors\[index\]; ctx.fill(); ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; ctx.stroke(); currentAngle += sliceAngle; }); // Hover canvas.addEventListener('mousemove', (e) => { const rect = canvas.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; const dx = x - centerX; const dy = y - centerY; const distance = Math.sqrt(dx * dx + dy * dy); if (distance <= radius) { let angle = Math.atan2(dy, dx) + Math.PI / 2; if (angle < 0) angle += 2 * Math.PI; const slice = slices.find(s => { let start = s.startAngle + Math.PI / 2; let end = s.endAngle + Math.PI / 2; if (start < 0) start += 2 * Math.PI; if (end < 0) end += 2 * Math.PI; return start > end ? (angle >= start || angle <= end) : (angle >= start && angle <= end); }); if (slice) { canvas.style.cursor = 'pointer'; tooltip.textContent = \`${slice.label}: ${slice.value}\`; tooltip.style.opacity = '1'; const containerRect = canvas.parentElement.parentElement.getBoundingClientRect(); tooltip.style.left = (rect.left - containerRect.left + x + 10) + 'px'; tooltip.style.top = (rect.top - containerRect.top + y - 10) + 'px'; return; } } canvas.style.cursor = 'default'; tooltip.style.opacity = '0'; }); canvas.addEventListener('mouseleave', () => { canvas.style.cursor = 'default'; tooltip.style.opacity = '0'; }); })(); ``` -------------------------------- ### Initialize SOAR App Instance Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/app.py.md This snippet demonstrates the initialization of the `App` object, which serves as the core instance for defining and managing actions within a Splunk SOAR application. This `app` variable is crucial as its path is configured in `pyproject.toml` for the SOAR App Engine. ```python app = App() ``` -------------------------------- ### Enable Command Line Execution for App Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/app.py.md This standard Python `if __name__ == "__main__":` block enables the `app.py` file to be executed directly as a script. When run, `app.run()` processes actions based on a provided JSON input, facilitating command-line testing and execution of app functionalities. ```python if __name__ == "__main__": app.run() ``` -------------------------------- ### Basic Python Action Decorator Usage Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_decorator.md Illustrates the simplest way to apply the action decorator to a Python function within an app, enabling it to be recognized and managed by the SDK. ```python @app.action() ``` -------------------------------- ### Define a Basic Action Output Class in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_outputs.md Illustrates how to define a basic action output schema by extending the `ActionOutput` class in Python. This class serves as a blueprint for the data returned by an action. ```Python class ReverseStringOutput(ActionOutput): reversed_string: str ``` -------------------------------- ### Application Template Directory Structure Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/templates.md Illustrates the recommended directory structure for storing Jinja2 HTML templates within a Splunk SOAR app, showing the `templates/` folder alongside `src/` and `pyproject.toml`. ```Filesystem my_app/ ├── src/ │ └── app.py ├── templates/ │ ├── detection_results.html │ ├── user_summary.html │ └── scan_report.html └── pyproject.toml ``` -------------------------------- ### Splunk SOAR SDK Artifact API Class Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/api_reference.rst Documents the Artifact API class, providing methods for interacting with artifacts within Splunk SOAR. This snippet specifically details the 'create' method for generating new artifacts. ```APIDOC Class: soar_sdk.apis.artifact.Artifact Methods: create ``` -------------------------------- ### Attach Action Output Schema to SOAR Actions in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_outputs.md Demonstrates two methods for associating an `ActionOutput` schema with a SOAR action: using the `output_class` argument in the `@app.action` decorator, or by providing a return type hint for the action function. It also shows how to define input parameters using `Params`. ```Python class ReverseStringParams(Params): input_string = Param(0, "Input String", data_type="string") class ReverseStringOutput(ActionOutput): reversed_string: str @app.action(params_class=ReverseStringParams, output_class=ReverseStringOutput) def reverse_string_via_decorator(params, client): return ReverseStringOutput(reversed_string=params.input_string[::-1]) @app.action() def reverse_string_via_type_hint(params: ReverseStringParams, client: SOARClient) -> ReverseStringOutput: return ReverseStringOutput(reversed_string=params.input_string[::-1]) ``` -------------------------------- ### Action Decorator Parameters Reference Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_decorator.md Detailed API documentation for the parameters available to configure the Action Decorator, including their types, default values, and purpose. These parameters allow overriding implicitly derived information or adding more specific details to an action. ```APIDOC Action Decorator Parameters: name: str Description: Name of the action used in the SOAR platform UI and app documentation. Default: Generated automatically from the function name (replacing '_' with spaces). identifier: str Description: Unique identifier of the action in the app context. Should be lowercase, snake case. Default: Python function name. description: str Description: Description of the action used for app documentation in the SOAR platform. Default: Docstring of the action function. verbose: str Description: Extended description of what the action does, providing extra technical details. Default: Empty string. type: str Description: Type of action. Possible values: "contain", "correct", "generic", "ingest" (for on poll actions), "investigate", or "test". Default: "generic". Note: "test_connection" action must always be "test". read_only: bool Description: Informs whether the action performs changes in the asset's system. True if only gathering information, False if modifying. Default: True. params_class: Type[soar_sdk.params.Params] Description: Specifies the class for the 'params' argument of the action function if it cannot be provided via type hint. Default: Derived from the function's 'params' argument type hint. Example Usage: def my_action(params: MyActionParams, client: SOARClient) output_class: Type[soar_sdk.action_results.ActionOutput] Description: Specifies the return type class for the action. Default: Derived from the handler function's return type hint. Example Usage: def my_action(params: MyActionParams, client: SOARClient) -> MyActionOutput ``` -------------------------------- ### Define SOAR Action Function Signature Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/app.py.md This snippet outlines the standard function signature for a SOAR app action. It specifies that actions must accept `params` (a model inheriting from `soar_sdk.params.Params` for input data) and `client` (an instance of `SOARClient` for interacting with the SOAR platform API). ```python def test_connectivity(params: Params, client: SOARClient): ``` -------------------------------- ### Return Action Result Tuple Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/app.py.md This snippet shows the required return format for a SOAR app action. Actions must return a tuple consisting of a boolean value (True for success, False for failure) and a string message. This tuple is automatically processed by the SDK to create an Action Result. ```python return True, "Connectivity checked!" ``` -------------------------------- ### Splunk SOAR SDK App Class API Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/api_reference.rst Documents the main class for creating Splunk SOAR applications. It outlines the core functionalities and methods available for application development, including action registration, connectivity testing, and webhook enablement. ```APIDOC Class: soar_sdk.app.App Description: The main class for creating SOAR applications. Methods: action test_connectivity on_poll register_action enable_webhooks ``` -------------------------------- ### APIDOC: PieChartData Component Parameters Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/reusable_components.md This section details the parameters required to configure the `PieChartData` component. It outlines the expected types and purposes for the chart's title, data labels, numeric values, and custom color definitions, ensuring proper data structure for rendering. ```APIDOC PieChartData Parameters: - `title: str` - Chart title - `labels: list[str]` - Labels for each data segment - `values: list[int]` - Numeric values for each segment - `colors: list[str]` - Custom colors for each segment ``` -------------------------------- ### Add Splunk SOAR SDK as App Dependency Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/README.md This command demonstrates how to add the Splunk SOAR SDK as a development dependency to a Splunk SOAR app project using `uv`. This action updates the `pyproject.toml` file, integrating the SDK for app development. ```Shell uv add splunk-soar-sdk ``` -------------------------------- ### Reuse Action Output Classes for Multiple Actions in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_outputs.md Illustrates the reusability of defined `ActionOutput` classes across multiple actions. This promotes consistency and reduces redundancy when different actions produce or consume similar data structures, such as lists of users or new user creations. ```Python class ListUsersOutput(ActionOutput): count: int users: list[User] class CreateUserOutput(ActionOutput): success: bool new_user: User ``` -------------------------------- ### Splunk SOAR SDK Container API Class Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/api_reference.rst Documents the Container API class, which offers functionalities for managing containers in Splunk SOAR. It includes methods for creating containers and setting their executing asset. ```APIDOC Class: soar_sdk.apis.container.Container Methods: create set_executing_asset ``` -------------------------------- ### Python: Render Pie Chart with Soar SDK Component Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/reusable_components.md This Python snippet demonstrates how to use the `PieChartData` component from the `soar_sdk` to render a pie chart. It defines a view handler that processes `ThreatAnalysisOutput` and returns a `PieChartData` instance, populating it with a title, labels, values, and custom colors for visualization. ```python from soar_sdk.views.components.pie_chart import PieChartData @app.view_handler() def render_threat_distribution(output: list[ThreatAnalysisOutput]) -> PieChartData: output = output[0] return PieChartData( title="Threat Distribution", labels=["Malware", "Phishing", "Suspicious", "Clean"], values=[output.malware_count, output.phishing_count, output.suspicious_count, output.clean_count], colors=["#dc3545", "#fd7e14", "#ffc107", "#28a745"] ) ``` -------------------------------- ### Define Nested Action Output Classes in Python Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_outputs.md Shows how to create complex and hierarchical action output structures by nesting `ActionOutput` classes within each other. This enables defining rich data models, such as user profiles with nested email addresses and locations. ```Python class UserLocation(ActionOutput): country: str city: str class EmailAddress(ActionOutput): email: str = OutputField(cef_types=["email"]) is_primary: bool class User(ActionOutput): username: str = OutputField(cef_types=["username"]) first_name: str last_name: str active: bool email_addresses: list[EmailAddress] location: UserLocation ``` -------------------------------- ### Jinja2 Template Inheritance and Inclusion for Widgets Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/base/header.html This Jinja2 template snippet shows how to extend a base template (`widget_template.html`) and define a block (`custom_tools`) where other template snippets, like `widget_resize_snippet.html`, can be included. This pattern is commonly used in the Splunk SOAR SDK for modular UI development and widget customization. ```Jinja2 {% extends 'widgets/widget\_template.html' %} {% block custom\_tools %} {% include 'widgets/widget\_resize\_snippet.html' %} {% endblock %} ``` -------------------------------- ### Handle Enter Key Press on Widget Tool Menu with JavaScript Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/widgets/widget_template.html This JavaScript snippet adds an event listener to the element with ID 'widget-tool-menu'. When the 'Enter' key is pressed, it simulates a click on the target element, providing keyboard accessibility for menu items. ```JavaScript document.getElementById("widget-tool-menu").addEventListener('keydown', e => { if (e.key === 'Enter') { e.target.click(); } }) ``` -------------------------------- ### Python SDK Action Function Signature Definition Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/test_app.py.md This snippet illustrates the typical function signature for an action declared within the Splunk SOAR SDK. It shows that actions primarily expect a `Params` object, with the `client` argument automatically provided by the SDK. The signature also indicates that the action returns a boolean status, not an `ActionResult` instance. ```python def inner( params: Params, /, client: SOARClient = self.soar_client, *args: Iterable[Any], **kwargs: dict[str, Any], ) -> bool: ``` -------------------------------- ### Splunk SOAR SDK Logging API Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/api_reference.rst Documents the logging functions available within the Splunk SOAR SDK. These functions allow developers to output messages at various severity levels for debugging and operational monitoring. ```APIDOC Logging Functions: soar_sdk.logging.getLogger soar_sdk.logging.info soar_sdk.logging.debug soar_sdk.logging.progress soar_sdk.logging.warning soar_sdk.logging.error soar_sdk.logging.critical ``` -------------------------------- ### Utilize Pre-built Components with Python View Handler Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/view_handlers.md Instead of returning a dictionary for a custom template, view handlers can return specific data structures like TableData to leverage pre-built reusable components. This simplifies rendering common UI elements. ```python @app.view_handler() def render_as_table(output: list[DetectionOutput]) -> TableData: return TableData( title="Detection Results", headers=["ID", "Message", "Severity"], rows=[[d.detection_id, d.message, d.severity] for d in output] ) ``` -------------------------------- ### Log Action Progress to SOAR Engine Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/app.py.md This line demonstrates how to send real-time progress updates or log messages from an action to the SOAR app engine. The `client.save_progress()` method allows the app to communicate its current operational status, which is visible in the SOAR platform's logs. ```python client.save_progress("Connectivity checked!") ``` -------------------------------- ### Test Splunk SOAR App Connectivity Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/tests/cli/test_assets/converted_app/actions.py.txt This snippet defines a function to test the connectivity of a Splunk SOAR app. It's decorated with `@app.test_connectivity()` and takes `SOARClient` and `Asset` objects as input. Currently, it raises a `NotImplementedError`, indicating it's a placeholder for actual connectivity logic. ```Python @app.test_connectivity() def test_connectivity(soar: SOARClient, asset: Asset) -> None: raise NotImplementedError() ``` -------------------------------- ### Python Test for SOAR App Connectivity Action Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/app_structure/test_app.py.md This Python code snippet demonstrates how to write a unit test for the `test_connectivity` action within a Splunk SOAR app. It utilizes `unittest.mock` to patch the `save_progress` method of the SOAR client, allowing for offline testing and verification that the action correctly calls the progress saving mechanism. ```python from unittest import mock from src.app import app, test_connectivity from soar_sdk.params import Params def test_app_test_connectivity_action(): with mock.patch.object( app.manager.soar_client, "save_progress" ) as mock_save_progress: test_connectivity(Params()) # calling the action! mock_save_progress.assert_called_with("Connectivity checked!") ``` -------------------------------- ### Jinja2 Template for Custom Widget Tools and Resizing Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/widgets/widget_template.html This Jinja2 template block defines a section for custom widget tools. It conditionally includes a widget resizing snippet if `disable_resize` is not set, allowing for flexible widget layout management. ```Jinja2 {% block custom_tools %} {% if not disable_resize %} {% include 'widgets/widget_resize_snippet.html' %} {% endif %} {% endblock %} ``` -------------------------------- ### Splunk SOAR SDK ActionResult Class API Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/api_reference.rst Documents the ActionResult class, which is used to manage and manipulate the results of actions within the Splunk SOAR SDK. It includes methods for setting status, adding data, and retrieving the current status. ```APIDOC Class: soar_sdk.action_results.ActionResult Methods: set_status add_data get_status ``` -------------------------------- ### Jinja2 Template for Widget Action List Display Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/widgets/widget_template.html This Jinja2 template snippet defines a list of actions for a widget, including 'Collapse', 'Remove', and a conditionally displayed 'Toggle JSON view' option. It provides common UI controls for widget management. ```Jinja2 * Collapse * Remove {% if not disable_jsonview %}* Toggle JSON view {% endif %} ``` -------------------------------- ### Splunk SOAR SDK Exceptions API Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/api_reference.rst Documents the custom exception classes defined in the Splunk SOAR SDK. These exceptions are used to signal specific error conditions, such as action failures or general API errors. ```APIDOC Exception Classes: soar_sdk.exceptions.ActionFailure soar_sdk.exceptions.SoarAPIError ``` -------------------------------- ### Jinja2 Template for Widget Content Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/tests/example_app/templates/reverse_string.html This Jinja2 template extends 'base/logo_header.html' and defines the 'widget_content' block. Inside this block, it displays the values of 'original' and 'reversed' variables, typically passed from a backend context, along with static text. This pattern is common for rendering dynamic data in web applications. ```Jinja2 {% extends 'base/logo_header.html' %} {% block widget_content %} **Original** {{ original }} **Reversed** {{ reversed }} ✓ Success {% endblock %} ``` -------------------------------- ### Jinja2 SDK-Specific Filters for SOAR Templates Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/templates.md Demonstrates common Jinja2 filters provided by the Splunk SOAR SDK for formatting data (human-readable datetime, integer comma separation) and safely embedding JSON data into JavaScript. The `|safe` filter is crucial for preventing double-escaping or XSS when outputting pre-sanitized content. ```Jinja2

Modified: {{ last_modified|human_datetime }}

Count: {{ total_items|safe_intcomma }}

``` -------------------------------- ### Synchronous Splunk SOAR Action Definition Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/actions/action_anatomy.md This Python code snippet illustrates the fundamental structure of a synchronous action function in the Splunk SOAR Apps SDK. It showcases the use of the `@app.action` decorator, the `params` argument for input data, and the `client` argument for SOAR platform interaction, along with a basic return statement. ```python @app.action( # 1. Action Decorator name="Custom Name Action", # 2. Decorator Params ) def my_action( # 3. Action Function params: MyActionParams, # 4. Action Params client: SOARClient # 5. SOAR Client ): """The action that does what I want it to do""" # 6. Action Description return True, "Action succeeded" # 7. Action Result ``` -------------------------------- ### Define Basic Python View Handler Structure Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/view_handlers.md View handlers are Python functions decorated with @app.view_handler. They process action results and return a dictionary, whose keys become variables for template rendering. The 'template' parameter specifies the HTML template to use. ```python @app.view_handler(template="my_template.html") def my_view_handler(output: list[MyActionOutput]) -> dict: # Process the action results # Return data for template rendering return { "key": "value", "data": processed_data } ``` -------------------------------- ### Define Splunk SOAR App Action: Send Message Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/tests/cli/test_assets/converted_app/actions.py.txt This snippet defines a custom action named 'send_message' for a Splunk SOAR app. It's decorated with `@app.action()` and configured with a description, action type, read-only status, and verbose message. It accepts `Params`, `SOARClient`, and `Asset` objects, and is currently a placeholder raising `NotImplementedError`. ```Python @app.action(description='Send a message', action_type='test', read_only=False, verbose='This is a test action') def send_message(params: Params, soar: SOARClient, asset: Asset) -> ActionOutput: raise NotImplementedError() ``` -------------------------------- ### Return Template Data Dictionary from Python View Handler Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/view_handlers.md Handlers must return a dictionary containing data intended for template rendering. The keys within this dictionary become accessible as variables directly within the associated Jinja2 template, enabling dynamic content display. ```python def handler(output: list[DetectionOutput]) -> dict: return { "title": "Detection Results", "total_detections": len(output), "detections": [ { "id": d.detection_id, "message": d.message, "severity": d.severity } for d in output ] } ``` -------------------------------- ### Specify Custom HTML Template for Python View Handler Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/custom_views/view_handlers.md To use a custom HTML template, specify its filename using the 'template' parameter within the @app.view_handler decorator. The template file should reside in the designated 'templates' directory for the application. ```python # Template file: templates/detection_results.html @app.view_handler(template="detection_results.html") def render_detections(output: list[DetectionOutput]) -> dict: return {"detections": output} ``` -------------------------------- ### Dynamically Set HTML Header Background Image Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/base/logo_header.html This Jinja2 template snippet extends a base header and conditionally applies inline CSS to the 'custom_title_prop' block. If the 'title_logo' variable is defined, it sets a background image, size, position, and repeat properties for the element, referencing an application resource. ```HTML {% extends 'base/header.html' %} {% block custom_title_prop %}{% if title_logo %}style="background-size: auto 60%; background-position: 50%; background-repeat: no-repeat; background-image: url('/app_resource/{{ title_logo }}');"{% endif %}{% endblock %} ``` -------------------------------- ### Jinja2 Template for Displaying Function Error Details Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/base/error.html This Jinja2 template renders a page to display detailed error messages related to function execution. It conditionally shows function context information, including the function name, template name, and templates directory, if available. The template extends a base HTML header for consistent page structure. ```Jinja2 {% extends 'base/header.html' %} {% block title %}View Function Error{% endblock %} {% block widget\_content %} **Error Message:** {{ error\_message }} {% if function\_name %} **Function Context:** **Function:** `{{ function_name }}` {% if template\_name %}**Template:** `{{ template_name }}` {% endif %} {% if templates\_dir %}**Templates Directory:** `{{ templates_dir }}`{% endif %} {% endif %} {% endblock %} ``` -------------------------------- ### Splunk SOAR SDK Vault API Class Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/docs/api_reference.rst Documents the Vault API class, designed for managing attachments within the Splunk SOAR vault. It provides methods for creating, adding, retrieving, and deleting attachments. ```APIDOC Class: soar_sdk.apis.vault.Vault Methods: create_attachment add_attachment get_attachment delete_attachment ``` -------------------------------- ### Jinja2 Template for Conditional Title Logo Display Source: https://github.com/phantomcyber/splunk-soar-sdk/blob/beta/src/soar_sdk/templates/widgets/widget_template.html This Jinja2 template block conditionally displays application logos based on the `title_logo` variable. It includes both dark and regular versions of the logo, linking to app resources and using fallback names for alt text. ```Jinja2 {% if title_logo %} ![{{ dark_title_logo_name or '' }}](/app_resource/{{ dark_title_logo }}) ![{{ title_logo_name or '' }}](/app_resource/{{ title_logo }}) {% endif %} {% block title %}{% endblock %} {% block subtitle %}{% endblock %} ```