### Basic Taegis SDK Usage Example Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md Demonstrates basic usage of the Taegis SDK by initializing the GraphQLService and querying current subject information. Requires the 'taegis-sdk-python' library. ```python from taegis_sdk_python import GraphQLService from pprint import pprint as pp service = GraphQLService() results = service.subjects.query.current_subject() pp(results) ``` -------------------------------- ### Taegis QL Jinja2 Template Example for Advanced Search Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/templates.md An example Jinja2 template file ('example.jinja') demonstrating how to use Taegis SDK's QL filters to construct an Advanced Search query. It shows combining IP and domain filtering with severity and time range criteria. The output generated by rendering this template is also provided. ```jinja FROM alert WHERE ( {{ ips | in('@ip') }} OR {{ domains | regex('@domain') }} ) AND severity >= {{ severity }} EARLIEST={{ earliest }} ``` ```text FROM alert WHERE ( @ip IN ('1.1.1.1','8.8.8.8') OR @domain MATCHES_REGEX 'secureworks\.com|sophos\.com' ) AND severity >= 0.6 EARLIEST=-1d ``` -------------------------------- ### Install Taegis SDK for Python Source: https://github.com/secureworks/taegis-sdk-python/blob/main/README.md This code snippet shows the command to install the Taegis SDK for Python using pip. Ensure Python 3.8 or higher is installed. ```bash python -m pip install taegis-sdk-python ``` -------------------------------- ### Taegis SDK Context Manager Example Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md Illustrates using the Taegis SDK's `GraphQLService` as a context manager to temporarily override default parameters like environment, tenant ID, and output fields for specific API calls. This example shows overriding these parameters for an `alerts_service_search` call. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.alerts.types import SearchRequestInput service = GraphQLService() with service( environment="US2", tenant_id="00000", output=""" reason alerts { total_results list { id tenant_id metadata { title severity } status } } """, # Note: Multi-line string for output field selection ): result = service.alerts.query.alerts_service_search(SearchRequestInput( offset=0, limit=10, cql_query=""" FROM alert WHERE severity >= 0.6 EARLIEST=-1d """ )) ``` -------------------------------- ### Query Events and Paginate using GraphQLService Source: https://github.com/secureworks/taegis-sdk-python/blob/main/README.md This example demonstrates querying for events with specific options and then fetching the next page of results using pagination. It uses EventQueryOptions and handles StopIteration for when there are no more pages. ```python from taegis_sdk_python.graphql.types import EventQueryOptions results = service.events.subscription.event_query( query="FROM process EARLIEST=-1d", options=EventQueryOptions( max_rows=20, page_size=10, skip_cache=True, ), ) pp(results) print() try: next_page = next( iter( { result.next for result in results if result.next } ) ) except StopIteration: next_page = None if next_page: results = service.events.subscription.event_page(page_id=next_page) pp(results) ``` -------------------------------- ### Configure Proxy Directly in Constructor (Python) Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/proxy.md This Python code illustrates initializing the Taegis SDK's GraphQLService by directly providing proxy configuration parameters. It includes setting the `proxy` URL and `proxy_auth` using `aiohttp.BasicAuth`. The example demonstrates querying current subject information using these direct settings. ```python from taegis_sdk_python import GraphQLService from aiohttp import BasicAuth service = GraphQLService( proxy="http://your.proxy.domain:port", proxy_auth=BasicAuth("", "") ) results = service.subjects.query.current_subject() print(results) ``` ```python from taegis_sdk_python import GraphQLService from aiohttp import BasicAuth service = GraphQLService() with service( proxy="http://your.proxy.domain:port", proxy_auth=BasicAuth("", "") ): results = service.subjects.query.current_subject() print(results) ``` -------------------------------- ### Build GraphQL Query String Assistance with Python SDK Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md This example demonstrates using the `_build_output_query` method from the Taegis Python SDK to assist in constructing a GraphQL query string. It utilizes `GraphQLService` and `build_output_string` to fetch a schema and then generate a query for a specific endpoint. ```python from taegis_sdk_python import GraphQLService, build_output_string from taegis_sdk_python.services.investigations.types import InvestigationStatusCountResponse service = GraphQLService() schema = service.alerts.get_sync_schema() print(service.alerts._build_output_query( operation_type="query", endpoint="investigationsStatusCount", graphql_field=schema.query_type.fields.get("investigationsStatusCount"), output=build_output_string(InvestigationStatusCountResponse) )) ``` -------------------------------- ### Enable Global Debug Logging (Python) Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/logging.md Configures the root logger to display all debug messages. This is useful for general troubleshooting but may produce excessive output. It requires the 'logging' module. ```python import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Batch Operations with Commons Helpers (Python) Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Provides examples of using helper functions for common batch operations, specifically for alerts and investigations searches. It includes automatic pagination and processing of batched responses. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.commons.alerts.search import alerts_search from taegis_sdk_python.commons.investigations.search import investigations_search service = GraphQLService() # Alerts batch search with automatic pagination # Note: The actual return type of alerts_search needs to be known to iterate correctly. # Assuming it returns an iterable of responses, where each response has an 'alerts' attribute with a 'list'. # Mocking the return for demonstration. class MockAlertList: def __init__(self, alerts): self.alerts = alerts class MockAlert: def __init__(self, title): self.metadata = MockAlert.Metadata(title=title) class Metadata: def __init__(self, title): self.title = title class MockAlertResponse: def __init__(self, alerts_list): self.alerts = MockAlertList(alerts=alerts_list) # Mocking the alerts_search function def mock_alerts_search(*args, **kwargs): # Simulate returning paginated results mock_data = [ MockAlertResponse(alerts=[MockAlert(title='Fake Alert 1'), MockAlert(title='Fake Alert 2')]) ] return mock_data # Monkey patch the actual function for the example alerts_search = mock_alerts_search all_alerts = alerts_search( service=service, query="FROM alert WHERE severity >= 0.7 EARLIEST=-7d", limit=5000, caller_name="Weekly Security Report" ) total_alerts = sum(len(response.alerts.list) for response in all_alerts) # type: ignore print(f"Total alerts retrieved: {total_alerts}") # Process all alert responses for alert_response in all_alerts: for alert in alert_response.alerts.list: # type: ignore print(f"Alert: {alert.metadata.title}") # Investigations batch search # Mocking the return for investigations_search. class MockInvestigation: def __init__(self, description, priority, assignee_id): self.description = description self.priority = priority self.assignee_id = assignee_id class MockInvestigationResponse: def __init__(self, investigations, total_count): self.investigations = investigations self.total_count = total_count # Mocking the investigations_search function def mock_investigations_search(*args, **kwargs): # Simulate returning a list of investigations and a total count mock_investigations = [ MockInvestigation(description='Investigate suspicious login', priority='HIGH', assignee_id='user123'), MockInvestigation(description='Analyze potential data exfiltration', priority='MEDIUM', assignee_id='user456') ] return [MockInvestigationResponse(investigations=mock_investigations, total_count=2)] # Monkey patch the actual function for the example investigations_search = mock_investigations_search all_investigations = investigations_search( service=service, query="WHERE status='OPEN' EARLIEST=-30d", limit=1000 ) total_count = all_investigations[0].total_count if all_investigations else 0 print(f"Total investigations: {total_count}") for inv_response in all_investigations: for investigation in inv_response.investigations: print(f"Investigation: {investigation.description}") print(f" Priority: {investigation.priority}") print(f" Assignee: {investigation.assignee_id}") ``` -------------------------------- ### Change Tenant Context with Taegis SDK Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md Demonstrates how to change the tenant context using the Taegis SDK's `GraphQLService` context manager. This example initializes the service and prepares for a call related to investigations, potentially specifying a different tenant ID. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.investigations.types import InvestigationsV2Arguments service = GraphQLService() # Placeholder for actual tenant context change logic if needed, e.g.: # with service(tenant_id="new_tenant_id"): # results = service.investigations.query.investigations_v2(...) ``` -------------------------------- ### Execute Custom GraphQL Queries Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt This section details how to run arbitrary GraphQL queries and mutations not directly exposed as SDK methods. It covers `alertsServiceSearch`, raw GraphQL string execution, and custom mutation examples. ```APIDOC ## Execute Custom GraphQL Queries Run arbitrary GraphQL queries not directly supported by the SDK methods. ### Method POST ### Endpoint `/graphql` (Implicitly handled by SDK) ### Parameters #### Request Body - **endpoint** (string) - Required - The specific GraphQL endpoint or operation name. - **variables** (object) - Optional - Variables to be passed with the query. - **output** (string) - Required - A GraphQL selection set defining the desired output fields. ### Request Example (alertsServiceSearch) ```python from taegis_sdk_python import GraphQLService service = GraphQLService() custom_result = service.alerts.execute_query( endpoint="alertsServiceSearch", variables={ "in": { "limit": 10, "offset": 0, "cql_query": "FROM alert WHERE severity >= 0.8 EARLIEST=-2h" } }, output=""" search_id status alerts { total_results list { id tenant_id metadata { title severity detector_name } entities { entities } } } " ``` -------------------------------- ### Search Investigations with Pagination (Python) Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Queries investigations with automatic pagination handling. This example demonstrates a manual loop to fetch all open investigations from the last 30 days, collecting them into a single list. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.investigations2.types import InvestigationsV2Arguments service = GraphQLService() # Manual query with pagination page = 1 per_page = 50 all_investigations = [] while True: result = service.investigations2.query.investigations_v2( service, InvestigationsV2Arguments( page=page, per_page=per_page, cql="WHERE status = 'OPEN' EARLIEST=-30d" ) ) all_investigations.extend(result.investigations) if len(result.investigations) < per_page: break page += 1 print(f"Total open investigations: {len(all_investigations)}") for investigation in all_investigations: print(f"ID: {investigation.id}") print(f"Description: {investigation.description}") print(f"Priority: {investigation.priority}") print(f"Created: {investigation.created_at}") ``` -------------------------------- ### Configure Proxy using Environment Variables (Python) Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/proxy.md This Python snippet demonstrates how to initialize the Taegis SDK's GraphQLService with proxy settings automatically detected from environment variables. It utilizes the `trust_env=True` flag, which pulls proxy configuration from standard environment variables like `HTTPS_PROXY`. The example shows querying current subject information. ```bash export HTTPS_PROXY=http://$USERNAME:$PASSWORD@your.proxy.domain:port ``` ```python from taegis_sdk_python import GraphQLService service = GraphQLService(trust_env=True) results = service.subjects.query.current_subject() print(results) ``` ```python from taegis_sdk_python import GraphQLService service = GraphQLService() with service(trust_env=True): results = service.subjects.query.current_subject() print(results) ``` -------------------------------- ### Query Events Using Subscriptions (Python) Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Retrieves event data from Taegis using WebSocket subscriptions. This example specifically queries for process events related to 'powershell.exe' within the last hour, with custom query options. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.events.types import EventQueryOptions service = GraphQLService() # Query process events with subscription options = EventQueryOptions( timestamp_ascending=True, page_size=100, max_rows=1000, skip_cache=True, aggregation_off=False ) results = service.events.subscription.event_query( query="FROM process WHERE process.name='powershell.exe' EARLIEST=-1h", options=options ) ``` -------------------------------- ### Handle Event Pagination using Python Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/querying_events.md This example demonstrates how to paginate through event query results using the Taegis SDK for Python. It includes a helper function `get_next_page` to extract the next page indicator from the results. The main logic iteratively fetches pages of events until no more pages are available, accumulating all results. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.events.types import EventQueryResults, EventQueryOptions from typing import List, Optional def get_next_page(events_results: List[EventQueryResults]) -> Optional[str]: """Retrieve events next page indicator.""" try: # the next page could be found in any of the result pages, # but we cannot guarantee which result it will be found in return next( iter({result.next for result in events_results if result.next is not None}) ) except StopIteration: return None service = GraphQLService() options = EventQueryOptions( timestamp_ascending=True, page_size=1000, max_rows=100000, skip_cache=True, aggregation_off=False, ) results = [] result = service.events.subscription.event_query("FROM process EARLIEST=-1d | head 10", options=options) results.extend(result) next_page = get_next_page(result) while next_page: result = service.events.subscription.event_page(next_page) results.extend(result) next_page = get_next_page(result) ``` -------------------------------- ### Explore Taegis SDK with Python Help Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md Demonstrates how to use Python's built-in `help()` function to explore the Taegis SDK. This allows developers to discover available services, queries, mutations, subscriptions, and input types directly within their Python environment. Requires the 'taegis-sdk-python' library. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.alerts.types import SearchRequestInput service = GraphQLService() # Find available services (Service Endpoints) help(service) # Find available service queries (or mutations or subscriptions) help(service.alerts.query) help(service.alerts.mutation) help(service.alerts.subscription) # Reference documentation on specific endpoint help(service.alerts.query.alerts_service_search) # Help on an Input variable help(SearchRequestInput) ``` -------------------------------- ### GraphQLService Initialization Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Learn how to initialize the GraphQLService with different authentication methods and environment configurations. ```APIDOC ## Initialize GraphQLService with OAuth Authentication The primary entry point for accessing all Taegis services with automatic OAuth2 authentication. ### Method POST (Implicit via SDK initialization) ### Endpoint N/A (SDK Initialization) ### Parameters #### Environment Variables (for OAuth) - **CLIENT_ID** (string) - Required - Your OAuth client ID. - **CLIENT_SECRET** (string) - Required - Your OAuth client secret. #### Constructor Arguments - **environment** (string) - Optional - The Taegis environment (e.g., 'US1', 'US2', 'EU'). Defaults to 'US1'. - **tenant_id** (string) - Optional - The tenant ID for multi-tenant access. ### Request Example ```python import os from taegis_sdk_python import GraphQLService # Set OAuth credentials in environment os.environ['CLIENT_ID'] = 'your_client_id_here' os.environ['CLIENT_SECRET'] = 'your_client_secret_here' # Initialize service with default environment (charlie/US1) service = GraphQLService() # Initialize with specific region service_us2 = GraphQLService(environment="US2") service_eu = GraphQLService(environment="EU") # With tenant context for multi-tenant access service = GraphQLService( environment="US1", tenant_id="00000000-0000-0000-0000-000000000000" ) ``` ### Response N/A (SDK Initialization returns a service object) ### Response Example N/A ``` -------------------------------- ### Get Synchronous Schema using GraphQLService Source: https://github.com/secureworks/taegis-sdk-python/blob/main/README.md Retrieves the synchronous GraphQL schema from Taegis using the GraphQLService. This is useful for understanding the available API endpoints and types. ```python from taegis_sdk_python import GraphQLService service = GraphQLService() schema = service.core.get_sync_schema() ``` -------------------------------- ### Initialize GraphQLService Source: https://github.com/secureworks/taegis-sdk-python/blob/main/README.md Initializes the GraphQLService, which is the main entry point for interacting with the Taegis GraphQL APIs. This requires the taegis_sdk_python library. ```python from taegis_sdk_python import GraphQLService from pprint import pprint as pp service = GraphQLService() ``` -------------------------------- ### Inspect Arguments of a GraphQL Field Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/exploring_the_schema.md This snippet explains how to access and list the arguments accepted by a specific GraphQL query field, using 'alertsServiceSearch' as an example. It displays the argument names and their types. ```python schema.query_type.fields['alertsServiceSearch'].args ``` -------------------------------- ### Change the Environment Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md Shows how to instantiate the GraphQLService and use a service context manager to change the environment for API requests. ```APIDOC ## Change Environment ### Description This demonstrates how to configure the `GraphQLService` to operate within a specific environment, such as 'US2'. ### Method `POST` (implicitly through SDK client) ### Endpoint `/investigations2/query/investigations_v2` (example endpoint) ### Parameters #### Query Parameters - **environment** (string) - Required - The environment to use for the service context (e.g., 'US2'). - **page** (integer) - Required - The page number for pagination. - **per_page** (integer) - Required - The number of items per page. - **cql** (string) - Required - The Common Query Language string to filter investigations. ### Request Example ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.investigations.types import InvestigationsV2Arguments service = GraphQLService() # specify the output fields, and start the service context with service(environment="US2"): result = service.investigations2.query.investigations_v2( InvestigationsV2Arguments( page=1, per_page=3, cql="WHERE deleted_at IS NOT NULL EARLIEST=-90d" ) ) pp(result) ``` ### Response #### Success Response (200) - **result** (object) - The response containing the query results. #### Response Example ```json { "example": "result object" } ``` ``` -------------------------------- ### Use a Preexisting Access Token Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md Illustrates how to authenticate API requests by providing a preexisting access token when initializing the GraphQLService. ```APIDOC ## Use Preexisting Access Token ### Description This example shows how to authenticate API requests using a provided access token. ### Method `POST` (implicitly through SDK client) ### Endpoint `/investigations2/query/investigations_v2` (example endpoint) ### Parameters #### Query Parameters - **access_token** (string) - Required - The access token for authentication. - **page** (integer) - Required - The page number for pagination. - **per_page** (integer) - Required - The number of items per page. - **cql** (string) - Required - The Common Query Language string to filter investigations. ### Request Example ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.investigations.types import InvestigationsV2Arguments service = GraphQLService() # specify the output fields, and start the service context with service(access_token=""): result = service.investigations2.query.investigations_v2( InvestigationsV2Arguments( page=1, per_page=3, cql="WHERE deleted_at IS NOT NULL EARLIEST=-90d" ) ) pp(result) ``` ### Response #### Success Response (200) - **result** (object) - The response containing the query results. #### Response Example ```json { "example": "result object" } ``` ``` -------------------------------- ### Retrieve Specific Query Field Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/exploring_the_schema.md Shows how to get a specific GraphQL query field by its name, such as 'alertsServiceSearch'. It illustrates both direct dictionary-style access and the .get() method for retrieving field information. ```python schema.query_type.fields['alertsServiceSearch'] ``` ```python schema.query_type.fields.get('alertsServiceSearch') ``` -------------------------------- ### Initialize GraphQLService with OAuth Authentication (Python) Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Initializes the GraphQLService for Taegis XDR API interaction using OAuth2 authentication. Supports environment variables for credentials and allows specifying the Taegis environment and tenant ID. ```python import os from taegis_sdk_python import GraphQLService # Set OAuth credentials in environment os.environ['CLIENT_ID'] = 'your_client_id_here' os.environ['CLIENT_SECRET'] = 'your_client_secret_here' # Initialize service with default environment (charlie/US1) service = GraphQLService() # Initialize with specific region service_us2 = GraphQLService(environment="US2") service_eu = GraphQLService(environment="EU") # With tenant context for multi-tenant access service = GraphQLService( environment="US1", tenant_id="00000000-0000-0000-0000-000000000000" ) ``` -------------------------------- ### Print GraphQL Schema using Taegis SDK Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/exploring_the_schema.md Shows how to retrieve and print the GraphQL schema in a standard `.graphql` format. It imports necessary modules, initializes the service, fetches the schema, and then prints it using `print_schema`. ```python from taegis_sdk_python import GraphQLService from graphql.utilities import print_schema service = GraphQLService() schema = service.core.get_sync_schema() print(print_schema(schema)) ``` ```graphql input AbsoluteTimeRedQLQueryInput { query: String! referenceTime: Time! currentTime: Time! } type AccessPoint { tenantID: String! arn: String! alias: String! principal: [String!]! } ... ``` -------------------------------- ### Context Manager for Multi-Tenant Operations Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Illustrates using context managers to temporarily override service configuration, enabling operations across multiple tenants and environments. It shows how to query alerts from different tenants and cascade contexts for complex scenarios. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.alerts.types import SearchRequestInput service = GraphQLService() # Query alerts across multiple tenants tenant_ids = [ "tenant-001-uuid", "tenant-002-uuid", "tenant-003-uuid" ] tenant_alerts = {} for tenant_id in tenant_ids: # Temporarily override tenant context with service(tenant_id=tenant_id): result = service.alerts.query.alerts_service_search( service, SearchRequestInput( cql_query="FROM alert WHERE severity >= 0.8 EARLIEST=-7d", offset=0, limit=50 ) ) tenant_alerts[tenant_id] = result.alerts.list # Query different environments with service(environment="US2", tenant_id="eu-tenant-uuid"): eu_result = service.investigations2.query.investigations_v2( service, arguments={"page": 1, "per_page": 10, "cql": "WHERE status='OPEN'"} ) # Cascade contexts for complex scenarios with service(environment="US1", tenant_id="parent-tenant"): parent_data = service.assets.query.list_assets() with service(tenant_id="child-tenant-1"): # Inherits environment US1, overrides tenant child1_data = service.assets.query.list_assets() with service(environment="EU", tenant_id="child-tenant-2"): # Overrides both environment and tenant child2_data = service.assets.query.list_assets() ``` -------------------------------- ### Enable Taegis SDK Debug Logging (Python) Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/logging.md Sets the logging level specifically for the 'taegis_sdk_python' package to DEBUG. This focuses debug output on the SDK's operations without affecting other libraries. It requires the 'logging' module. ```python import logging logging.getLogger('taegis_sdk_python').setLevel(level=logging.DEBUG) ``` -------------------------------- ### Update Alert Status with GraphQL Mutations Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Demonstrates how to modify alert statuses and resolution using GraphQL mutations. It includes examples for updating a single alert and performing bulk updates on multiple alerts, specifying status and resolution reasons. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.alerts.types import ( UpdateAlertStatusInput, AlertResolutionStatus ) service = GraphQLService() # Update single alert status alert_id = "alert_12345" result = service.alerts.mutation.alerts_service_update_alert_status( service, UpdateAlertStatusInput( alert_ids=[alert_id], status=AlertResolutionStatus.TRUE_POSITIVE_MITIGATED, resolution_reason="Threat contained and system isolated" ) ) print(f"Updated {result.updated_count} alerts") print(f"Success: {result.success}") # Bulk update multiple alerts alert_ids = ["alert_001", "alert_002", "alert_003"] bulk_result = service.alerts.mutation.alerts_service_update_alert_status( service, UpdateAlertStatusInput( alert_ids=alert_ids, status=AlertResolutionStatus.FALSE_POSITIVE, resolution_reason="Confirmed benign activity" ) ) for update in bulk_result.results: print(f"Alert {update.alert_id}: {update.status}") ``` -------------------------------- ### Context Manager for Multi-Tenant Operations Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Demonstrates using context managers to temporarily override service configurations, allowing operations across different tenants and environments within a single script. ```APIDOC ## Service Context Management ### Description Temporarily override service configuration (like tenant ID or environment) using context managers. This is useful for performing operations across multiple tenants or environments within a single execution context. ### Method N/A (This is a programmatic feature using context managers) ### Endpoint N/A ### Usage Example (Querying Alerts Across Tenants) ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.alerts.types import SearchRequestInput service = GraphQLService() tenant_ids = [ "tenant-001-uuid", "tenant-002-uuid", "tenant-003-uuid" ] tenant_alerts = {} for tenant_id in tenant_ids: # Temporarily override tenant context with service(tenant_id=tenant_id): result = service.alerts.query.alerts_service_search( service, SearchRequestInput( cql_query="FROM alert WHERE severity >= 0.8 EARLIEST=-7d", offset=0, limit=50 ) ) tenant_alerts[tenant_id] = result.alerts.list # Query different environments with service(environment="US2", tenant_id="eu-tenant-uuid"): eu_result = service.investigations2.query.investigations_v2( service, arguments={"page": 1, "per_page": 10, "cql": "WHERE status='OPEN'"} ) # Cascade contexts for complex scenarios with service(environment="US1", tenant_id="parent-tenant"): parent_data = service.assets.query.list_assets() with service(tenant_id="child-tenant-1"): # Inherits environment US1, overrides tenant child1_data = service.assets.query.list_assets() with service(environment="EU", tenant_id="child-tenant-2"): # Overrides both environment and tenant child2_data = service.assets.query.list_assets() ``` ### Parameters When using the service as a context manager, you can pass keyword arguments to override the current configuration: - **environment** (string) - Optional - The environment to use (e.g., "US1", "EU"). - **tenant_id** (string) - Optional - The tenant ID to use. ### Response Responses will vary based on the specific query or mutation executed within the context manager. The context manager itself does not return a direct response but modifies the service's behavior for subsequent operations. ``` -------------------------------- ### Execute Custom Search with Minimal Output in Python Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Demonstrates executing a custom alert search query with a predefined minimal output structure for performance optimization. It specifies the fields to retrieve, handles the results, and prints specific alert information. Dependencies include the taegis_sdk_python library. ```python from taegis_sdk_python import GraphQLService, SearchRequestInput # Define minimal output for performance minimal_output = """ search_id alerts { total_results list { id status metadata { title severity confidence } } } """ # Assume 'service' is an authenticated GraphQLService instance # with service(output=minimal_output): # result = service.alerts.query.alerts_service_search( # service, # SearchRequestInput( # cql_query="FROM alert WHERE severity >= 0.6 EARLIEST=-1d", # offset=0, # limit=100 # ) # ) # Only specified fields will be populated # for alert in result.alerts.list: # print(f"{alert.id}: {alert.metadata.title} - {alert.metadata.severity}") # # Other fields will be None # print(f"Entities: {alert.entities}") # None ``` -------------------------------- ### Disable Specific Service Type Endpoint Deprecation Warnings (Python) Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/deprecation.md This example shows how to disable deprecation warnings for a specific service type, such as 'queries' within the 'investigations' service in the Taegis SDK for Python. This provides further granularity in managing warning visibility. ```python import logging # logging.getLogger("taegis_sdk_python.services..").setLevel(logging.ERROR) logging.getLogger("taegis_sdk_python.services.investigations.queries").setLevel(logging.ERROR) ``` -------------------------------- ### Configure Proxy and SSL Settings for GraphQLService (Python) Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Shows how to configure proxy settings, including basic, authenticated, and environment variable-based proxies. It also covers custom SSL contexts for self-signed certificates, disabling SSL verification, and setting execution timeouts. ```python from taegis_sdk_python import GraphQLService import aiohttp import ssl # Basic proxy configuration service = GraphQLService( proxy="http://proxy.company.com:8080" ) # Proxy with authentication service = GraphQLService( proxy="http://proxy.company.com:8080", proxy_auth=aiohttp.BasicAuth("username", "password"), proxy_headers={"Proxy-Custom-Header": "value"} ) # Use environment variables for proxy (respects HTTP_PROXY, HTTPS_PROXY) service = GraphQLService(trust_env=True) # Custom SSL context for self-signed certificates ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE service = GraphQLService(ssl=ssl_context) # Disable SSL verification (not recommended for production) service = GraphQLService(ssl=False) # Configure execution timeout (default 300 seconds) service = GraphQLService( execute_timeout=600, # 10 minutes max_message_size=10485760 # 10MB max for subscriptions ) # Use proxy for specific calls only service = GraphQLService() with service(proxy="http://special-proxy:8080"): # Placeholder for actual service call # result = service.alerts.query.alerts_service_search(service, search_input) pass ``` -------------------------------- ### Investigations V2 API Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md Demonstrates how to query investigations using the InvestigationsV2Arguments, with options for specifying tenant ID, page size, and CQL queries. ```APIDOC ## Investigations V2 Query ### Description This endpoint allows querying investigations with specific arguments such as tenant ID, pagination, and a custom CQL query. ### Method `POST` (implicitly through SDK client) ### Endpoint `/investigations2/query/investigations_v2` ### Parameters #### Query Parameters - **tenant_id** (string) - Required - The unique identifier for the tenant. - **page** (integer) - Required - The page number for pagination. - **per_page** (integer) - Required - The number of items per page. - **cql** (string) - Required - The Common Query Language string to filter investigations. ### Request Example ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.services.investigations.types import InvestigationsV2Arguments service = GraphQLService() # specify the output fields, and start the service context with service(tenant_id="00000"): result = service.investigations2.query.investigations_v2( InvestigationsV2Arguments( page=1, per_page=3, cql="WHERE deleted_at IS NOT NULL EARLIEST=-90d" ) ) pp(result) ``` ### Response #### Success Response (200) - **result** (object) - The response containing the query results. #### Response Example ```json { "example": "result object" } ``` ``` -------------------------------- ### Enable Specific Service Debug Logging (Python) Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/logging.md Allows enabling debug logging for a particular service within the Taegis SDK, such as 'alerts'. Replace 'alerts' with the desired service name. This provides granular control over log output. It requires the 'logging' module. ```python import logging logging.getLogger('taegis_sdk_python.services.alerts').setLevel(level=logging.DEBUG) ``` -------------------------------- ### Explore Schema and Build Queries Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Introspect the GraphQL schema to discover available operations and build dynamic queries. This section shows how to fetch the schema and list available queries. ```APIDOC ## Explore Schema and Build Queries Introspect GraphQL schema to discover available operations and build dynamic queries. ### Method N/A (Schema introspection and SDK usage) ### Endpoint N/A ### Parameters N/A ### Request Example (Fetching Schema and Listing Queries) ```python from taegis_sdk_python import GraphQLService service = GraphQLService() # Fetch the schema for a specific service schema = service.investigations2.get_sync_schema() # List all available queries print("Available Queries:") for query_name, query_field in schema.query_type.fields.items(): print(f" - {query_name}: {query_field.description}") # You can similarly explore mutation_type.fields and subscription_type.fields ``` ### Response Example (Listing Queries) ```text Available Queries: - investigationsStatusCount: - getInvestigation: Get a single investigation by ID. - listInvestigations: List investigations with filtering and pagination. ... ``` **Note:** The `build_output_string` and `build_output_string_from_introspection` functions can be used to programmatically construct query output strings based on the schema. ``` -------------------------------- ### Custom Output with Deprecated Fields Included (Python) Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/deprecation.md This example illustrates how to explicitly include deprecated fields, such as 'assignee', in the SDK's output by using a custom output string within the GraphQLService context manager. This allows access to fields that would normally be excluded. ```python from taegis_sdk_python import GraphQLService service = GraphQLService() with service(output='id tenant_id ... assignee { id name ... }'): results = service.investigations.query.all_investigations( page=1, per_page=3, ) print(results[0].assignee) ``` -------------------------------- ### Build Arbitrary GraphQL Query using alertsServiceSearch Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/exploring_the_schema.md Demonstrates how to construct and execute an arbitrary GraphQL query for searching alerts. It utilizes the `execute_query` method with specific endpoint, variables, and output fields. The output includes a sample response. ```python service.core.execute_query( endpoint="alertsServiceSearch", variables={ "in": { "cql_query": "FROM alert EARLIEST=-1d | head 10" } }, output=""" status alerts { list { id } } "") ``` ```json { "alertsServiceSearch": { "status": "OK", "alerts": { "list": [ { "id": "alert://priv:event-filter:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:event-filter:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:event-filter:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:event-filter:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:event-filter:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:email:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:email:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:event-filter-ql:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:event-filter:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, { "id": "alert://priv:event-filter:00000:0000000000000:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" } ] } } } ``` -------------------------------- ### Configure Subscription Max Message Size in Python SDK Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md This example demonstrates setting the maximum message size for subscriptions in the Taegis Python SDK. It shows how to set a default `max_message_size` for the `GraphQLService` and how to override it for individual subscription calls using a context manager. It also includes error handling for `ConnectionResetError`. ```python from taegis_sdk_python import GraphQLService service = GraphQLService(max_message_size=4194304) # sets default to 4MB with service(max_message_size=5242880): # sets specific API call to 5MB options = EventQueryOptions( timestamp_ascending=True, page_size=1000, max_rows=1000, skip_cache=True, aggregation_off=False, ) results = service.events.subscription.event_query("FROM process EARLIEST=-1d", options=options) try: results = service.events.subscription.event_query("FROM process EARLIEST=-1d", options=options) except ConnectionResetError as exc: # handle error ``` -------------------------------- ### Query Tenants using GraphQLService Source: https://github.com/secureworks/taegis-sdk-python/blob/main/README.md Shows how to query for tenants using the GraphQLService with specific parameters like max_results and page_num. This requires the TenantsQuery object. ```python from taegis_sdk_python.graphql.types import TenantsQuery result = service.tenants.query.tenants(tenants_query=TenantsQuery( max_results=10, page_num=1, )) pp(result) ``` -------------------------------- ### Query Taegis SDK by Region Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/getting_started.md Shows how to initialize the GraphQLService for different Taegis regions (US1, US2, US3, EU) and how to temporarily override the environment for individual API calls using a context manager. This is useful for targeting specific geographical deployments of Taegis. ```python service = GraphQLService(environment="US1") service = GraphQLService(environment="US2") service = GraphQLService(environment="US3") service = GraphQLService(environment="EU") # change the environment for an individual call with service(environment="US1"): results = service.users.query.current_tdruser() with service(environment="US2"): results = service.users.query.current_tdruser() ``` -------------------------------- ### Threaded API Calls with Taegis SDK Python Source: https://github.com/secureworks/taegis-sdk-python/blob/main/docs/threading.md Demonstrates how to perform threaded API calls using the Taegis SDK for Python. It shows the use of the `GraphQLService` context manager within a threaded function to manage API call configurations, including nested context managers for specific query fields. The example also illustrates setting up a `ThreadPoolExecutor` to submit and manage futures for concurrent execution across multiple tenants. ```python from taegis_sdk_python import GraphQLService import concurrent.futures service = GraphQLService(environment="charlie") def threaded_function(service: GraphQLService, tenant_id: str): results = [] try: # this will be constrained to just the the thread # this will apply to all API calls within the context manager with service(tenant_id=tenant_id): # these can be ANY API calls that you want to thread results.append(service.subjects.query.current_subject()) # the context manager can remain layered where you may want to request # fields specific to an API call with service(output="field fields { field field }"): results.append(service.clients.query.clients()) results.append(service.tenants.query.assignable_services()) except Exception as exc: print(exc) return [] return results tenants = get_tenants() # defined elsewhere future_results = {} # The GraphQLService optionally supports shared configuration between threads. # The below example supplies a user-managed token at the service level, # which will be applied to all threads within the service, # rather than requiring the user to supply the same token to each function. with service(access_token=my_managed_token): # Optional with concurrent.futures.ThreadPoolExecutor() as executor: futures = { executor.submit(threaded_function, service, tenant.id): tenant.id for tenant in tenants } print("Completing futures...") for future in concurrent.futures.as_completed(futures): # stitch results per tenant tenant = futures[future] future_results[tenant] = future.result() ``` -------------------------------- ### Configure Authentication and Manage Tokens in Python Source: https://context7.com/secureworks/taegis-sdk-python/llms.txt Illustrates how to configure custom authentication methods and manage access tokens for the Taegis SDK. It covers setting environment variable names for client IDs and secrets for different regions, using custom tokens, and enabling universal authentication for multi-region access. Dependencies include GraphQLService and configuration utilities from taegis_sdk_python. ```python from taegis_sdk_python import GraphQLService from taegis_sdk_python.config import write_to_config, get_config import os # Configure custom environment variable names write_to_config("US1", "CLIENT_ID", "PROD_TAEGIS_CLIENT_ID") write_to_config("US1", "CLIENT_SECRET", "PROD_TAEGIS_CLIENT_SECRET") write_to_config("US2", "CLIENT_ID", "DELTA_TAEGIS_CLIENT_ID") write_to_config("US2", "CLIENT_SECRET", "DELTA_TAEGIS_CLIENT_SECRET") # Now set environment variables with custom names os.environ['PROD_TAEGIS_CLIENT_ID'] = 'your_prod_client_id' os.environ['PROD_TAEGIS_CLIENT_SECRET'] = 'your_prod_client_secret' service = GraphQLService(environment="US1") # Use pre-existing access token existing_token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." # with service(access_token=existing_token): # result = service.users.query.current_tdruser() # print(f"Current user: {result.email}") # Universal authentication for multi-region access service = GraphQLService(use_universal_authentication=True) # Clear cached token to force re-authentication service.clear_access_token() # View cached configuration config = get_config() if config.has_section("US1"): print(f"Configured sections: {config.sections()}") ```