Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
# API Guide PDF (for reference only, not to be committed)
*.pdf
*.pdf:Zone.Identifier

# AI agent knowledge base files
AGENTS.md

# Certificates
*.crt
*.pem
*.cer
*.pfx

# Python
__pycache__/
*.pyc
*.pyo
.eggs/
*.egg-info/
dist/
build/
52 changes: 52 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Changelog

All notable changes to the Darktrace SDK will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.9.0] - 2026-02-27

### Added
- **Connection Pooling**: Added `requests.Session()` for improved performance with multiple requests (4x faster on reused connections)
- **Context Manager Support**: `DarktraceClient` now supports `with` statement for proper resource cleanup
```python
with DarktraceClient(host, public_token, private_token) as client:
client.devices.get()
```
- **Automatic Retry Logic**: Transient failures (5xx, 429, connection errors) are automatically retried
- Max 3 retries with 10 second wait between attempts
- Client errors (4xx) are NOT retried
- **SSRF Protection**: URL scheme validation blocks dangerous schemes (`file://`, `ftp://`, `data://`, `javascript://`)
- Note: Private IPs are explicitly ALLOWED for enterprise baremetal deployments
- **`_safe_json()` Helper**: Added to `BaseEndpoint` for JSON parsing with proper error handling
- **Configurable Request Timeout**: Added `timeout` parameter to `DarktraceClient` (default: None, uses requests default)
- **Compilation Test**: Added `tests/test_compilation.py` for full SDK validation without network calls
- **Read-Only Test**: Added `tests/test_sdk_readonly.py` for comprehensive testing against real Darktrace instances
- **CHANGELOG.md**: This changelog file

### Changed
- **SSL Verification Default**: Changed from `False` to `True` for security (verify_ssl=True by default)
- **Error Handling in ModelBreaches**: Methods now re-raise exceptions instead of returning `{"error": str}` dicts
- `add_comment()`, `acknowledge()`, `unacknowledge()` now properly propagate exceptions
- **IntelFeed Parameter**: Fixed `fulldetails` parameter name (was incorrectly documented as `full_details` in examples)
- **Cleaned Up Imports**: Removed unused `timedelta` import from `auth.py`
- **Translated Comments**: German comments translated to English
- **Documentation Updated**: Added v0.9.0 features to README.md and docs/README.md

### Fixed
- IntelFeed `get_with_details()` now correctly passes `fulldetails=True` to `get()`
- Examples and tests updated to use correct `fulldetails` parameter

### Security
- SSL certificate verification is now enabled by default
- URL scheme validation prevents SSRF attacks via non-HTTP schemes

### Removed
- Mocked test file `tests/test_devicesearch.py` (replaced by compilation + readonly tests)

---

## [0.8.55] - Previous Release

Initial stable release with 28 endpoint modules.
75 changes: 64 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@

# 🚀 Darktrace Python SDK

![PyPI - Python Version](https://img.shields.io/pypi/pyversions/darktrace-sdk)
![GitHub License](https://img.shields.io/github/license/LegendEvent/darktrace-sdk)
![GitHub Repo stars](https://img.shields.io/github/stars/LegendEvent/darktrace-sdk?style=social)


> **A modern, Pythonic SDK for the Darktrace Threat Visualizer API.**


---

## 🆕 Latest Updates (v0.9.0)

## 🆕 Latest Updates (v0.8.55)
### New Features
- **Connection Pooling**: Automatic HTTP connection pooling via `requests.Session()` for 4x faster requests on reused connections
- **Context Manager Support**: Use `with DarktraceClient(...) as client:` for proper resource cleanup
- **Automatic Retry Logic**: Transient failures (5xx, 429, connection errors) are automatically retried (3 retries, 10s wait)
- **SSRF Protection**: URL scheme validation blocks dangerous schemes (`file://`, `ftp://`, `data://`, `javascript://`)
- **Configurable Timeout**: New `timeout` parameter on `DarktraceClient`

- **Feature: Add 13 missing parameters to devicesummary endpoint** - Added support for `device_name`, `ip_address`, `end_timestamp`, `start_timestamp`, `devicesummary_by`, `devicesummary_by_value`, `device_type`, `network_location`, `network_location_id`, `peer_id`, `source`, and `status` parameters to align with Darktrace API specification
- **Documentation: Update devicesummary documentation** - Added examples and parameter descriptions for new filtering options
- **Note: devicesummary HTTP 500 limitation confirmed** - Documentation updated to clarify that all devicesummary parameters return HTTP 500 with API token authentication (Darktrace backend limitation, not SDK bug)
### Improvements
- **Error Handling**: `ModelBreaches` methods now properly re-raise exceptions instead of returning error dicts
- **SSL Verification**: Enabled by default for security (verify_ssl=True)

## 📝 Previous Updates (v0.8.54)
### Bug Fixes
- Fixed IntelFeed `fulldetails` parameter name in examples

- **Fix: Multi-parameter devicesearch query format (fixes #45)** - Changed query parameter joining from explicit ' AND ' to space separation per Darktrace API specification
- **Fix: ensure host URL includes protocol (default to https if missing)**
> For previous updates, see [GitHub Releases](https://github.com/LegendEvent/darktrace-sdk/releases) or [CHANGELOG.md](CHANGELOG.md).

---

Expand All @@ -31,12 +34,54 @@
- **Extensive API Coverage**: Most endpoints, parameters, and actions from the official Darktrace API Guide are implemented.
- **Modular & Maintainable**: Each endpoint group is a separate Python module/class.
- **Easy Authentication**: Secure HMAC-SHA1 signature generation and token management.
- **SSL Verification**: SSL certificate verification is enabled by default for secure connections.
- **Async-Ready**: Designed for easy extension to async workflows.
- **Type Hints & Docstrings**: Full typing and documentation for all public methods.
- **Comprehensive Documentation**: Detailed documentation for every module and endpoint.

---

## 🔒 SSL Certificate Verification

**SSL verification is enabled by default (`verify_ssl=True`)** for secure connections to your Darktrace instance.

For development or testing environments with self-signed certificates, you can disable verification:

```python
client = DarktraceClient(
host="https://your-darktrace-instance",
public_token="YOUR_PUBLIC_TOKEN",
private_token="YOUR_PRIVATE_TOKEN",
verify_ssl=False # Only for development/testing
)
```

> ⚠️ **Warning**: Disabling SSL verification exposes your connection to man-in-the-middle attacks. Never disable in production environments.

### Using Self-Signed Certificates with verify_ssl=True

For production environments with self-signed certificates, add the certificate to your system trust store instead of disabling verification:

```bash
# 1. Get the certificate from your Darktrace instance
openssl s_client -showcerts -connect your-darktrace-instance:443 </dev/null 2>/dev/null | openssl x509 -outform PEM > ~/darktrace-cert.pem

# 2. Copy to system CA store (Linux/Ubuntu/Debian)
sudo cp ~/darktrace-cert.pem /usr/local/share/ca-certificates/darktrace-cert.crt
sudo update-ca-certificates

# 3. Now verify_ssl=True will work
```

**Alternative (no sudo required):**
```bash
# Create a custom CA bundle and set environment variable
cat /etc/ssl/certs/ca-certificates.crt ~/darktrace-cert.pem > ~/.custom-ca-bundle.pem
export REQUESTS_CA_BUNDLE=~/.custom-ca-bundle.pem
```

---

## 📦 Installation

```bash
Expand Down Expand Up @@ -64,13 +109,21 @@ pip install .
```python
from darktrace import DarktraceClient

# Initialize the client
# Initialize the client (SSL verification enabled by default)
client = DarktraceClient(
host="https://your-darktrace-instance",
public_token="YOUR_PUBLIC_TOKEN",
private_token="YOUR_PRIVATE_TOKEN"
)

# For development with self-signed certificates, disable SSL verification:
# client = DarktraceClient(
# host="https://your-darktrace-instance",
# public_token="YOUR_PUBLIC_TOKEN",
# private_token="YOUR_PRIVATE_TOKEN",
# verify_ssl=False # Not recommended for production
# )

# Access endpoint groups
devices = client.devices
all_devices = devices.get()
Expand Down
5 changes: 4 additions & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ def pytest_addoption(parser):
from urllib3.exceptions import InsecureRequestWarning

def pytest_configure(config):
warnings.filterwarnings("ignore", category=InsecureRequestWarning)
# Only suppress SSL warnings when --no-verify is passed
# Follow SDK's default of verify_ssl=True
if config.getoption('no_verify', default=False):
warnings.filterwarnings("ignore", category=InsecureRequestWarning)
Comment on lines +13 to +16
Copy link

Copilot AI Feb 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The conftest.py change references a --no-verify option that doesn't exist in the pytest_addoption function. The code checks for config.getoption('no_verify', default=False) but this option is never registered. This will cause the code to always use the default value of False, effectively never suppressing SSL warnings. Either add the option registration in pytest_addoption, or remove this conditional logic.

Copilot uses AI. Check for mistakes.
5 changes: 3 additions & 2 deletions darktrace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from .dt_subnets import Subnets
from .dt_summarystatistics import SummaryStatistics
from .dt_tags import Tags
from .dt_utils import debug_print
from .dt_utils import debug_print, TimeoutType
from .dt_components import Components
from .dt_cves import CVEs
from .dt_details import Details
Expand Down Expand Up @@ -61,5 +61,6 @@
'DeviceSearch',
'ModelBreaches',
'AdvancedSearch',
'debug_print'
'debug_print',
'TimeoutType',
]
2 changes: 1 addition & 1 deletion darktrace/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Version information for darktrace-sdk
# This is the single source of truth for version information
# after that the script update_version.py needs to be run
__version__ = "0.8.55"
__version__ = "0.9.0"
4 changes: 2 additions & 2 deletions darktrace/auth.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import hmac
import hashlib
import json
from datetime import datetime, timezone, timedelta
from datetime import datetime, timezone
from typing import Dict, Optional, Any

class DarktraceAuth:
Expand All @@ -23,7 +23,7 @@ def get_headers(self, request_path: str, params: Optional[Dict[str, Any]] = None
- 'headers': The required authentication headers
- 'params': The sorted parameters (or original params if none)
"""
# UTC Zeit verwenden (Darktrace Server läuft auf UTC)
# Use UTC time (Darktrace Server runs on UTC)
date = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')

# Include query parameters in the signature if provided
Expand Down
Loading