Metadata-Version: 2.4
Name: hfortix-fortios
Version: 0.5.2
Summary: FortiOS SDK - Part of HFortix
Author-email: "Herman W. Jacobsen" <herman@wjacobsen.fo>
License: Proprietary
Project-URL: Homepage, https://github.com/hermanwjacobsen/hfortix
Project-URL: Repository, https://github.com/hermanwjacobsen/hfortix
Keywords: fortinet,fortigate,fortios,firewall,api,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: hfortix-core>=0.5.2

# HFortix FortiOS

Python SDK for FortiGate/FortiOS API - Complete, type-safe, production-ready.

[![PyPI version](https://badge.fury.io/py/hfortix-fortios.svg)](https://pypi.org/project/hfortix-fortios/)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)

> **⚠️ BETA STATUS - Version 0.5.0-beta (January 4, 2026)**
>
> **Breaking Changes**: v0.5.0 removes convenience wrappers. Use direct API access via `fgt.api.*`
> **Status**: Production-ready but in beta until v1.0 with comprehensive unit tests.

**Version:** 0.5.0-beta
**Status:** Beta (100% auto-generated, production-ready, pending comprehensive unit tests for v1.0)

## Overview

Complete Python client for FortiOS 7.6.5 REST API with 100% endpoint coverage (1,219 endpoints), full type safety, and enterprise features. All code is auto-generated from FortiOS API schemas.

## Installation

```bash
pip install hfortix-fortios
```

This automatically installs `hfortix-core` as a dependency.

**For everything (includes future products):**
```bash
pip install hfortix[all]
```

## Quick Start

```python
from hfortix_fortios import FortiOS

# Connect to FortiGate
fgt = FortiOS(
    host="192.168.1.99",
    token="your-api-token",
    verify=False
)

# Get system status
status = fgt.monitor.system.status()
print(f"Hostname: {status['hostname']}")
print(f"Version: {status['version']}")

# Manage firewall addresses
fgt.api.cmdb.firewall.address.create(
    name="web-server",
    subnet="192.168.1.100 255.255.255.255"
)

# Use convenience wrappers (v0.3.39+)
fgt.firewall.service_custom.create(
    name="HTTPS-8443",
    tcp_portrange="8443",
    protocol="TCP/UDP/SCTP"
)
```

## API Coverage

**FortiOS 7.6.5 - 100% Coverage (1,219 Endpoints):**

- **CMDB API**: 886 endpoints - Full configuration management (firewall, system, VPN, routing, etc.)
- **Monitor API**: 295 endpoints - Real-time monitoring (sessions, stats, resources, etc.)
- **Log API**: 38 endpoints - Log queries (disk, memory, FortiAnalyzer, FortiCloud, search)

All endpoints are **100% auto-generated** with:
- Complete `.pyi` type stub files
- Schema-based parameter validation
- Auto-generated basic tests
- Comprehensive error handling

## Key Features

### 🎯 Complete API Coverage

Access every FortiOS endpoint with clean, Pythonic syntax:

```python
# CMDB (Configuration)
fgt.api.cmdb.firewall.policy.get()
fgt.api.cmdb.system.interface.get(name="port1")
fgt.api.cmdb.router.static.create(...)

# Monitor (Real-time data)
sessions = fgt.api.monitor.firewall.session.get()
resources = fgt.api.monitor.system.resource.usage.get()

# Log (Query logs)
vpn_logs = fgt.api.log.disk.event.vpn.get(rows=50)
traffic = fgt.api.log.memory.traffic.forward.get(rows=100)
```

### 🎨 Direct API Access

All 1,219 endpoints are accessed directly - no wrappers needed:

```python
# Service Management
fgt.firewall.service_custom.create(
    name="custom-app",
    tcp_portrange="8080-8090",
    comment="My application"
)

# Schedules
fgt.firewall.schedule_recurring.create(
    name="business-hours",
    day=["monday", "tuesday", "wednesday", "thursday", "friday"],
    start="08:00",
    end="17:00"
)

# Traffic Shaping
fgt.firewall.traffic_shaper.create(
    name="critical-apps",
    guaranteed_bandwidth=50000,
    maximum_bandwidth=100000,
    bandwidth_unit="kbps"
)

# IP/MAC Binding
fgt.firewall.ipmacbinding_table.create(
    ip="10.0.1.100",
    mac="00:11:22:33:44:55",
    name="Server-01"
)
```

**Available Wrappers:**
- **Service Management**: `service_custom`, `service_category`, `service_group`
- **Schedules**: `schedule_onetime`, `schedule_recurring`, `schedule_group`
- **Traffic Shaping**: `traffic_shaper`, `shaper_per_ip`
- **IP/MAC Binding**: `ipmacbinding_table`, `ipmacbinding_setting`
- **SSH/SSL Proxy**: `ssh_host_key`, `ssh_local_ca`, `ssh_local_key`, `ssh_setting`, `ssl_setting` (⚠️ with API limitations)
- **Firewall Policies**: `policy` with 150+ parameters

**Note:** Some wrappers have FortiOS API limitations (e.g., SSH CA deletion requires CLI/GUI). See documentation for details.

### ⚡ Advanced Features

**Async/Await Support:**
```python
import asyncio

async def main():
    async with FortiOS(host="...", token="...", mode="async") as fgt:
        # All methods support await
        addresses = await fgt.api.cmdb.firewall.address.list()

        # Concurrent operations
        addr, pol, svc = await asyncio.gather(
            fgt.api.cmdb.firewall.address.list(),
            fgt.api.cmdb.firewall.policy.list(),
            fgt.api.cmdb.firewall.service.custom.list()
        )

asyncio.run(main())
```

**Error Handling:**
```python
from hfortix_core import (
    APIError,
    ResourceNotFoundError,
    DuplicateEntryError
)

try:
    fgt.api.cmdb.firewall.address.create(name="test", subnet="10.0.0.1/32")
except DuplicateEntryError:
    print("Address already exists")
except ResourceNotFoundError:
    print("Resource not found")
except APIError as e:
    print(f"API Error: {e.message} (code: {e.error_code})")
```

**Read-Only Mode & Operation Tracking:**
```python
# Safe testing - block all write operations
fgt = FortiOS(host="...", token="...", read_only=True)

# Audit logging - track all API calls
fgt = FortiOS(host="...", token="...", track_operations=True)
operations = fgt.get_operations()
```

**Performance Testing:**
```python
# Test your device and get optimal settings
results = fgt.api.utils.performance_test()
print(f"Recommended settings: {results['recommendations']}")
```

### 🔧 Enterprise Features

- **Audit Logging**: Built-in compliance logging with SIEM integration (SOC 2, HIPAA, PCI-DSS)
- **Observability**: Structured logging, distributed tracing with `trace_id`, user context tracking
- **HTTP/2 Support**: Connection multiplexing for better performance
- **Automatic Retry**: Handles transient failures (429, 500, 502, 503, 504) with exponential/linear/fibonacci backoff
- **Circuit Breaker**: Prevents cascade failures with automatic recovery
- **Request Tracking**: Correlation IDs for distributed tracing
- **Validation Framework**: 832 auto-generated validators

### 🔍 Debugging & Monitoring (v0.4.0)

**Quick Debug Mode:**
```python
# Enable debug logging with simple boolean
fgt = FortiOS(host="...", token="...", debug=True)
```

**Connection Pool Monitoring:**
```python
# Real-time connection statistics
stats = fgt.connection_stats
print(f"Active: {stats['active_requests']}/{stats['max_connections']}")
print(f"Total requests: {stats['total_requests']}")
print(f"Pool exhaustion: {stats['pool_exhaustion_count']}")
```

**Request Inspection:**
```python
# Debug slow or failed requests
result = fgt.api.cmdb.firewall.address.list()
info = fgt.last_request
print(f"Endpoint: {info['endpoint']}")
print(f"Response time: {info['response_time_ms']}ms")
print(f"Status: {info['status_code']}")
```

**Debug Session:**
```python
from hfortix_fortios import DebugSession

# Comprehensive session monitoring
with DebugSession(fgt) as session:
    # Make API calls
    fgt.api.cmdb.firewall.address.list()
    fgt.api.cmdb.firewall.policy.list()

    # Auto-prints summary on exit:
    # - Duration, total requests, success/failure counts
    # - Avg/min/max response times
    # - Connection pool deltas
```

**Performance Profiling:**
```python
from hfortix_fortios import debug_timer

# Time individual operations
with debug_timer("Fetch all addresses") as timing:
    result = fgt.api.cmdb.firewall.address.list()

print(f"Took {timing['duration_ms']:.1f}ms")
```

**Enhanced Logging:**
```python
from hfortix_fortios import configure_logging

# JSON logging for ELK/Splunk
configure_logging(
    level="INFO",
    format="json",
    include_trace=True,  # Add request_id to all logs
    output_file="/var/log/fortios.log"  # Log to file
)

# Text logging with colors for development
configure_logging(
    level="DEBUG",
    format="text",
    use_color=True
)
```

**Type Hints & IDE Support:**
```python
# Full type hints for better autocomplete
from hfortix_fortios import FortiOS
from hfortix_core import APIResponse, ListResponse

fgt: FortiOS = FortiOS(host="...", token="...")
response: APIResponse = fgt.api.cmdb.firewall.address.get(name="test")
```

See `docs/fortios/DEBUGGING.md` for complete debugging guide.
- **Type Safety**: Full type hints with IDE autocomplete
- **Structured Logging**: Machine-readable JSON logs for ELK/Splunk/CloudWatch

## Import Patterns

### Recommended (New)
```python
from hfortix_fortios import FortiOS
```

### Legacy (Still Supported)
```python
from hfortix import FortiOS
from hfortix.FortiOS import FortiOS
```

## API Structure

```python
# Configuration Management (CMDB)
fgt.api.cmdb.firewall.policy.*
fgt.api.cmdb.firewall.address.*
fgt.api.cmdb.system.interface.*
fgt.api.cmdb.router.static.*
fgt.api.cmdb.vpn.ipsec.*

# Monitoring
fgt.api.monitor.system.status()
fgt.api.monitor.firewall.session.*
fgt.api.monitor.system.resource.*

# Logging
fgt.api.log.disk.traffic.*
fgt.api.log.disk.event.*
fgt.api.log.disk.virus.*

# Convenience Wrappers
fgt.firewall.policy.*
fgt.firewall.service_custom.*
fgt.firewall.schedule_recurring.*
fgt.firewall.traffic_shaper.*
```

## Documentation

**Main Guides:**
- [Quick Start](https://github.com/hermanwjacobsen/hfortix/blob/main/QUICKSTART.md) - Getting started guide
- [Async Guide](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/ASYNC_GUIDE.md) - Async/await patterns
- [API Reference](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/ENDPOINT_METHODS.md) - Complete method reference

**Convenience Wrappers:**
- [Overview Guide](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/wrappers/CONVENIENCE_WRAPPERS.md) - All wrappers
- [Service Wrappers](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/wrappers/CONVENIENCE_WRAPPERS.md#service-management) - Service management
- [Schedule Wrappers](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/wrappers/SCHEDULE_WRAPPERS.md) - Schedule management
- [Shaper Wrappers](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/wrappers/SHAPER_WRAPPERS.md) - Traffic shaping

**Advanced Features:**
- [Validation Guide](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/VALIDATION_GUIDE.md) - Using validators
- [Filtering Guide](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/FILTERING_GUIDE.md) - FortiOS filtering
- [Performance Testing](https://github.com/hermanwjacobsen/hfortix/blob/main/docs/fortios/PERFORMANCE_TESTING.md) - Optimization

**Full Documentation:**
- [Complete Changelog](https://github.com/hermanwjacobsen/hfortix/blob/main/CHANGELOG.md) - Version history
- [Main Repository](https://github.com/hermanwjacobsen/hfortix) - Complete docs

## Requirements

- Python 3.10+
- FortiOS 7.0+ (tested with 7.6.5)
- hfortix-core >= 0.4.0-dev1

## Development Status

**Beta** - All APIs are functional and tested against live FortiGate devices. The package remains in beta status until version 1.0.0 with comprehensive unit test coverage.

**Current Test Coverage:**
- 226 test files (145 CMDB, 81 Monitor)
- 75%+ pass rate
- ~50% of endpoints have dedicated tests
- All implementations validated against FortiOS 7.6.5

## Examples

### Firewall Policies

```python
# Create policy
fgt.firewall.policy.create(
    name="Allow-Web",
    srcintf=["port1"],
    dstintf=["port2"],
    srcaddr=["all"],
    dstaddr=["web-servers"],
    action="accept",
    schedule="always",
    service=["HTTP", "HTTPS"],
    logtraffic="all"
)

# Check if exists
if fgt.firewall.policy.exists(policy_id=10):
    fgt.firewall.policy.update(policy_id=10, status="disable")
```

### Address Management

```python
# Create address
fgt.api.cmdb.firewall.address.create(
    name="web-server",
    subnet="192.168.1.100 255.255.255.255",
    comment="Production web server"
)

# Create address group
fgt.api.cmdb.firewall.addrgrp.create(
    name="internal-networks",
    member=["subnet1", "subnet2", "subnet3"],
    comment="All internal networks"
)
```

### VPN Configuration

```python
# Create IPsec Phase 1
fgt.api.cmdb.vpn.ipsec.phase1_interface.create(
    name="site-to-site",
    type="static",
    interface="wan1",
    ike_version=2,
    peertype="any",
    proposal="aes256-sha256",
    remote_gw="203.0.113.10"
)
```

## License

Proprietary - See LICENSE file

## Support

- 📖 [Documentation](https://github.com/hermanwjacobsen/hfortix)
- 🐛 [Report Issues](https://github.com/hermanwjacobsen/hfortix/issues)
- 💬 [Discussions](https://github.com/hermanwjacobsen/hfortix/discussions)

## Author

**Herman W. Jacobsen**
- Email: herman@wjacobsen.fo
- LinkedIn: [linkedin.com/in/hermanwjacobsen](https://www.linkedin.com/in/hermanwjacobsen/)
- GitHub: [@hermanwjacobsen](https://github.com/hermanwjacobsen)
