# AISentinel Offline Mode

The AISentinel standalone binary can operate entirely without persistent network
connectivity. **Offline mode is completely self-contained and does not sync data
to external AISentinel servers.** All data remains local to your infrastructure.

## Prerequisites

- Build the offline binary using `build-offline.sh` (see repository root for build instructions).
- Ensure write permissions for the offline data directory.
- Generate or obtain a Fernet encryption key for secure data storage.

## Optional Cloud Synchronization

**Offline mode can optionally synchronize select data with AISentinel cloud services.** This feature is completely opt-in and disabled by default to maintain data sovereignty.

### When to Enable Sync

Consider enabling synchronization if you want:
- **Rulepack updates**: Automatic downloads of new rulepacks from AISentinel (safe one-way sync)
- **Audit log aggregation**: Centralized analysis of audit patterns and trends (aggregated summaries only)
- **Performance monitoring**: System metrics and usage analytics (high-level statistics only)
- **Usage insights**: Anonymous usage patterns for capacity planning (no individual user data)

### Configuration

```bash
export OFFLINE_SYNC_ENABLED=true
export OFFLINE_SYNC_API_KEY="your-tenant-api-key"             # Required: your tenant API key
export OFFLINE_SYNC_INTERVAL=3600  # Check every hour
# Choose what to sync (all disabled by default)
export OFFLINE_SYNC_AUDIT_LOGS=true     # Aggregated audit summaries
export OFFLINE_SYNC_METRICS=true        # Performance statistics
export OFFLINE_SYNC_USAGE_STATS=true    # Usage patterns
export OFFLINE_SYNC_RULEPACK_UPDATES=true  # Safe - only downloads
```

**Important**: The sync endpoint is fixed to the AISentinel cloud API. Tenant isolation is handled by API key authentication - each tenant's data is automatically associated with their account.

### Sync API Endpoints

When sync is enabled, the system communicates with these AISentinel cloud endpoints:

- `POST /sync/audit-logs` - Receives aggregated audit log summaries
- `POST /sync/metrics` - Receives performance metrics data
- `POST /sync/usage` - Receives usage statistics
- `POST /sync/rulepacks/check` - Checks for available rulepack updates
- `GET /sync/rulepacks/download/{name}/{version}` - Downloads updated rulepacks
- `POST /api/sync/trigger` - Manually triggers synchronization (requires authentication)

### Manual Sync Trigger

You can manually trigger synchronization using the API:

```bash
curl -X POST http://localhost:8000/api/sync/trigger \
  -H "Authorization: Bearer your-api-key"
```

Response includes sync status and which data types were synchronized.

### Data Privacy and Security

**Privacy-Preserving Design:**
- **Audit Logs**: Only aggregated summaries are sent (event counts by severity/category, no individual log content)
- **Metrics**: System performance statistics only (CPU, memory, response times, error rates)
- **Usage Statistics**: High-level patterns only (peak usage hours, feature adoption rates, no user-specific data)
- **Anonymous Identification**: Tenant identification uses hashed encryption keys, not actual tenant names

**Security Features:**
- All sync traffic is encrypted end-to-end using HTTPS
- API keys are required and must be kept secure
- Network traffic can be restricted to specific endpoints
- All sync activities are logged locally for audit purposes
- Sync failures never crash the offline system

## Licensing and Pricing

Offline mode for the standalone binary requires a valid AISentinel license. Two yearly subscription plans are available:

- **Professional Plan**: $499/year - Includes core offline capabilities with up to 25,000 API calls per day, 25 users, 5,000 rule evaluations per day, and 100GB of data processing per day, plus enterprise support.
- **Enterprise Plan**: $999/year - Includes all Professional features plus unlimited API calls, unlimited users, unlimited rule evaluations, unlimited data processing, dedicated SLA, and whitelabel capabilities.

### Purchasing a License

1. **Access the Billing Portal**: Navigate to your AISentinel account dashboard and go to **Billing** \u2192 **Offline Packages**
2. **Select a Plan**: Choose between Professional ($499/year) or Enterprise ($999/year) based on your requirements
3. **Complete Purchase**: Click the subscribe button to process payment via Stripe checkout
4. **License Generation**: Upon successful payment, a license file is automatically generated and made available for download

### Downloading the Binary

After purchasing a license:

1. **License Download**: From the **Billing** \u2192 **Offline Licenses** section, click "Download" next to your active license
2. **Binary Access**: The license file contains download instructions and access credentials for the offline binary
3. **Build Process**: Use the included build scripts (`build-offline.sh`) to create your deployment-ready binary
4. **License Validation**: The binary validates your license on startup and requires the license file to be specified with `--license-file`

**Note**: Licenses are valid for 1 year and auto-renew annually. Renewed license files are automatically generated and emailed to you, with downloads available from the billing portal.

## Enabling Offline Mode

Set the following environment variables before starting the standalone binary:

```bash
export OFFLINE_STORAGE_ENABLED=true
export OFFLINE_DATA_DIR=/var/lib/aisentinel/offline
# optionally provide a pre-generated Fernet key
export OFFLINE_ENCRYPTION_KEY="<base64-key>"
# optional: maximum audit log file size in bytes (default: 10485760 = 10MB)
export OFFLINE_MAX_LOG_FILE_SIZE=10485760
# optional: number of audit log files to retain (default: 5)
export OFFLINE_LOG_RETENTION=5
# optional: metrics retention in hours (default: 168 = 1 week)
export OFFLINE_METRICS_RETENTION_HOURS=168
```

### Configuration Details

- **`OFFLINE_STORAGE_ENABLED`**: Enables offline storage functionality
- **`OFFLINE_DATA_DIR`**: Directory path for encrypted offline storage
- **`OFFLINE_ENCRYPTION_KEY`**: Base64-encoded Fernet key for data encryption (auto-generated if not provided)
- **`OFFLINE_MAX_LOG_FILE_SIZE`**: Maximum size of individual audit log files before rotation
- **`OFFLINE_LOG_RETENTION`**: Number of historical audit log files to keep
- **`OFFLINE_METRICS_RETENTION_HOURS`**: How long to retain performance metrics data

On start-up the standalone binary initialises dedicated encrypted storage locations for
rulepacks, audit logs, configuration schemas, and metrics.

## Running the Binary

After setting the environment variables, start the binary with:

```bash
./aisentinel-offline
```

For additional options, use:

```bash
./aisentinel-offline --help
```

If using a license file, specify it with:

```bash
./aisentinel-offline --license-file /path/to/license.json
```

The binary will run in the foreground. For production use, consider running it as a background service or within a container.

## Using the Binary for AISentinel Operations

Once the binary is running, it exposes a REST API on `http://localhost:8000` (default port; configurable via environment variables) for performing AISentinel safety auditing operations. All requests require authentication using an API key in the `Authorization` header: `Authorization: Bearer your-api-key`.

### Core Operations

#### Preflight Safety Checks

The primary operation is performing preflight checks on proposed AI agent tool executions to ensure safety and compliance.

**Endpoint:** `POST /api/v1/preflight`

**Description:** Validates a tool action against loaded rulepacks, invariants, and optional local risk assessment. Returns allow/block status with reasons and remediations.

**Request Body Example:**

```json
{
  "tool_name": "python_exec",
  "tool_args": {
    "code": "import os; os.system('rm -rf /')"
  },
  "context": "User attempting to execute potentially dangerous code",
  "metadata": {
    "user_id": "user123",
    "session_id": "sess456"
  }
}
```

**Response Example (Allowed):**

```json
{
  "allowed": true,
  "requires_approval": false,
  "reasons": ["Action passes all safety checks"],
  "alternatives": []
}
```

**Response Example (Blocked):**

```json
{
  "allowed": false,
  "requires_approval": true,
  "reasons": ["Blocked by code_exec_sandbox rule: System commands not allowed"],
  "alternatives": [
    {
      "tool_name": "safe_exec",
      "tool_args": {"command": "echo hello"},
      "context": "Safer alternative for execution"
    }
  ]
}
```

**Notes:**
- In offline mode, LLM-based risk assessments are disabled; only rule-based and invariant checks apply.
- Invariants like `execution_token_required` may block side-effecting tools unless an `execution_approval_token` is provided.

#### Managing Rulepacks

**List Available Rulepacks:** `GET /api/v1/rulepacks`

Returns a list of loaded rulepacks (system and custom).

**Upload Custom Rulepack:** `POST /api/v1/rulepacks`

Upload a YAML rulepack file to extend safety policies.

**Request Body:** Multipart form with `rulepack` file.

**Get Rulepack Details:** `GET /api/v1/rulepacks/{name}`

Retrieve details of a specific rulepack.

#### Audit Logging and Activity

**Get Audit Logs:** `GET /api/v1/auditing/logs`

Retrieve recent audit log entries. Supports query parameters for filtering by time, severity, etc.

**Example:** `GET /api/v1/auditing/logs?severity=high&limit=50`

**Get Activity Summary:** `GET /api/v1/activity/summary`

Get aggregated activity statistics.

#### Metrics and Usage

**Get System Metrics:** `GET /api/v1/usage/metrics`

Retrieve performance metrics like latency, throughput, and error rates.

**Get Usage Statistics:** `GET /api/v1/usage/stats`

Get usage patterns and API call counts.

#### API Keys and Administration

**List API Keys:** `GET /api/v1/api_keys`

**Create API Key:** `POST /api/v1/api_keys`

**Revoke API Key:** `DELETE /api/v1/api_keys/{key_id}`

#### Billing and Licensing (Offline Mode)

In offline mode, billing endpoints are limited. Check license status:

**Get License Info:** `GET /api/v1/billing/license`

Returns license details and usage against limits.

### Example Workflow

1. **Start the Binary:** `./aisentinel-offline --license-file license.json`

2. **Check Status:** Verify API is responding: `curl http://localhost:8000/api/v1/rulepacks`

3. **Perform Preflight Check:**

   ```bash
   curl -X POST http://localhost:8000/api/v1/preflight \
     -H "Authorization: Bearer your-api-key" \
     -H "Content-Type: application/json" \
     -d '{
       "tool_name": "web_search",
       "tool_args": {"query": "safe topic"},
       "context": "Research query"
     }'
   ```

4. **Review Logs:** `curl http://localhost:8000/api/v1/auditing/logs`

5. **Monitor Metrics:** `curl http://localhost:8000/api/v1/usage/metrics`

### Offline-Specific Considerations

- **No Cloud Dependencies:** All operations are performed locally; no external API calls for core functionality.
- **Data Sovereignty:** Audit logs and metrics remain local unless sync is enabled.
- **Limited Features:** Advanced features like LLM risk assessment require cloud connectivity and are disabled in offline mode.
- **Storage Limits:** Monitor disk usage for logs and metrics as per configured retention policies.

For full API documentation, refer to the online AISentinel API docs or use `./aisentinel-offline --help` for CLI options.

## Components

### Offline Rulepacks

Rulepacks are stored locally in encrypted form and support JSON or YAML. The
`OfflineRulepackManager` verifies checksums, maintains version metadata, and
mirrors bundled rulepacks for immediate offline use. Temporary decrypted copies
are created on demand to preserve compatibility with existing loading paths.

### Offline Audit Logging

`OfflineAuditLogger` writes append-only encrypted audit logs with automatic
rotation and compression. Logs remain searchable offline using structured filters
and are retained locally according to your configured retention policies.

### Configuration Validation

The `OfflineConfigurationValidator` validates deployment configurations against
locally stored encrypted JSON schemas and includes helpers for template
management and migration compatibility checks.

### Local Data Management

The offline system manages local data consistency and integrity. All data
operations are performed locally with encrypted storage ensuring data
sovereignty and security.

### Offline Metrics

The `OfflineMetricsStore` collects latency, throughput, and error metrics in an
encrypted time-series file, supports aggregation for alerting, and provides
local analysis capabilities.

## Verifying Offline Operation

Once the binary is running, verify offline mode is active by checking:

1. **Log Output**: The binary should log initialization messages for offline storage components.
2. **Data Directory**: Confirm encrypted files are created in `$OFFLINE_DATA_DIR` (e.g., `rulepacks.enc`, `audit_logs.enc`).
3. **Sync Service** (if enabled): Check for "Cloud synchronization enabled for: [enabled_sources]" in logs.
4. **Metrics Access**: Query metrics via the binary's API endpoints (if available) or inspect the metrics file directly.
5. **Network Isolation**: Disconnect network connectivity and ensure the binary continues processing requests without errors.

Example log excerpt indicating successful offline initialization:

```
INFO: Offline storage initialized at /var/lib/aisentinel/offline
INFO: Rulepacks loaded from encrypted storage
INFO: Audit logging enabled in offline mode
INFO: Cloud synchronization enabled for: rulepacks, audit_logs, metrics
INFO: Cloud sync monitoring started - data may be transmitted to AISentinel
```

## Testing Offline Mode

`pytest tests/test_offline_capabilities.py`

These tests cover rulepack bootstrapping, audit logging, configuration validation, metrics aggregation, and the synchronization manager.

### Testing Sync Features

To test synchronization features:

```bash
# Test sync service initialization
pytest tests/ -k "sync" -v

# Test with sync enabled (set OFFLINE_SYNC_ENABLED=true and OFFLINE_SYNC_RULEPACK_UPDATES=true)
pytest tests/test_offline_capabilities.py::test_sync_service -v

# Manual sync testing
curl -X POST http://localhost:8000/api/sync/trigger
```

## Troubleshooting

### Common Issues

- **Permission Denied**: Ensure the user running the binary has write access to `$OFFLINE_DATA_DIR`. Create the directory if it doesn't exist: `mkdir -p /var/lib/aisentinel/offline && chmod 755 /var/lib/aisentinel/offline`.
- **Invalid Encryption Key**: If providing `OFFLINE_ENCRYPTION_KEY`, ensure it's a valid base64-encoded Fernet key (32 bytes). Auto-generated keys are recommended for new setups.
- **Storage Full**: Monitor disk space in the data directory. Adjust `OFFLINE_MAX_LOG_FILE_SIZE` and `OFFLINE_LOG_RETENTION` to manage storage usage.
- **Binary Won't Start**: Run `./aisentinel-offline --help` to verify the binary is executable. Check for missing dependencies or corrupted builds.
- **Sync Connection Failed**: Verify `OFFLINE_SYNC_API_KEY` is correct. Check network connectivity and firewall rules. Ensure the endpoint supports the required sync API endpoints.
- **Sync Not Working**: Ensure at least one `OFFLINE_SYNC_*` option is set to `true`. Check logs for "No sync data types enabled" messages. Verify that `OFFLINE_SYNC_API_KEY` is configured.

### Debugging Steps

1. Enable verbose logging by setting `LOG_LEVEL=DEBUG` before starting.
2. Inspect encrypted files using decryption tools if needed (requires the Fernet key).
3. Review system logs for OS-level errors (e.g., SELinux restrictions on file access).
4. Test with minimal configuration: unset optional variables and use defaults.

## Limitations

- Offline mode operates completely independently by default
- Optional cloud synchronization is fully implemented but disabled by default for data sovereignty
- All data processing and storage happens locally when sync is disabled
- Offline data is secured using Fernet symmetric encryption; manage keys with your organization's secret rotation policies
- Sync only occurs when network connectivity is available and explicitly enabled
```