Skip to main content

Audit | Python SDK

The audit API is designed for recording a trail of application-based user activity in a scalable, tamper-proof log.

Audit client

Audit(token, config, private_key_file, public_key_info, tenant_id, logger_name, config_id)

Initializes a new Audit client.

required parameters

str

Pangea API token.

optional parameters

PangeaConfig | None

Configuration.

str

Private key filepath.

dict[str, str]

Public key information.

str | None

Tenant ID.

str

Logger name.

str | None

Configuration ID.

config = PangeaConfig(domain="pangea_domain")
audit = Audit(token="pangea_token", config=config)

download-file

Audit.download_file()

Download search results

Audit.download_results(result_id, format, request_id, return_context)

Get all search results as a compressed (gzip) CSV file.

optional parameters

Optional[str]

ID returned by the search API.

DownloadFormat

Format for the records.

Optional[str]

ID returned by the export API.

bool

Return the context data needed to decrypt secure audit events that have been redacted with format preserving encryption.

Response Object

URL where search results can be downloaded.

response = audit.download_results(
    result_id="pas_[...]",
    format=DownloadFormat.JSON,
)

Export from the audit log

Audit.export(format, start, end, order, order_by, verbose)

Bulk export of data from the Secure Audit Log, with optional filtering.

optional parameters

DownloadFormat

Format for the records.

Optional[datetime.datetime]

The start of the time range to perform the search on.

Optional[datetime.datetime]

The end of the time range to perform the search on. If omitted, then all records up to the latest will be searched.

Optional[SearchOrder]

Specify the sort order of the response.

Optional[str]

Name of column to sort the results by.

bool

Whether or not to include the root hash of the tree and the membership proof for each record.

export_res = audit.export(verbose=False)

# Export may take several dozens of minutes, so polling for the result
# should be done in a loop. That is omitted here for brevity's sake.
try:
    audit.poll_result(request_id=export_res.request_id)
except AcceptedRequestException:
    # Retry later.

# Download the result when it's ready.
download_res = audit.download_results(request_id=export_res.request_id)
download_res.result.dest_url
# => https://pangea-runtime.s3.amazonaws.com/audit/xxxxx/search_results_[...]

fix-consistency-proofs

Audit.fix_consistency_proofs()

Log an entry

Audit.log(message, actor, action, new, old, source, status, target, timestamp, verify, sign_local, verbose, tenant_id)

Create a log entry in the Secure Audit Log.

required parameters

str, dict

A message describing a detailed account of what happened.

optional parameters

str

Record who performed the auditable activity.

str

The auditable action that occurred.

str, dict

The value of a record after it was changed.

str, dict

The value of a record before it was changed.

str

Used to record the location from where an activity occurred.

str

Record whether or not the activity was successful.

str

Used to record the specific record that was targeted by the auditable activity.

datetime

An optional client-supplied timestamp.

bool

True to verify logs consistency after response.

bool

True to sign event with local key.

bool

True to get a more verbose response.

string

Used to record the tenant associated with this activity.

Response Object

A PangeaResponse where the hash of event data and optional verbose results are returned in the response.result field. Available response fields can be found in our API documentation.

log_response = audit.log(
    message="hello world",
    verbose=True,
)

Log multiple entries

Audit.log_bulk(events, sign_local, verbose)

Create multiple log entries in the Secure Audit Log.

required parameters

List[dict[str, Any]]

events to be logged

optional parameters

bool

True to sign event with local key.

bool

True to get a more verbose response.

Response Object

A PangeaResponse where the hash of event data and optional verbose results are returned in the response.result field. Available response fields can be found in our API documentation.

log_response = audit.log_bulk(
    events=[{"message": "hello world"}],
    verbose=True,
)

Log multiple entries asynchronously

Audit.log_bulk_async(events, sign_local, verbose)

Asynchronously create multiple log entries in the Secure Audit Log.

required parameters

List[dict[str, Any]]

events to be logged

optional parameters

bool

True to sign event with local key.

bool

True to get a more verbose response.

Response Object

A PangeaResponse where the hash of event data and optional verbose results are returned in the response.result field. Available response fields can be found in our API documentation.

log_response = audit.log_bulk_async(
    events=[{"message": "hello world"}],
    verbose=True,
)

Log an entry

Audit.log_event(event, verify, sign_local, verbose)

Create a log entry in the Secure Audit Log.

required parameters

dict[str, Any]

event to be logged

optional parameters

bool

True to verify logs consistency after response.

bool

True to sign event with local key.

bool

True to get a more verbose response.

Response Object

A PangeaResponse where the hash of event data and optional verbose results are returned in the response.result field. Available response fields can be found in our API documentation.

try:
    log_response = audit.log({"message": "hello world"}, verbose=True)
    print(f"Response. Hash: {log_response.result.hash}")
except pe.PangeaAPIException as e:
    print(f"Request Error: {e.response.summary}")
    for err in e.errors:
        print(f"\t{err.detail} \n")

Log streaming endpoint

Audit.log_stream(data)

This API allows 3rd party vendors (like Auth0) to stream events to this endpoint where the structure of the payload varies across different vendors.

required parameters

dict

Event data. The exact schema of this will vary by vendor.

data = {
    "logs": [
        {
            "log_id": "some log ID",
            "data": {
                "date": "2024-03-29T17:26:50.193Z",
                "type": "sapi",
                "description": "Create a log stream",
                "client_id": "some client ID",
                "ip": "127.0.0.1",
                "user_agent": "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0",
                "user_id": "some user ID",
            },
        }
        # ...
    ]
}

response = audit.log_stream(data)

Poll result

Audit.poll_result(exception)

Returns request's result that has been accepted by the server

optional parameters

Optional[AcceptedRequestException]

Exception that was previously raised by the SDK on a call that is being processed.

Response Object

PangeaResponse

response = service.poll_result(exception)
Audit.results(id, limit, offset, assert_search_restriction, verify_consistency, verify_events, return_context)

Fetch paginated results of a previously executed search.

required parameters

string

the id of a search action, found in response.result.id

optional parameters

integer

the maximum number of results to return, default is 20

integer

the position of the first result to return, default is 0

Dict[str, Sequence[str]]

Assert the requested search results were queried with the exact same search restrictions, to ensure the results comply to the expected restrictions.

bool

True to verify logs consistency

bool

True to verify hash events and signatures

bool

Return the context data needed to decrypt secure audit events that have been redacted with format preserving encryption.

response = audit.results(
    id="pas_sqilrhruwu54uggihqj3aie24wrctakr",
    limit=10,
    offset=0,
)

Tamperproof verification

Audit.root(tree_size)

Returns current root hash and consistency proof.

optional parameters

int

The size of the tree (the number of records). If None, endpoint will return last tree root.

Response Object

PangeaResponse[RootOutput]

response = audit.root(tree_size=7)

Search the log

Audit.search(query, order, order_by, last, start, end, limit, max_results, search_restriction, verbose, verify_consistency, verify_events, return_context)

Search for events that match the provided search criteria.

required parameters

str

Natural search string; list of keywords with optional <option>:<value> qualifiers. The following optional qualifiers are supported:

  • action
  • actor
  • message
  • new
  • old
  • status
  • target

optional parameters

SearchOrder

Specify the sort order of the response.

SearchOrderBy, str

Name of column to sort the results by.

str

Optional[str] = None,

datetime

An RFC-3339 formatted timestamp, or relative time adjustment from the current time.

datetime

An RFC-3339 formatted timestamp, or relative time adjustment from the current time.

int

Optional[int] = None,

int

Maximum number of results to return.

Dict[str, Sequence[str]]

A list of keys to restrict the search results to. Useful for partitioning data available to the query string.

bool

If true, response include root and membership and consistency proofs.

bool

True to verify logs consistency

bool

True to verify hash events and signatures

bool

Return the context data needed to decrypt secure audit events that have been redacted with format preserving encryption.

Response Object

A PangeaResponse[SearchOutput] where the first page of matched events is returned in the response.result field. Available response fields can be found in our API documentation. Pagination can be found in the search results endpoint.

response = audit.search(
    query="message:test",
    search_restriction={'source': ["monitor"]},
    limit=1,
    verify_consistency=True,
    verify_events=True,
)