Skip to main content

CrowdStrike Falcon Foundry Function Software Developer Kit for Python

Project description

CrowdStrike Falcon

Falcon Foundry Function as a Service Python FDK

falcon-foundry-python is a community-driven, open source project designed to enable the authoring of functions. While not a formal CrowdStrike product, the falcon-foundry-python project is maintained by CrowdStrike and supported in partnership with the open source developer community.

Installation ⚙️

Installation via pip

The FDK can be installed or updated via pip install:

python3 -m pip install crowdstrike-falcon-foundry

Quickstart 💫

Example Code

Add the FDK to your project by following the installation instructions above, then create your main.py that contains your handler implementation:

from falconfoundry import (
    FoundryAPIError,
    FoundryRequest,
    FoundryResponse,
    FoundryFunction,
)


func = FoundryFunction.instance()

# An example POST handler
@func.handler(method='POST', path='/my-resource')
def on_post(request: FoundryRequest) -> FoundryResponse:
    
    # Validate the request body
    if 'name' not in request.body:
        # This example expects 'name' field in the request body.
        # Return an error response (400 - Bad Request) if not provided by the caller
        return FoundryResponse(
            code=400,
            errors=[FoundryAPIError(code=400, message='name field is missing from request body')]
        )
    
    # Process the request
    new_resource_id = 1
    # ...snip...
    
    # Return a success response
    return FoundryResponse(
        body={
           'result': f'Resource with name {request.body["name"]} is created.',
           'id': new_resource_id
        },
        code=200,
    )


if __name__ == '__main__':
    func.run()

Example breakdown

The FoundryFunction object

The FoundryFunction class wraps the Foundry Function implementation. A FoundryFunction instance can consist of one or more handlers, with each corresponding to an endpoint. You should only have one FoundryFunction object defined per function implemented within your Foundry application. Multiple instances will result in unexpected behavior.

func = FoundryFunction.instance()

The function handler decorator

The handler decorator defines a Python method as handler for a specific endpoint. This handler must have the method and path keywords defined. The method keyword will correspond to one of the supported HTTP methods (GET, POST, PUT, PATCH or DELETE). The path keyword will define the URL used to trigger this method, and should be unique.

@func.handler(method='POST', path='/my-resource')

Method details - FoundryRequest

Our python handler function is decorated with @func.handler. The first argument to our method must be a FoundryRequest object which defines the HTTP request payload and metadata.

A FoundryRequest object consists of:

  • body: The request payload as given in the Function Gateway body payload field. This will be deserialized as a dictionary (Dict[str, Any]).
  • params: The request headers (params.header) and query string parameters (params.query).
  • url: The request path relative to the function. This is a string.
  • method: The request HTTP method or verb.
  • access_token: Caller-supplied access token.

In this example we've named our method on_post, but you may name the method whatever you wish.

def on_post(request: FoundryRequest) -> FoundryResponse:

Method details - FoundryResponse

The return type for our method should be a FoundryResponse object.

Successful responses

A successful response will be a FoundryResponse object containing the fields body (a dictionary containing the response returned to the function) and code (the HTTP status code returned to the function).

# Return a success response
return FoundryResponse(
    body={
        'result': f'Resource with name {request.body["name"]} is created.',
        'id': new_resource_id
    },
    code=200,
)
Error responses

An unsuccessful response will be a FoundryResponse object containing the fields errors (a list of FoundryAPIError objects) and code (the HTTP status code returned to the function).

A FoundryAPIError object will contain a code indicating the type of the error and a message which should contain the error text.

If no code is provided as part of the FoundryResponse object, this value will be derived from the greatest valid HTTP code present within the FoundryAPIError list.

return FoundryResponse(
    code=400,
    errors=[FoundryAPIError(code=400, message='id field is missing from request params')]
)

Running the function

The runner method is the general starting point for execution of your function and will be executed when your code is called by Foundry. This causes the FoundryFunction to initialize and start execution. This should be the last line of your script as code defined after the func.run() statement may not be executed. You may implement code before this statement as necessary.

if __name__ == '__main__':
    func.run()

Retrieving parameters passed to your FoundryFunction

You may retrieve query string values passed to your function by accessing the request.params.query dictionary.

resource_id = request.params.query.get("id")

Additional HTTP method examples

Different types of HTTP requests will follow the same pattern demonstrated in our POST request above.

HTTP GET
from falconfoundry import (
    FoundryAPIError,
    FoundryRequest,
    FoundryResponse,
    FoundryFunction,
)


func = FoundryFunction.instance()

# An example GET handler
@func.handler(method='GET', path='/my-resource')
def on_get(request: FoundryRequest) -> FoundryResponse:  
    
    # Fetch the requested resources
    resources = []
    # ...snip...
    
    # Return the requested resources
    return FoundryResponse(
        body={'resources': resources},
        code=200,
    )


if __name__ == '__main__':
    func.run()
HTTP PUT
from falconfoundry import (
    FoundryAPIError,
    FoundryRequest,
    FoundryResponse,
    FoundryFunction,
)


func = FoundryFunction.instance()

# An example PUT handler
@func.handler(method='PUT', path='/my-resource')
def on_put(request: FoundryRequest) -> FoundryResponse:  
    
    # Obtain the id of the resource to update from the request query parameters
    resource_id = request.params.query.get('id')
    if not resource_id:
        # This example expects 'id' field in the request query parameters.
        # Returns an error response (400 - Bad Request) if not provided by the caller
        return FoundryResponse(
            code=400,
            errors=[FoundryAPIError(code=400, message='id field is missing from request params')]
        )
    
    # Get the update data provided in the request body and
    # Update the resource with the data provided
    data = request.body.get('data')
    # ...snip...
    
    # Return success with the updated resource info
    return FoundryResponse(
        body={
           'result': f'Resource {resource_id} is updated successfully.',
           'data': data
        },
        code=200,
    )


if __name__ == '__main__':
    func.run()
HTTP DELETE
from falconfoundry import (
    FoundryAPIError,
    FoundryRequest,
    FoundryResponse,
    FoundryFunction,
)


func = FoundryFunction.instance()

# An example DELETE handler
@func.handler(method='DELETE', path='/my-resource') 
def on_delete(request: FoundryRequest) -> FoundryResponse:  
   
    # Obtain the id of the resource to update from the request query parameters
    resource_id = request.params.query.get('id')
    if not resource_id:
        # This example expects 'id' field in the request query parameters.
        # Returns an error response (400 - Bad Request) if not provided by the caller
        return FoundryResponse(
            code=400,
            errors=[FoundryAPIError(code=400, message='id field is missing from request params')]
        )
    
    # Delete the requested resource
    # ...snip...
    
    # Return success back to the caller
    return FoundryResponse(
        code=200,
    )


if __name__ == '__main__':
    func.run()

Testing locally

The FDK provides an out-of-the-box runtime for executing the function.

Executing your code

[!NOTE] A basic HTTP server will be started to listen on port 8081 when executing your code locally.

cd my-project
python3 main.py

You can use curl or another python application to make requests to the web server that has been started.

Example POST request
# Test POST /my-resource request
curl --location 'http://localhost:8081' \
  -H 'Content-Type: application/json' \
  --data '{
    "body": {
        "name": "bar"
    },
    "method": "POST",
    "url": "/my-resource"
}'
Example GET request
# Test GET /my-resource request
curl --location 'http://localhost:8081' \
  -H 'Content-Type: application/json' \
  --data '{
    "method": "GET",
    "url": "/my-resource"
}'
Example PUT request
# Test PUT /my-resource request
curl --location 'http://localhost:8081' \
  -H 'Content-Type: application/json' \
  --data '{
    "body": {
        "name": "bar",
    },
    "params": {
        "query": {
          "id": "12345"
        }
    },
    "method": "PUT",
    "url": "/my-resource"
}'
Example DELETE request
# Test DELETE /my-resource request
curl --location 'http://localhost:8081' \
  -H 'Content-Type: application/json' \
  --data '{
    "params": {
        "query": {
          "id": "12345"
        }
    },
    "method": "DELETE",
    "url": "/my-resource"
}'

Executing your code without an HTTP server

If you prefer to test your function locally without starting an HTTP server, you can provide the request payload in a JSON file on the command line.

First, create a JSON file containing your request payload. Example request_payload.json file:

{
    "body": {
        "name": "bar"
    },
    "method": "POST",
    "url": "/my-resource"
}

Then invoke your function handler as follows:

python3 main.py --data ./request_payload.json

This will execute the requested function handler and print the response returned, including the response status code, body and headers.

You can also provide request headers to your function on the command line:

python3 main.py --data request_payload.json --header "Content-Type: application/json" --header "X-CUSTOM-HEADER: testing"

Leveraging the FalconPy SDK to interact with CrowdStrike APIs inside of your Foundry function

Foundry function authors should include crowdstrike-falconpy within their requirements.txt file and then import falconpy explicitly in their function code.

You may use any FalconPy Service Class or the FalconPy Uber Class within your function.

General FalconPy usage information

FalconPy implements Context Authentication for use within Foundry Functions, removing the need for developers to provide their access_token to the class as this value is provided by context when the function is executed.

[!TIP] If you are instantiating a FalconPy class within your method, you will need to do this for every method you implement. If you instantiate your the FalconPy class outside of your method, but before the funct.run() statement, this object will be available to all methods defined in your function code.

To test the function locally without having to adjust your code, you can set the following environment variables in your local environment:

Variable Name Purpose
FALCON_CLIENT_ID CrowdStrike Falcon API client ID
FALCON_CLIENT_SECRET CrowdStrike Falcon API client secret

FalconPy usage example

from falconpy import Hosts
from falconfoundry import (
    FoundryFunction,
    FoundryRequest,
    FoundryResponse,
    FoundryAPIError
)


func = FoundryFunction.instance()


@func.handler(method='POST', path='/hosts-query')
def on_hosts_query(request: FoundryRequest) -> FoundryResponse:
    
    # get the requested Host IDs from the request body
    host_ids = request.body.get("ids")
    if not host_ids:
       return FoundryResponse(
            code=400,
            errors=[FoundryAPIError(code=400, message='Required host ids are not provided')]
        )
    
    # Initialize falconpy client for Hosts API
    # This example uses context authentication
    hosts_client = Hosts()
    
    # Call falconpy API to fetch the details of the requested hosts
    api_result = hosts_client.get_device_details_v1(ids=host_ids)
    if api_result['status_code'] != 200:
        # falconpy API returned an error
        response = FoundryResponse(
           code=api_result['status_code'],
            errors=[
               FoundryAPIError(code=api_result['status_code'], message="falconpy API call failed")
            ]
        )
    else:
       # falconpy API was successful, return the requested data
        response = FoundryResponse(
            body={
                'hosts': api_result['body']['resources']
            },
            code=200
        )
       
    return response

if __name__ == '__main__':
    func.run()

Using custom configurations and debug logging

Foundry supports custom configurations and debug logging to support developers with the implementation of their functions.

Implementing custom configurations

Using a custom configuration within a function is optional and may be provided as either a JSON or YAML file. This functionality is intended to give the developer a location to store custom configuration data, such as API keys and credentials, in a secure manner when the function is deployed on Falcon platform.

[!NOTE] The configuration is encrypted with a unique key per function in the cloud.

To utilize a custom configuration within a function, include the config keyword argument as shown in the example below.

The config keyword is an optional argument to the handler function and must be the second argument if provided.

Enabling logging

Logging for a function is optional but adding log messages to functions can make triage and debugging easier when troubleshooting problems. When a function is deployed on the Falcon platform, the messages logged with the provided logger are formatted in a custom manner with fields injected to assist with working within the Falcon logging infrastructure.

[!NOTE] You may use native FalconPy logging in conjuction with your function logger config by providing the debug keyword when you instantiate your FalconPy class.

To utilize logging in a function, include the logger parameter as shown in the example below.

logger is an optional parameter to the handler function and must the third parameter if provided.

from logging import Logger
from typing import Dict
from falconpy import Hosts
from falconfoundry import (
    FoundryFunction,
    FoundryRequest,
    FoundryResponse,
    FoundryAPIError
)


func = FoundryFunction.instance()


@func.handler(method='POST', path='/hosts-query')
def on_hosts_query(request: FoundryRequest, config: Dict[str, object] | None, logger: Logger) -> FoundryResponse:
    
    logger.info("POST handler for /hosts-query is invoked")

    # get the requested Host IDs from the request body
    host_ids = request.body.get("ids")
    if not host_ids:
       logger.error("ids argument is missing from request parameters")
       return FoundryResponse(
            code=400,
            errors=[FoundryAPIError(code=400, message='Required host ids are not provided')]
        )

    # Example config provided to the function
    action = "Dev resource update"
    if config and config.get("is_production", False):
        action = "Production resource update"

    # Initialize falconpy client for Hosts API and enable debugging
    hosts_client = Hosts(debug=True)
    
    # Call falconpy API to fetch the details of the requested hosts
    api_result = hosts_client.get_device_details_v1(ids=host_ids)
    if api_result['status_code'] != 200:
        # FalconPy SDK returned an error
        response = FoundryResponse(
           code=api_result['status_code'],
            errors=[
               FoundryAPIError(code=api_result['status_code'], message="FalconPy API call failed")
            ]
        )
    else:
       # falconpy API was successful, return the requested data
        response = FoundryResponse(
            body={
                'hosts': api_result['body']['resources'],
                'action': action
            },
            code=200
        )
       
    return response

if __name__ == '__main__':
    func.run()


WE STOP BREACHES

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

crowdstrike_falcon_foundry-1.0.1.tar.gz (16.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

crowdstrike_falcon_foundry-1.0.1-py3-none-any.whl (18.7 kB view details)

Uploaded Python 3

File details

Details for the file crowdstrike_falcon_foundry-1.0.1.tar.gz.

File metadata

File hashes

Hashes for crowdstrike_falcon_foundry-1.0.1.tar.gz
Algorithm Hash digest
SHA256 e6d6ec73cbd318d494ae13a5cb6b634f4af654e385b67ee053da10cc394a9ea3
MD5 7b68929a554cb40ffe8c080556a912b2
BLAKE2b-256 456f5351b3a2d1a6bf8b0012b98b715879b8e9547c7441496e1ab9f2265d37b1

See more details on using hashes here.

File details

Details for the file crowdstrike_falcon_foundry-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for crowdstrike_falcon_foundry-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 20519e84d69d63fa7b82395173d25b5cddebca0437006e97e7d7fa1cd1cc7b26
MD5 4183cfd164c7899db5ece0bf957e002a
BLAKE2b-256 2c06bbba6e91624503b426d03f109827610d592865acb90ec1aaa29312553a8d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page