Metadata-Version: 2.4
Name: ocean-basket-protocol
Version: 4.0.0
Summary: Physics-inspired self-protecting security framework
Author-email: OBP Authors <obp@example.com>
License: PROPRIETARY
Project-URL: Homepage, https://github.com/ocean-basket-protocol/ocean-basket-protocol
Project-URL: Documentation, https://github.com/ocean-basket-protocol/ocean-basket-protocol#readme
Project-URL: Repository, https://github.com/ocean-basket-protocol/ocean-basket-protocol
Project-URL: Issues, https://github.com/ocean-basket-protocol/ocean-basket-protocol/issues
Keywords: security,protection,secrets,leak-detection,leakguard,honeypot,attribution,self-protection,runtime-protection,secret-scanning,secrets-management,vault-alternative,anti-patching,memory-protection,context-awareness,entropy-analysis,decoy,deception,traps,attribution,TPM,HSM,cryptography,secure-audit,self-healing,physics-inspired,viscosity,steam-burn
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3
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
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: rich>=13.0
Requires-Dist: matplotlib>=3.8
Requires-Dist: pyyaml>=6.0
Requires-Dist: cryptography>=42.0
Requires-Dist: tomli>=2.0
Requires-Dist: numpy>=1.24
Provides-Extra: ml
Requires-Dist: tensorflow>=2.15; extra == "ml"
Provides-Extra: rust
Requires-Dist: maturin>=1.0; extra == "rust"
Provides-Extra: geoip
Requires-Dist: geoip2>=4.7; extra == "geoip"
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == "redis"
Provides-Extra: vault
Requires-Dist: hvac>=1.1; extra == "vault"
Provides-Extra: aws
Requires-Dist: boto3>=1.34; extra == "aws"
Provides-Extra: full
Requires-Dist: geoip2>=4.7; extra == "full"
Requires-Dist: redis>=5.0; extra == "full"
Requires-Dist: hvac>=1.1; extra == "full"
Requires-Dist: boto3>=1.34; extra == "full"
Requires-Dist: tomli>=2.0; extra == "full"
Requires-Dist: numpy>=1.24; extra == "full"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-mock>=3.11.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.5.0; extra == "dev"
Dynamic: license-file

# 🌊 Ocean Basket Protocol (OBP)

**Physics-inspired self-protecting security framework.**

*You can't carry the ocean in a basket. The ocean protects itself.*

[![Rust](https://img.shields.io/badge/Rust-high--performance-brightgreen.svg)](bindings/rust/)
[![TypeScript](https://img.shields.io/badge/TypeScript-browser--ready-blue.svg)](bindings/typescript/)
[![Go](https://img.shields.io/badge/Go-server--side-orange.svg)](bindings/go/)
[![Python](https://img.shields.io/badge/Python-full--featured-yellow.svg)](obp/)
[![License](https://img.shields.io/badge/License-PROPRIETARY-red.svg)](LICENSE)

---

## Overview

Ocean Basket Protocol is a production-ready Python framework that implements physics-inspired protection mechanisms for sensitive operations. Using metaphors from fluid dynamics and thermodynamics, OBP provides layered security through:

- **Viscosity Control**: Execution flow resistance based on trust level
- **Steam Burn**: Active computational resistance in untrusted contexts
- **LeakGuard**: Real-time secret detection in function arguments AND return values
- **Context Awareness**: Hardware/environment fingerprinting
- **Self-Protection**: OBP protects its own critical components
- **Anti-Patching**: Detects attempts to disable OBP protections
- **Memory Protection**: Warns about memory scraping attacks
- **Log Sanitization**: Automatic redaction of secrets in output
- **Trap Engine**: Turn attackers into targets with active attribution

## Features

- 🔒 **Multi-Mode Protection**: Graceful, Defensive, and Paranoid modes
- 🔍 **Secret Detection**: Pattern matching + entropy analysis for 30+ secret types
- 🎯 **Return Value Scanning**: Prevents secrets from leaking in API responses
- 🚫 **Anti-Patching**: Detects tampering with OBP's internal components
- 📝 **Log Sanitization**: Automatic redaction in print() and logging output
- 💾 **Memory Protection**: Warns about memory scraping and side-channel attacks
- 🎭 **Trap Engine**: Feed decoys, harvest attacker intel, real-time alerting
- 📊 **Audit Timeline**: Visual logging of all protection events
- 🐳 **Docker Ready**: Standard and air-gapped deployment options
- 🧪 **Fully Tested**: Comprehensive test suite with pytest
- ⚡ **Production Ready**: Singleton pattern, thread-safe, minimal dependencies

## New in v2.3

### Return Value Scanning
Prevents secrets from leaking in API responses, database queries, and function returns.

```python
from obp import obp, OBPConfig, ProtectionMode

config = OBPConfig(
    mode=ProtectionMode.DEFENSIVE,
    scan_return=True  # NEW: Scan return values
)

@obp.protect(config)
def get_api_key():
    return {"key": "sk_live_xxx..."}  # Automatically redacted!
```

### Anti-Patching Protection
Detects attempts to disable OBP by patching critical methods or replacing the singleton.

```python
from obp import AntiPatchProtection

# Check if OBP has been tampered with
violations = AntiPatchProtection.check_integrity()
if violations:
    print("OBP INTEGRITY COMPROMISED!")
```

### Memory Protection Awareness
Warns about potential memory-based attacks.

```python
from obp import MemoryProtection

warnings = MemoryProtection.check_environment()
for warning in warnings:
    print(f"SECURITY WARNING: {warning}")
```

### Log Sanitization
Automatic redaction of secrets in print() and logging output.

```python
from obp import enable_log_sanitization

enable_log_sanitization()

print(f"Token: ghp_abcdefgh...")  # Output: Token: [SECRET_REDACTED]
```

### Expanded Secret Patterns
Detects secrets from HuggingFace, OpenAI, Anthropic, and more:

```python
from obp import LeakGuard

leakguard = LeakGuard()
# HuggingFace tokens
leakguard.scan("hf_abcdefghijklmnopqrstuvwxyz12345678")
# OpenAI API keys
leakguard.scan("sk-abcdefghijklmnopqrstuvwxyz1234567890")
# Anthropic keys
leakguard.scan("sk-ant-api03-abcdefghijklmnopqrstuvwxyz")
# Database URLs with credentials
leakguard.scan("postgresql://user:password@host/db")
```

## Security Hardening (v2.0)

OBP now includes enterprise-grade security features:

### 🛡️ TPM Integration
Hardware-backed cryptographic signing for OBP artifacts.

```python
from obp import TPMManager, TPMConfig

config = TPMConfig(use_tpm=True, allow_software_fallback=True)
tpm = TPMManager(config)

# Generate and sign artifacts
key_id = tpm.generate_key("my_key")
signature = tpm.sign(key_id, b"critical_data")
```

### 🎭 Active Honeypots
Active deception system that tracks and analyzes attackers.

```python
from obp import HoneypotManager, HoneypotType, HoneypotConfig

config = HoneypotConfig(enabled=True, track_attempts=True)
hp = HoneypotManager(config)

# Create decoy API keys
decoy_id = hp.create_decoy("Production API Key", HoneypotType.API)

# When attacker accesses it
value = hp.get_decoy(decoy_id, attacker_id="attacker_ip")

# Get attacker analysis
report = hp.get_attacker_report()
```

### 🔐 Secure Audit Logging
Tamper-evident, cryptographically-signed audit logs.

```python
from obp import SecureAuditLogger, SecureAuditConfig, LogLevel

config = SecureAuditConfig(
    log_dir="/var/log/obp",
    encrypt_logs=True,
    sign_entries=True
)
audit = SecureAuditLogger(config)

# Log security events
audit.log(
    event_type="LEAK_DETECTED",
    message="Secret detected in function call",
    level=LogLevel.SECURITY,
    security_event=True
)

# Verify integrity
result = audit.verify_integrity()
```

### 🔑 Session Hijacking Protection
Comprehensive session security with anomaly detection.

```python
from obp import SessionHijackingProtection, SessionFingerprint, SessionConfig

config = SessionConfig(
    session_timeout=1800,
    require_fresh_fingerprint=True,
    check_geo_velocity=True
)
session = SessionHijackingProtection(config)

# Create session
fingerprint = SessionFingerprint(
    user_agent="Browser/1.0",
    ip_address="192.168.1.100",
    platform="Linux"
)
token, refresh = session.create_session("user_123", fingerprint, "192.168.1.100")

# Validate - detects hijacking attempts
status, sess = session.validate_session(token, fingerprint, "192.168.1.100")
```

### 🎯 Trap Engine - Attribution & Deception (v2.2)

**Turn attackers into targets.** Trap Engine feeds convincing decoy data while silently harvesting attacker intelligence and generating court-admissible forensic evidence.

```python
from obp import trap_engine, configure_trap_engine, TrapLevel

# Configure with real-time alerting
configure_trap_engine(
    trap_level='active',
    slack_webhook='https://hooks.slack.com/services/XXX',
    log_dir='/var/log/obp/forensics'
)

# When attacker accesses "sensitive" data
decoy_data, evidence_ids = trap_engine.activate_trap(
    attacker_id='203.0.113.50',
    data_requested='api_keys',
    decoy_data='sk_live_fake_key_xxxxx'
)

# Attacker thinks they got real data ✅
# You get: IP, geo, ISP, user agent, fingerprints ✅
# Evidence logged for law enforcement ✅

# Generate full investigation report
report = trap_engine.generate_investigation_report(attacker_ip)
```

**What gets harvested:**
- IP address, geolocation, ISP, ASN
- Tor/VPN/Proxy detection
- Browser fingerprint
- User agent & headers
- All accessed endpoints
- Session timing & behavior

**Alert Channels:**
- Slack, Webhook, Email, Syslog, File

**Trap Levels:**
| Level | Behavior |
|-------|----------|
| PASSIVE | Monitor only |
| SUBTLE | Return decoys silently |
| ACTIVE | Harvest + alert (default) |
| AGGRESSIVE | Full attribution |

## Installation

```bash
# Standard installation
pip install -e .

# With development dependencies
pip install -e ".[dev]"

# With Rust support (for high-performance steam burn)
pip install -e ".[rust]"
```

## Quick Start

```python
from obp import obp, OBPConfig, ProtectionMode, render_timeline

# Configure protection
config = OBPConfig(
    viscosity=0.8,
    max_temperature=0.9,
    mode=ProtectionMode.DEFENSIVE,
    enable_leakguard=True
)

# Protect sensitive functions
@obp.protect(config)
def sensitive_trading_logic(api_key: str, amount: float):
    """This function is now protected by OBP."""
    return {"profit": amount * 1.15, "status": "executed"}

# Execute (LeakGuard will protect if API key is exposed)
result = sensitive_trading_logic("dummy_key_123", 1000.0)

# View audit timeline
render_timeline(obp.audit_log)
```

## Protection Modes

| Mode | On Secret Detected | On Untrusted Context |
|------|-------------------|---------------------|
| **GRACEFUL** | Returns decoy value | Applies viscosity delay |
| **DEFENSIVE** | Returns decoy value | Applies viscosity + steam burn |
| **PARANOID** | Raises exception | Applies viscosity + steam burn + reversion |

## LeakGuard Detection

LeakGuard automatically detects common secret patterns:

- GitHub tokens (`ghp_`, `github_pat_`)
- Stripe keys (`sk_live_`, `sk_test_`)
- AWS keys (`AKIA...`)
- Google API keys (`AIza...`)
- Private key headers
- JWT tokens
- High-entropy strings (configurable threshold)

```python
# LeakGuard in action
@obp.protect(OBPConfig(enable_leakguard=True))
def process_payment(card_number: str):
    # If "sk_live_" or high-entropy string detected...
    # OBP returns decoy instead of executing
    pass
```

## Self-Protection

OBP protects its own critical methods:

```python
# Critical methods are protected using the same framework
@obp.protect(OBPConfig(mode=ProtectionMode.DEFENSIVE, viscosity=0.6))
def _protected_generate_fingerprint():
    return obp._generate_context_fingerprint()
```

## Configuration

```python
from obp import OBPConfig, ProtectionMode, ReversionSpeed

config = OBPConfig(
    viscosity=0.75,           # 0.0 (free) -> 1.0 (slow)
    max_temperature=0.85,     # Steam burn intensity
    mode=ProtectionMode.DEFENSIVE,
    enable_leakguard=True,
    resonance_sensitivity=0.6,
    reversion_speed=ReversionSpeed.GRACEFUL,
    entropy_threshold=4.5,    # For high-entropy secret detection
    steam_burn_iterations=50_000
)
```

## Examples

### Basic Usage

```bash
python examples/basic.py
```

### Self-Protection Demo

```bash
python examples/self_protected.py
```

## Testing

```bash
# Run core tests
pytest tests/test_obp.py -v

# Run security hardening tests
pytest tests/test_security.py -v

# Run all tests with coverage
pytest tests/ --cov=obp --cov-report=html
```

## Docker Deployment

### Standard Deployment

```bash
docker build -f docker/Dockerfile -t obp:latest .
docker run obp:latest
```

### Air-Gapped Deployment

```bash
# Download dependencies on connected machine
pip download -r requirements.txt -d wheels/

# Build air-gapped image
docker build -f docker/airgapped.Dockerfile -t obp:airgapped .

# Run in isolated environment
docker run --network=none obp:airgapped
```

## Project Structure

```
ocean-basket-protocol/
├── pyproject.toml           # Package configuration (with maturin/Rust)
├── README.md                # This file
├── LICENSE                  # PROPRIETARY - All Rights Reserved
├── obp/                     # Python implementation
│   ├── __init__.py          # Package exports
│   ├── core.py              # OBP singleton & decorator
│   ├── config.py            # Configuration classes
│   ├── leakguard.py         # Secret detection
│   ├── exceptions.py        # Custom exceptions
│   ├── timeline.py          # Visual timeline renderer
│   ├── tpm.py               # TPM integration
│   ├── honeypot.py          # Active honeypots
│   ├── trap_engine.py       # 🎯 Attribution & Deception
│   ├── secure_audit.py      # Secure audit logging
│   ├── session.py           # Session hijacking protection
│   ├── rate_limiter.py      # Rate limiting
│   ├── secrets_manager.py   # Secrets manager integration
│   └── _rust_bridge.py      # Rust core bridge
├── bindings/                 # Multi-language bindings
│   ├── rust/                # Rust + PyO3 high-performance core
│   ├── typescript/          # TypeScript/JavaScript
│   └── go/                  # Go implementation
├── examples/                # Usage examples
│   ├── basic.py
│   └── self_protected.py
├── tests/                   # Test suite
│   ├── test_obp.py
│   └── test_security.py
├── docs/                    # Documentation
│   └── architecture.md
├── web_app.py              # 🌊 Live test UI
└── docker/                  # Docker configurations
    ├── Dockerfile
    └── airgapped.Dockerfile
```

## API Reference

### Core Classes

- `OBP`: Main singleton class
- `OBPConfig`: Configuration dataclass
- `ProtectionMode`: Enum (GRACEFUL, DEFENSIVE, PARANOID)
- `ReversionSpeed`: Enum (GRACEFUL, IMMEDIATE)

### Components

- `LeakGuard`: Secret detection engine
- `render_timeline()`: Visual timeline renderer
- `get_timeline_stats()`: Audit statistics

### Exceptions

- `OceanBasketError`: Base exception
- `LeakDetectedError`: Secret detected
- `ReversionError`: Reversion triggered

## Security Considerations

- Context fingerprinting is for runtime verification (use TPM for cryptographic signing)
- Decoy values are not active honeypots
- Audit logs should be secured in production
- Consider additional hardening for sensitive deployments

## Performance

Typical overhead per protected call:
- **GRACEFUL**: ~0.5ms baseline
- **DEFENSIVE**: ~5-50ms (depending on viscosity)
- **PARANOID**: ~5-50ms + potential exception

## Contributing

Contributions welcome! Please see CONTRIBUTING.md for guidelines.

## Competitive Analysis

OBP occupies a unique position as the **only runtime protection framework** with self-healing capabilities. See [docs/COMPETITIVE_ANALYSIS.md](docs/COMPETITIVE_ANALYSIS.md) for a detailed comparison with:

- **Vault Solutions**: HashiCorp Vault, AWS Secrets Manager, GCP Secret Manager, Azure Key Vault
- **Secret Scanners**: Gitleaks, TruffleHog, Secretlint
- **Secrets Injection**: Docker Secrets, envchain, Mozilla SOPS
- **Runtime Security**: Bandit, PyTanche, Python-dotenv Security

### Key Differentiators

| Feature | OBP | Vault | Scanners |
|---------|-----|-------|----------|
| Runtime Protection | ✅ | ❌ | ❌ |
| Self-Protection | ✅ | ❌ | ❌ |
| Return Value Scanning | ✅ | ❌ | ❌ |
| Zero Infrastructure | ✅ | ❌ | ✅ |
| Python-native | ✅ | Via SDK | Partial |

## Roadmap

See [docs/COMPETITIVE_ANALYSIS.md](docs/COMPETITIVE_ANALYSIS.md) for planned features including:
- ML-based anomaly detection
- HSM/TPM 2.0 integration
- Kubernetes operator
- SIEM connectors
- Quantum-resistant cryptography

## License

**PROPRIETARY - All Rights Reserved**

Copyright (c) 2024 Ocean Basket Protocol Authors

This software is proprietary and confidential. Unauthorized copying, distribution, or modification is strictly prohibited.

To obtain a commercial license, contact: licensing@oceanbasketprotocol.com

See [LICENSE](LICENSE) file for full terms.

---

*The ocean protects itself. 🐚🛡️🌊*
