Metadata-Version: 2.4
Name: secpod-saner-sdk
Version: 1.0.1
Summary: Official Python SDK for SecPod Saner APIs
Author: SecPod Technologies
License-Expression: LicenseRef-Proprietary
Project-URL: Documentation, https://apidocs-cvem.readme.io/docs/sdk-overview
Project-URL: Homepage, https://www.secpod.com
Keywords: saner,secpod,cybersecurity,vulnerability,api,sdk
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Operating System :: OS Independent
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.32.4
Provides-Extra: dev
Requires-Dist: ruff; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: types-requests; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: python-dotenv; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: PyYAML; extra == "dev"
Dynamic: license-file

# Saner Python SDK

**Official Python SDK for the SecPod Saner CVEM platform**, covering continuous vulnerability and exposure management, patching, compliance, and endpoint management.

[![Python](https://img.shields.io/badge/python-3.9%2B-blue)](https://pypi.org/project/secpod-saner-sdk/)
![License](https://img.shields.io/badge/license-Proprietary-lightgrey)
![Types](https://img.shields.io/badge/types-typed-brightgreen)

Every endpoint, parameter, and response shape is documented on the developer portal:

**📖 Full API reference: [apidocs.developer.secpod.com](https://apidocs.developer.secpod.com/docs/sdk-overview)**

---

## Table of contents

- [Introduction](#introduction)
- [Features](#features)
- [Installation](#installation)
- [Quickstart](#quickstart)
- [Configuration](#configuration)
- [Resources](#resources)
- [Error handling](#error-handling)
- [Retries](#retries)
- [Logging](#logging)
- [Thread safety](#thread-safety)
- [Support](#support)
- [License](#license)

## Introduction

[Saner CVEM](https://www.secpod.com/vulnerability-and-exposure-management) is SecPod's platform for continuous vulnerability and exposure management. It discovers the devices in your environment, finds their vulnerabilities, misconfigurations, and exposures, and fixes them through patching and remediation jobs, all from one console.

This SDK lets you do the same from Python. It wraps Saner's REST and RPC APIs in 225 methods across 20 resources, so you work with calls like `client.cvem.Device.getBasicSystemDetails(...)` instead of building HTTP requests by hand. The SDK handles authentication, checks every parameter before a request is sent, retries transient failures safely, and returns the parsed JSON response.

Typical uses:

- Pulling device inventory, vulnerability, and compliance data into a SIEM, CMDB, or reporting pipeline.
- Automating routine work such as scans, patch and remediation jobs, and group assignments.
- Managing organizations, accounts, users, and service provisioning across many tenants from one script.
- Building internal tools and integrations on top of Saner.

## Features

- **One SDK, two products**: `platform` (org/account/user management) and `cvem` (vulnerability, patching, compliance, endpoints), reachable through a universal client or two product-scoped ones.
- **Safe-by-default retries**: exponential backoff with jitter on transient failures and HTTP 429/5xx; writes are never blindly replayed, so a retry can't silently duplicate a remediation job.
- **Structured errors**: every exception carries `status_code`, `response_body`, `method`, `url`, and `attempts` instead of an opaque message string.
- **Declarative validation**: every parameter is checked against its documented shape before a request is ever made, so a bad call fails fast, locally, with no network round trip.
- **Secure logging**: optional JSONL request/response logs redact credentials by key name, cap response size, and are written owner-only (`0600`) on disk.
- **Typed**: ships `py.typed`; editors autocomplete every resource and method.

## Installation

```bash
pip install secpod-saner-sdk
```

Requires Python 3.9+. The only runtime dependency is `requests`.

## Quickstart

### 1. Set your credentials

You need an API key and the name of the account you want to work in, both available from the Saner console. The simplest setup is to export them as environment variables:

```bash
export SANER_API_KEY="<YOUR_API_KEY>"
export SANER_ACCOUNT_ID="<YOUR_ACCOUNT>"
export SANER_BASE_URL="https://saner.secpod.com"   # or your regional / on-prem host
```

### 2. Create a client and make your first call

```python
from saner import SanerClient

client = SanerClient()   # reads the SANER_* variables set above

orgs = client.platform.Organization.get()       # every organization
accounts = client.platform.Account.get()        # every account
print(orgs)
print(accounts)

client.close()
```

You can also pass the values directly, which always wins over the environment:

```python
client = SanerClient(
    api_key="<YOUR_API_KEY>",
    accountid="<YOUR_ACCOUNT>",
    base_url="https://saner.secpod.com",
)
```

The client owns pooled HTTP connections, so close it when you're done, or let a `with` block do it for you. The rest of the examples use the `with` form.

### 3. List the devices in an account

```python
with SanerClient() as client:
    result = client.cvem.Device.getBasicSystemDetails(accountname="<YOUR_ACCOUNT>")

    for host in result.get("hostDetails", []):
        print(host["name"], host["ipAddress"], host["osName"])
```

### 4. Look up one device

`Device.getInfo` finds a device you can already identify by `hostname`, `ip`, `mac`, `serialnumber`, or a tag filter. It does not list an account, so use `getBasicSystemDetails` above for that.

```python
with SanerClient() as client:
    device = client.cvem.Device.getInfo(hostname="web-server-01")
```

### 5. Check the response body

Methods return the server's response as-is. The Saner API often reports a failure inside a normal HTTP 200 response, so a call that returns without raising has not necessarily worked. For example, a misspelled account name in step 3 comes back as a `FAIL` result, and the loop there would print nothing:

```python
with SanerClient() as client:
    result = client.cvem.Device.getBasicSystemDetails(accountname="no-such-account")

for item in result.get("response", {}).get("results", {}).get("result", []):
    if item.get("status", "").upper() == "FAIL":
        print("Saner rejected the call:", item.get("reason"))
        # Saner rejected the call: Failed due to invalid account name or Id
```

The shape of a failure varies by endpoint. `Account.get`, for instance, answers an unknown name with `{"accounts": [{"status": "fail", ...}]}`. Each method's docstring and its page in the API reference show what it returns. An empty result is not a failure either: `Device.getInfo` for a host that does not exist returns `"totalEntries": 0` and an empty device list.

Transport and HTTP errors (bad key, rate limit, network failure) are raised as exceptions instead. See [Error handling](#error-handling).

### 6. Let validation catch mistakes early

Arguments are checked before anything is sent, so a malformed call fails immediately with a clear message:

```python
with SanerClient() as client:
    client.cvem.Device.getInfo(ip="999.1.1.1")
    # ValueError: ip must be valid IPv4 address; got '999.1.1.1'
```

Calling `Device.getInfo()` with no identifier at all is rejected the same way, with a message listing the parameters it needs.

### 7. Next steps

- Browse the [Resources](#resources) table to see what each product covers.
- Use `PlatformClient` or `CvemClient` if you only need one product and want shorter attribute paths.
- Look up any method's parameters and response shape in the [API reference](https://apidocs.developer.secpod.com/docs/sdk-overview), or in your editor, since every method has a full docstring.

## Configuration

`api_key`, `accountid`, `base_url`, and `verify_ssl` all fall back to environment variables when omitted, so `SanerClient()` works unmodified across dev, CI, and containers. Only the environment differs. An explicit argument always wins over the environment, which keeps the [multi-client pattern](#resources) (several clients, several accounts, one script) isolated even when the variables are set.

```python
# with SANER_API_KEY / SANER_ACCOUNT_ID set in the environment
client = SanerClient()
```

The SDK reads the process environment, not a `.env` file. If you keep credentials in `.env`, load it first (`pip install python-dotenv`):

```python
from dotenv import load_dotenv
from saner import SanerClient

load_dotenv()          # before the client is constructed
client = SanerClient()
```

| Argument | Default | Description |
| --- | --- | --- |
| `api_key` | *required*, or `SANER_API_KEY` | Saner API key, sent as the `Authorization` header. |
| `accountid` | *required*, or `SANER_ACCOUNT_ID` | Account the client operates against. |
| `base_url` | `SANER_BASE_URL`, else `https://saner.secpod.com` | Saner server URL. Use your regional or on-prem host. |
| `verify_ssl` | `SANER_VERIFY_SSL` (`True`/`False`), else `True` | Verify TLS certificates. Only disable against a lab server or an internal host with a self-signed cert. |
| `timeout` | `30` | Per-request timeout, in seconds. |
| `max_retries` | `3` | Retries after the first attempt. `0` disables retrying. |
| `retry_backoff` | `1.0` | Base for exponential backoff, in seconds. |
| `retry_on_write` | `False` | Also retry requests that may mutate server state. See [Retries](#retries). |
| `max_response_bytes` | `256 MB` | Largest response body accepted. `None` removes the cap. |
| `enable_logging` | `False` | Write a JSONL request/response log. |
| `log_dir` | `"logs"` | Directory for the JSONL log. |

## Resources

Resources are split into two products, each with its own client if you only need one of them:

| | Resources | Client |
| --- | --- | --- |
| **platform**: shared across every Saner product | `Organization`, `Account`, `User`, `Group`, `ServiceProvision`, `Report`, `MFA` | `from saner.platform import PlatformClient` → flat: `client.Organization` |
| **cvem**: vulnerability management, patching, compliance, endpoints | `Agent`, `Device`, `Configuration`, `CyberHygiene`, `Vulnerability`, `Compliance`, `Patch`, `RiskPrioritization`, `PostureAnomaly`, `AssetExposure`, `Endpoint`, `NetworkScanner`, `AD` | `from saner.cvem import CvemClient` → flat: `client.Patch` |

`SanerClient` (the universal client) nests both under `client.platform.*` / `client.cvem.*` instead. Prefer it when your process touches both products. Each client *instance* opens its own pair of pooled sessions, so creating a `PlatformClient` and a `CvemClient` side by side doubles connection overhead for no benefit over one `SanerClient`. Reach for `PlatformClient`/`CvemClient` only when you exclusively work within one product and want flatter attribute access.

Methods return the parsed JSON response as a `dict`. Endpoints that produce a file (`Report.getPdf`, `AD.downloadAgent`) return `bytes` instead:

```python
with SanerClient(api_key="...", accountid="...") as client:
    report = client.platform.Report.getPdf(accountid="MyAccount", reportname="Asset Report")
    if isinstance(report, bytes):
        with open("report.zip", "wb") as f:
            f.write(report)
```

## Error handling

Every SDK error derives from `SanerError` and carries structured context, so you can branch on it without parsing message strings. Response bodies attached to an exception are redacted the same way logs are, so a caught error is safe to forward to your own logging or APM stack.

```python
from saner import SanerClient, SanerAuthError, SanerRateLimitError, SanerError

with SanerClient() as client:
    try:
        client.cvem.Device.getInfo(ip="192.168.1.10")
    except SanerAuthError:
        ...                                  # 401 / 403: bad or expired key
    except SanerRateLimitError as e:
        print("retry after", e.retry_after)  # 429, exhausted retries
    except SanerError as e:
        print(e.status_code, e.method, e.url, e.attempts, e.response_body)
```

| Exception | Raised when |
| --- | --- |
| `SanerAuthError` | HTTP 401 / 403. |
| `SanerRateLimitError` | HTTP 429 after retries are exhausted. Exposes `retry_after`. |
| `SanerRequestError` | Network failure, SSL error, or a non-retryable HTTP error. |
| `SanerResponseError` | Server replied successfully but the body was not valid JSON, or the response exceeded `max_response_bytes`. |
| `SanerError` | Base class; catch this to handle everything. |

Invalid arguments raise plain `ValueError` / `TypeError` before any network call is made.

## Retries

The SDK retries HTTP 429 and 500/502/503/504, plus connection failures, using exponential backoff with jitter capped at 60s. A `Retry-After` header always takes precedence over the computed delay.

**Writes are not retried by default.** Replaying a request that already reached the server can duplicate it, creating the same remediation job twice, for example. So retries apply to read-only calls only. Two exceptions are always safe and always retried: HTTP 429 (the server refused to process the request) and connect timeouts (the request never arrived).

Set `retry_on_write=True` if your workload is idempotent and you'd rather have the retries.

## Logging

With `enable_logging=True` the SDK writes one JSON object per request to `<log_dir>/secpod-saner-sdk__<account>__<hash>.jsonl`, rotating weekly and keeping 8 backups. The log directory and files are created owner-only (`0700`/`0600`) wherever the OS supports it.

Credentials (`password`, `client_secret`, `token`, and any parameter name containing those or similar stems such as `proxypassword`, `bindPassword`, `refresh_token`) are replaced with `***REDACTED***`, and long values are truncated. Response bodies are **not** content-redacted, and in a CVEM product those contain asset inventories and CVE exposure data, so treat the log directory as sensitive regardless of the file permissions.

For application-level logging, the SDK also emits retry warnings through the standard `logging` module under the `saner.*` logger namespace.

## Thread safety

All three client classes (`SanerClient`, `PlatformClient`, `CvemClient`) are safe to share between threads. One client can serve several calls at the same time, and each call keeps its own retries and response:

```python
from concurrent.futures import ThreadPoolExecutor
from saner import SanerClient

with SanerClient() as client, ThreadPoolExecutor(max_workers=4) as pool:
    orgs = pool.submit(client.platform.Organization.get)
    users = pool.submit(client.platform.User.get)
    print(orgs.result(), users.result())
```

Calls that run side by side finish in about the time of the slowest one rather than the sum of all of them. See the [Concurrent Requests](https://apidocs.developer.secpod.com/docs/sdk-concurrent-requests) guide for a timing example, how many threads to use, and how closing a shared client behaves.

## Support

- API reference: <https://apidocs.developer.secpod.com/docs/sdk-installation>
- Support: <support@secpod.com>

## License

Proprietary. Use is governed by your SecPod license agreement. The full terms are in the `LICENSE` file included with the package.
