src/app.py

This document will dive deeper into the initial structure of the app.py file when starting working with Apps.

The file consists of a few main parts:

  1. Logger initialization

  2. Asset definition

  3. App initialization

  4. Actions definitions

  5. App CLI invocation

Here’s an example app.py file which uses a wide variety of the features available in the SDK:

  1from collections.abc import Generator, Iterator
  2from datetime import UTC, datetime
  3from zoneinfo import ZoneInfo
  4
  5from soar_sdk.abstract import SOARClient
  6from soar_sdk.action_results import ActionOutput, MakeRequestOutput, OutputField
  7from soar_sdk.app import App
  8from soar_sdk.asset import AssetField, BaseAsset, FieldCategory
  9from soar_sdk.logging import getLogger
 10from soar_sdk.models.artifact import Artifact
 11from soar_sdk.models.container import Container
 12from soar_sdk.models.finding import Finding
 13from soar_sdk.params import (
 14    MakeRequestParams,
 15    OnESPollParams,
 16    OnPollParams,
 17    Param,
 18    Params,
 19)
 20
 21logger = getLogger()
 22
 23# Test mail template for ES findings
 24SAMPLE_EMAIL_TEMPLATE = """From: suspicious@example.com
 25To: {user}
 26Subject: Suspicious Activity Detected
 27Date: {date}
 28
 29This is a suspicious email that triggered the risk threshold.
 30Event ID: {event_id}
 31"""
 32
 33# Test event data CSV for attachments
 34SAMPLE_EVENTS_CSV = """timestamp,user,action,risk_score
 35{timestamp},{{user}},login_failed,{{risk_score}}
 36{timestamp},{{user}},access_denied,{{secondary_score}}
 37"""
 38
 39
 40class Asset(BaseAsset):
 41    base_url: str = AssetField(default="https://example")
 42    api_key: str = AssetField(sensitive=True, description="API key for authentication")
 43    key_header: str = AssetField(
 44        default="Authorization",
 45        value_list=["Authorization", "X-API-Key"],
 46        description="Header for API key authentication",
 47    )
 48    timezone: ZoneInfo
 49    timezone_with_default: ZoneInfo = AssetField(
 50        default=ZoneInfo("America/Denver"), category=FieldCategory.ACTION
 51    )
 52
 53
 54app = App(
 55    asset_cls=Asset,
 56    name="example_app",
 57    appid="9b388c08-67de-4ca4-817f-26f8fb7cbf55",
 58    app_type="sandbox",
 59    product_vendor="Splunk Inc.",
 60    logo="logo.svg",
 61    logo_dark="logo_dark.svg",
 62    product_name="Example App",
 63    publisher="Splunk Inc.",
 64    min_phantom_version="6.2.2.134",
 65)
 66
 67
 68@app.test_connectivity()
 69def test_connectivity(soar: SOARClient, asset: Asset) -> None:
 70    soar.get("rest/version")
 71    container_id = soar.get_executing_container_id()
 72    logger.info(f"current executing container's container_id is: {container_id}")
 73    asset_id = soar.get_asset_id()
 74    logger.info(f"current executing container's asset_id is: {asset_id}")
 75    logger.info(f"testing connectivity against {asset.base_url}")
 76    logger.debug("hello")
 77    logger.warning("this is a warning")
 78    logger.progress("this is a progress message")
 79
 80
 81class ActionOutputSummary(ActionOutput):
 82    is_success: bool
 83
 84
 85@app.action()
 86def test_summary_with_list_output(
 87    params: Params, asset: Asset, soar: SOARClient
 88) -> list[ActionOutput]:
 89    soar.set_summary(ActionOutputSummary(is_success=True))
 90    return [ActionOutput(), ActionOutput()]
 91
 92
 93@app.action()
 94def test_empty_list_output(
 95    params: Params, asset: Asset, soar: SOARClient
 96) -> list[ActionOutput]:
 97    return []
 98
 99
100class JsonOutput(ActionOutput):
101    name: str = OutputField(example_values=["John", "Jane", "Jim"], column_name="Name")
102    age: int = OutputField(example_values=[25, 30, 35], column_name="Age")
103
104
105class TableParams(Params):
106    company_name: str = Param(column_name="Company Name", default="Splunk")
107
108
109@app.action(render_as="json")
110def test_json_output(params: Params, asset: Asset, soar: SOARClient) -> JsonOutput:
111    return JsonOutput(name="John", age=25)
112
113
114@app.action(render_as="table")
115def test_table_output(
116    params: TableParams, asset: Asset, soar: SOARClient
117) -> JsonOutput:
118    return JsonOutput(name="John", age=25)
119
120
121from .actions.reverse_string import render_reverse_string_view
122
123app.register_action(
124    "actions.reverse_string:reverse_string",
125    action_type="investigate",
126    verbose="Reverses a string.",
127    view_template="reverse_string.html",
128    view_handler=render_reverse_string_view,
129)
130
131from .actions.generate_category import render_statistics_chart
132
133app.register_action(
134    "actions.generate_category:generate_statistics",
135    action_type="investigate",
136    verbose="Generate statistics with pie chart reusable component.",
137    view_handler=render_statistics_chart,
138)
139
140
141class MakeRequestParamsCustom(MakeRequestParams):
142    endpoint: str = Param(
143        description="The endpoint to send the request to. Base url is already included in the endpoint.",
144        required=True,
145    )
146
147
148@app.make_request()
149def http_action(params: MakeRequestParamsCustom, asset: Asset) -> MakeRequestOutput:
150    logger.info(f"HTTP action triggered with params: {params}")
151    return MakeRequestOutput(
152        status_code=200,
153        response_body=f"Base url is {asset.base_url}",
154    )
155
156
157@app.on_poll()
158def on_poll(
159    params: OnPollParams, soar: SOARClient, asset: Asset
160) -> Iterator[Container | Artifact]:
161    if params.is_manual_poll():
162        logger.info("Manual poll (poll now) detected")
163    else:
164        logger.info("Scheduled poll detected")
165
166    # Create container first for artifacts
167    yield Container(
168        name="Network Alerts",
169        description="Some network-related alerts",
170        severity="medium",
171    )
172
173    # Simulate collecting 2 network artifacts that will be put in the network alerts container
174    for i in range(1, 3):
175        logger.info(f"Processing network artifact {i}")
176
177        alert_id = f"testalert-{datetime.now(UTC).strftime('%Y%m%d')}-{i}"
178        artifact = Artifact(
179            name=f"Network Alert {i}",
180            label="alert",
181            severity="medium",
182            source_data_identifier=alert_id,
183            type="network",
184            description=f"Example network alert {i} from polling operation",
185            data={
186                "alert_id": alert_id,
187                "source_ip": f"10.0.0.{i}",
188                "destination_ip": "192.168.0.1",
189                "protocol": "TCP",
190            },
191        )
192
193        yield artifact
194
195
196@app.on_es_poll()
197def on_es_poll(
198    params: OnESPollParams, soar: SOARClient, asset: Asset
199) -> Generator[Finding, int | None]:
200    for i in range(1, 3):
201        logger.info(f"Processing ES finding {i}")
202
203        container_id = yield Finding(
204            rule_title=f"Risk threshold exceeded for user-{i}",
205            rule_description="Risk Threshold Exceeded for an object over a 24 hour period",
206            security_domain="threat",
207            risk_object=f"user{i}@example.com",
208            risk_object_type="user",
209            risk_score=75.0 + (i * 10),
210            status="New",
211            urgency="medium",
212        )
213
214        # Attach evidence
215        email_evidence = SAMPLE_EMAIL_TEMPLATE.format(
216            user=f"user{i}@example.com",
217            date=datetime.now(UTC).strftime("%a, %d %b %Y %H:%M:%S +0000"),
218            event_id=f"EVT-{i:04d}",
219        )
220
221        event_data = SAMPLE_EVENTS_CSV.format(
222            timestamp=datetime.now(UTC).isoformat()
223        ).format(
224            user=f"user{i}@example.com",
225            risk_score=75.0 + (i * 10),
226            secondary_score=50.0 + (i * 5),
227        )
228
229        soar.vault.create_attachment(
230            container_id,
231            file_content=email_evidence,
232            file_name=f"suspicious_email_user{i}.eml",
233            metadata={"type": "email_evidence", "source": "investigation_mailbox"},
234        )
235        soar.vault.create_attachment(
236            container_id,
237            file_content=event_data,
238            file_name=f"risk_events_user{i}.csv",
239            metadata={"type": "event_log", "event_count": "2"},
240        )
241
242
243app.register_action(
244    "actions.async_action:async_process",
245    action_type="investigate",
246    verbose="Processes a message asynchronously with concurrent HTTP requests.",
247)
248
249app.register_action(
250    "actions.async_action:sync_process",
251    action_type="investigate",
252    verbose="Processes a message synchronously with sequential HTTP requests.",
253)
254
255
256class GeneratorActionOutput(ActionOutput):
257    iteration: int
258
259
260class GeneratorActionSummary(ActionOutput):
261    total_iterations: int
262
263
264@app.action(summary_type=GeneratorActionSummary)
265def generator_action(
266    params: Params, soar: SOARClient[GeneratorActionSummary], asset: Asset
267) -> Iterator[GeneratorActionOutput]:
268    """Generates a sequence of numbers."""
269    logger.info(f"Generator action triggered with params: {params}")
270    for i in range(5):
271        yield GeneratorActionOutput(iteration=i)
272    soar.set_summary(GeneratorActionSummary(total_iterations=5))
273
274
275@app.action()
276def write_state(params: Params, soar: SOARClient, asset: Asset) -> ActionOutput:
277    asset.cache_state.clear()
278    assert asset.cache_state == {}
279    asset.cache_state["value"] = "banana"
280    return ActionOutput()
281
282
283@app.action()
284def read_state(params: Params, soar: SOARClient, asset: Asset) -> ActionOutput:
285    assert asset.cache_state == {"value": "banana"}
286    return ActionOutput()
287
288
289if __name__ == "__main__":
290    app.cli()

Components of the app.py File

Let’s dive deeper into each part of the app.py file above:

Logger Initialization

Logger initialization
 9from soar_sdk.logging import getLogger
10from soar_sdk.models.artifact import Artifact
11from soar_sdk.models.container import Container
12from soar_sdk.models.finding import Finding
13from soar_sdk.params import (
14    MakeRequestParams,
15    OnESPollParams,
16    OnPollParams,
17    Param,
18    Params,
19)
20
21logger = getLogger()

The SDK provides a logging interface via the getLogger() function. This is a standard Python logger which is pre-configured to work with either the local CLI or the Splunk SOAR platform. Within the platform,

  • logger.debug() and logger.warning() messages are written to the spawn.log file at DEBUG level.

  • logger.error() and logger.critical() messages are written to the spawn.log file at ERROR level.

  • logger.info() messages are sent to the Splunk SOAR platform as persistent action progress messages, visible in the UI.

  • logger.progress() messages are sent to the Splunk SOAR platform as transient action progress messages, visible in the UI, but overwritten by subsequent progress messages.

When running locally via the CLI, all log messages are printed to the console, in colors corresponding to their log level.

Asset Definition

Asset definition
40class Asset(BaseAsset):
41    base_url: str = AssetField(default="https://example")
42    api_key: str = AssetField(sensitive=True, description="API key for authentication")
43    key_header: str = AssetField(
44        default="Authorization",
45        value_list=["Authorization", "X-API-Key"],
46        description="Header for API key authentication",
47    )
48    timezone: ZoneInfo
49    timezone_with_default: ZoneInfo = AssetField(
50        default=ZoneInfo("America/Denver"), category=FieldCategory.ACTION
51    )

Apps should define an asset class to hold configuration information for the app. The asset class should be a pydantic model that inherits from BaseAsset and defines the app’s configuration fields. Fields requiring metadata should be defined using an instance of AssetField(). The SDK uses this information to generate the asset configuration form in the Splunk SOAR platform UI.

App Initialization

App initialization
54app = App(
55    asset_cls=Asset,
56    name="example_app",
57    appid="9b388c08-67de-4ca4-817f-26f8fb7cbf55",
58    app_type="sandbox",
59    product_vendor="Splunk Inc.",
60    logo="logo.svg",
61    logo_dark="logo_dark.svg",
62    product_name="Example App",
63    publisher="Splunk Inc.",
64    min_phantom_version="6.2.2.134",
65)

This is how you initialize the basic App instance. The app object will be used to register actions, views, and/or webhooks. Keep in mind this object variable and its path are referenced by pyproject.toml so the Splunk SOAR platform knows where the app instance is provided.

Action Definitions

Actions are defined as standalone functions, with a few important rules and recommendations.

Action Metadata

Action definition carry with them important metadata which is used by the Splunk SOAR platform to present the action in the UI, and to generate the app’s manifest. Often, this metadata can be derived automatically from the action function’s signature:

  • The action’s “identifier” is, by default, the name of the action function (e.g. my_action).

  • The action’s “name” is, by default, the action function’s name with spaces instead of underscores (e.g. my action).

  • The action’s “description” is, by default, the action function’s docstring.

  • The action’s “type” is, by default, generic unless the action is one of the reserved names like test connectivity or on poll.

Note

By convention, action names should be lowercase, with 2-3 words. Keep action names short but descriptive, and avoid using the name of the app or external service in action names. Where feasible, it’s recommended to consider reusing action names across different apps (e.g. get email) to provide a more consistent user experience.

Action Arguments

There is a magic element, similar to pytest fixtures, in the action arguments. The type hints for the argument definitions of an action function are critical to this mechanism. The rules are as follows:

  • The first positional argument of an action function must be the params argument, and its type hint must be a Pydantic model inheriting from Params. The position and type of this argument are required. The name params is a convention, but not strictly required.

  • If an action function has any argument named soar, at runtime the SDK will provide an instance of a SOARClient implementation as that argument, which is already authenticated with Splunk SOAR. The type hint for this argument should be SOARClient.

  • If an action function has any argument named asset, at runtime the SDK will provide an instance of the app’s asset class, populated with the asset configuration for the current action run. The type hint for this argument should be the app’s asset class.

Note

The special actions which define their own decorators have stricter rules about the type of the params argument. For example, the on poll action must take an OnPollParams instance as its params argument, and test connectivity must take no params argument at all.

Action Returns

An action’s return type annotation is critical for the Splunk SOAR platform to understand, via datapaths, what an action’s output looks like. In practice, this means that you must define a class inheriting from ActionOutput to represent the action’s output, and then return an instance of that class from your action function:

from soar_sdk.action_results import ActionOutput

class MyActionOutput(ActionOutput):
    field1: str
    field2: int

@app.action()
def my_action(params: MyActionParams) -> MyActionOutput:
    # action logic here
    return MyActionOutput(field1="value", field2=42)
Advanced Return Types

For more advanced use cases, an action’s return type can be a list, Iterator, or AsyncGenerator that yields multiple ActionOutput objects:

@app.action()
def my_action_list(params: MyActionParams) -> list[MyActionOutput]:
    # action logic here
    return [
        MyActionOutput(field1="value1", field2=1),
        MyActionOutput(field1="value2", field2=2)
    ]
from typing import Iterator

@app.action()
def my_action_iterator(params: MyActionParams) -> Iterator[MyActionOutput]:
    # action logic here
    yield MyActionOutput(field1="value1", field2=1)
    yield MyActionOutput(field1="value2", field2=2)
from typing import AsyncGenerator

@app.action()
async def my_action_async_generator(
    params: MyActionParams,
    asset: Asset,
) -> AsyncGenerator[MyActionOutput]:
    async with client = httpx.AsyncClient() as client:
        async for i in range(10):
            response = await client.get(
                f"{asset.base_url}/data",
                params={"page": i}
            )
            yield MyActionOutput(**response.json())

test connectivity Action

Test connectivity action definition
68@app.test_connectivity()
69def test_connectivity(soar: SOARClient, asset: Asset) -> None:
70    soar.get("rest/version")
71    container_id = soar.get_executing_container_id()
72    logger.info(f"current executing container's container_id is: {container_id}")
73    asset_id = soar.get_asset_id()
74    logger.info(f"current executing container's asset_id is: {asset_id}")
75    logger.info(f"testing connectivity against {asset.base_url}")
76    logger.debug("hello")
77    logger.warning("this is a warning")
78    logger.progress("this is a progress message")

All apps must register exactly one test connectivity action in order to be considered valid by Splunk SOAR. This action takes no parameters, and is used to verify that the app and its associated asset configuration are working correctly. Running test connectivity on the Splunk SOAR platform should answer the questions:

  • Can the app connect to the external service?

  • Can the app authenticate with the external service?

  • Does the app have the necessary permissions to perform its actions?

A successful test connectivity action should return None, and a failure should raise an ActionFailure with a descriptive error message.

on poll Action

on poll action definition
157@app.on_poll()
158def on_poll(
159    params: OnPollParams, soar: SOARClient, asset: Asset
160) -> Iterator[Container | Artifact]:
161    if params.is_manual_poll():
162        logger.info("Manual poll (poll now) detected")
163    else:
164        logger.info("Scheduled poll detected")
165
166    # Create container first for artifacts
167    yield Container(
168        name="Network Alerts",
169        description="Some network-related alerts",
170        severity="medium",
171    )
172
173    # Simulate collecting 2 network artifacts that will be put in the network alerts container
174    for i in range(1, 3):
175        logger.info(f"Processing network artifact {i}")
176
177        alert_id = f"testalert-{datetime.now(UTC).strftime('%Y%m%d')}-{i}"
178        artifact = Artifact(
179            name=f"Network Alert {i}",
180            label="alert",
181            severity="medium",
182            source_data_identifier=alert_id,
183            type="network",
184            description=f"Example network alert {i} from polling operation",
185            data={
186                "alert_id": alert_id,
187                "source_ip": f"10.0.0.{i}",
188                "destination_ip": "192.168.0.1",
189                "protocol": "TCP",
190            },
191        )
192
193        yield artifact

on poll is another special action that apps may choose to implement. This action always takes an OnPollParams instance as its parameter. If defined, this action will be called in order to ingest new data into the Splunk SOAR platform. The action should yield Container and/or Artifact instances representing the new data to be ingested. The SDK will handle actually creating the containers and artifacts in the platform.

Make Request Action

Make request action definition
148@app.make_request()
149def http_action(params: MakeRequestParamsCustom, asset: Asset) -> MakeRequestOutput:
150    logger.info(f"HTTP action triggered with params: {params}")
151    return MakeRequestOutput(
152        status_code=200,
153        response_body=f"Base url is {asset.base_url}",
154    )

Apps may define a special “make request” action, which can be used to interact with the underlying external service’s REST API directly. Having this action available can be useful when there are parts of the REST API that don’t have dedicated actions implemented in the app.

We create an action by decorating a function with the app.action decorator. The default action_type is generic, so usually you will not have to provide this argument for the decorator. This is not the case for the test action type though, so we provide this type here explicitly.

Custom Actions

Actions can be registered one of two ways:

Using the action() decorator to decorate a standalone function.

decorated action definition
264@app.action(summary_type=GeneratorActionSummary)
265def generator_action(
266    params: Params, soar: SOARClient[GeneratorActionSummary], asset: Asset
267) -> Iterator[GeneratorActionOutput]:
268    """Generates a sequence of numbers."""
269    logger.info(f"Generator action triggered with params: {params}")
270    for i in range(5):
271        yield GeneratorActionOutput(iteration=i)
272    soar.set_summary(GeneratorActionSummary(total_iterations=5))

Using the register_action() method to register a function which may be defined in another module.

The two methods are functionally equivalent. The decorator method is often more convenient for simple actions, while the registration method may be preferable for larger apps where actions are defined in separate modules. Apps may use either or both methods to register their actions.

App CLI Invocation

App CLI invocation
289if __name__ == "__main__":
290    app.cli()

A generic invocation to the app’s cli() method, which enables running the app actions directly from command line. The app template created by soarapps init includes this snippet by default, and it is recommended to keep it in order to facilitate local testing and debugging of your app actions.