Metadata-Version: 2.4
Name: osivault
Version: 0.2.1
Summary: One Smarter's shared security core: encryption at rest, tamper-evident audit logs, crypto signing, tokens, and MFA adapters.
Author-email: "One Smarter Inc. Engineering" <security@onesmarter.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/OneSmarterInc/OSIVault
Project-URL: Documentation, https://github.com/OneSmarterInc/OSIVault#readme
Project-URL: Repository, https://github.com/OneSmarterInc/OSIVault.git
Project-URL: Issues, https://github.com/OneSmarterInc/OSIVault/issues
Keywords: django,security,audit-log,encryption,hmac,crypto-agility,post-quantum,hipaa,tamper-evident
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: django>=4.2
Requires-Dist: cryptography>=42.0.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-django>=4.8.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: psycopg2-binary>=2.9.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Dynamic: license-file

# 🛡️ OSIVault: Enterprise Security Core

[![PyPI Version](https://img.shields.io/pypi/v/osivault.svg)](https://pypi.org/project/osivault/)
[![Python Versions](https://img.shields.io/pypi/pyversions/osivault.svg)](https://pypi.org/project/osivault/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**OSIVault** is One Smarter's shared security core: a single versioned Python package that every enterprise application imports for field-level encryption at rest, tamper-evident audit trail integrity, cryptographic signing and verification, token issuance, and strong multi-factor authentication adapters.

Extracted from proven primitives in Concorde and MeshKor alongside healthcare EDI security requirements, OSIVault provides a unified, **crypto-agile interface** designed to ensure that cryptographic algorithm upgrades occur centrally without requiring application code changes.

For full architectural details, governance rules, and monthly audit rituals, consult the [OSIVault Core Charter](docs/charter.md).

---

## 📦 Installation

```bash
pip install osivault
```

---

## 🏛️ Module Overview

| Module | Purpose | Underlying Cryptographic Primitive |
| :--- | :--- | :--- |
| **`osivault.fields`** | Field-level encryption at rest & search hashing | AES-256-GCM Envelope Encryption & HMAC-SHA-256 |
| **`osivault.audit`** | Keyed, chained, tamper-evident audit records | SHA-256 Merkle Hash Linkage & Signed Checkpoints |
| **`osivault.sign`** | Self-describing signatures over arbitrary bytes | RSA / HMAC / Post-Quantum Ready Envelopes |
| **`osivault.tokens`** | Session and service tokens with published JWKS | RS256 / JWT Tokens & RFC 7517 JWKS Metadata |
| **`osivault.auth`** | Multi-factor authentication adapters | TOTP (Replay Guarded) & WebAuthn / FIDO2 |
| **`osivault.watch`** | Compliance inventory & posture reporting | Machine-Readable Algorithm & CVE Inventory |

---

## 🚀 Quickstart & Code Examples

### 1. Field-Level Encryption & Blind Index Search Hashing (`osivault.fields`)

```python
from osivault.fields import encrypt, decrypt, SearchHash, EncryptedTextField, EncryptedJSONField
from django.db import models

# 1. Standalone AES-256-GCM Envelope Encryption (fresh 256-bit DEK per encrypt)
ciphertext = encrypt("Sensitive Data: 123-45-6789", context="tenant_101")
plaintext = decrypt(ciphertext, context="tenant_101")

# 2. Deterministic Blind Index Search Hashing for SQL queries
ssn_hash = SearchHash("123-45-6789")

# 3. Transparent Django Model Fields
class StudentRecord(models.Model):
    name = models.CharField(max_length=255)
    ssn_id = EncryptedTextField(blank=True, null=True)
    ssn_search_hash = models.CharField(max_length=64, db_index=True, blank=True, null=True)
    medical_notes = EncryptedTextField(blank=True, null=True)

    def save(self, *args, **kwargs):
        if self.ssn_id:
            self.ssn_search_hash = SearchHash(self.ssn_id)
        super().save(*args, **kwargs)
```

---

### 2. Tamper-Evident Audit Trail (`osivault.audit`)

```python
from django.db import models
from osivault.audit.models import OSIVaultAuditLog
from osivault.audit import append, verify_chain, rotate_key, checkpoint

# 1. Define Subclassed Audit Log Model
class SystemAuditLog(OSIVaultAuditLog):
    details = models.TextField(blank=True, default="")

# 2. Append Tamper-Evident Audit Record
log = append(
    model_class=SystemAuditLog,
    actor="admin_user",
    tenant="tenant_alpha",
    resource_type="STUDENT",
    resource_id="101",
    action="UPDATE",
    details="Updated student record"
)

# 3. Verify Entire Audit Chain Integrity
report = verify_chain(SystemAuditLog)
print("Is Audit Chain Intact?:", report.is_intact)

# 4. Rotate Encryption Master Key (k1 -> k2)
rotate_key(new_current_key="new-master-key-k2!", new_key_id="k2")

# 5. Take Periodic Table Snapshot Checkpoint
cp = checkpoint(SystemAuditLog)
print("Checkpoint Hash:", cp.checkpoint_hash)
```

---

### 3. Self-Describing Signatures (`osivault.sign`)

```python
from osivault.sign import sign, verify

# Produce self-describing signature envelope
envelope_str = sign(b"Payload Bytes", key=private_key, alg="RS256", key_id="key-1")

# Allowlist-first envelope verification
envelope = verify(envelope_str, public_key=public_key)
print(envelope.payload, envelope.sig_alg)
```

---

### 4. Session Tokens & JWKS Endpoints (`osivault.tokens`)

```python
from osivault.tokens import issue, verify, jwks_document

# Issue signed JWT token
token = issue({"sub": "user_101", "role": "admin"}, private_key=priv_key, alg="RS256")

# Verify token claims
claims = verify(token, public_key_or_jwks=pub_key)

# Generate RFC 7517 JWKS document for /.well-known/jwks.json endpoint
jwks = jwks_document(keys=[(pub_key, "key-1", "RS256")])
```

---

## 🛠️ Step-by-Step Integration Guide for Developers

1. **Add to `INSTALLED_APPS` in `settings.py`**:
   ```python
   INSTALLED_APPS = [
       ...
       'osivault.audit',
       'audit_trail.apps.AuditTrailConfig',
   ]

   OSIVAULT_SECRET_KEY = "your-32byte-master-encryption-key"
   ```

2. **Add Immutability Middleware**:
   ```python
   MIDDLEWARE = [
       ...
       'audit_trail.middleware.OSIVaultImmutabilityMiddleware',
   ]
   ```

3. **Run Migrations**:
   ```bash
   python manage.py makemigrations
   python manage.py migrate
   ```

---

## 🔒 Security Immutability & Threat Model

- **Data Theft Resistance**: All sensitive model fields are stored as AES-256-GCM scrambled ciphertext (`OSV1$AES-256-GCM$...`).
- **Audit Log Tamper Defense**: Any direct database alteration or row deletion breaks the HMAC SHA-256 Merkle chain. `verify_chain()` flags `is_intact: False` with the exact tampered row primary key.
- **ORM Immutability Guard**: Any attempt to modify or delete historical audit entries in Python code raises `osivault.audit.crypto.ImmutabilityError`.

---

## 📖 License

Copyright © 2026 One Smarter Inc. Engineering. Released under the MIT License.
