Metadata-Version: 2.4
Name: scswp
Version: 0.1.0
Summary: Secure Collaborative State Workspace Protocol — a stateful, continuously authenticated multi-client file workspace server and client.
Author-email: Sripad Hebbar <sripadkarthik@gmail.com>, Sharan Hiremani <sharanrhiremani@gmail.com>
Maintainer-email: Sripad Hebbar <sripadkarthik@gmail.com>, Sharan Hiremani <sharanrhiremani@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/sripadkarthik/scswp
Project-URL: Documentation, https://github.com/sripadkarthik/scswp#readme
Project-URL: Repository, https://github.com/sripadkarthik/scswp.git
Project-URL: Bug Tracker, https://github.com/sripadkarthik/scswp/issues
Project-URL: Changelog, https://github.com/sripadkarthik/scswp/blob/main/CHANGELOG.md
Project-URL: IETF Draft, https://github.com/sripadkarthik/scswp/blob/main/draft-hebbar-hiremani-scswp-secure-collaborative-workspace-00.txt
Project-URL: PyPI, https://pypi.org/project/scswp/
Keywords: scswp,secure workspace,collaborative protocol,continuous authentication,zero trust,ECDH,AES-GCM,AES-256-GCM,HKDF,HMAC,X.509,PKI,file server,websocket,fastapi,cryptography,key hierarchy,audit ledger,DNAC,session recovery,capability ACL,worker pool,ietf draft
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Telecommunications Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
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 :: Only
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Security
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: System :: Networking
Classifier: Topic :: System :: Distributed Computing
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Communications :: File Sharing
Classifier: Typing :: Typed
Classifier: Natural Language :: English
Classifier: Framework :: FastAPI
Classifier: Framework :: AsyncIO
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.111.0
Requires-Dist: uvicorn[standard]>=0.29.0
Requires-Dist: websockets>=12.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: sqlalchemy>=2.0.0
Requires-Dist: jinja2>=3.1.0
Requires-Dist: python-multipart>=0.0.9
Requires-Dist: PyJWT>=2.8.0
Requires-Dist: psutil>=5.9.0
Requires-Dist: bcrypt>=4.1.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: httpx>=0.27.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: isort>=5.13.0; extra == "dev"
Requires-Dist: mypy>=1.9.0; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Provides-Extra: build
Requires-Dist: pyinstaller>=6.6.0; extra == "build"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5.0; extra == "docs"
Requires-Dist: mkdocs-material>=9.5.0; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.24.0; extra == "docs"
Provides-Extra: all
Requires-Dist: scswp[dev]; extra == "all"
Requires-Dist: scswp[build]; extra == "all"
Requires-Dist: scswp[docs]; extra == "all"
Dynamic: license-file

<div align="center">

<img src="https://readme-typing-svg.demolab.com?font=Fira+Code&size=32&pause=1000&color=00D4FF&center=true&vCenter=true&width=700&lines=Secure+Collaborative+State;Workspace+Protocol+(SCSWP)" alt="SCSWP Typing SVG" />

<br/>

<p align="center">
  <b>A production-grade, continuously authenticated, multi-client secure file workspace protocol.</b><br/>
  <sub>Built by <a href="mailto:sripadkarthik@gmail.com">Sripad Hebbar</a> &amp; <a href="mailto:sharanrhiremani@gmail.com">Sharan Hiremani</a></sub>
</p>

<br/>

[![PyPI version](https://badge.fury.io/py/scswp.svg)](https://badge.fury.io/py/scswp)
[![Python](https://img.shields.io/pypi/pyversions/scswp.svg?logo=python&logoColor=white)](https://pypi.org/project/scswp/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![IETF Draft](https://img.shields.io/badge/IETF-Draft-blue?logo=ietf)](draft-hebbar-hiremani-scswp-secure-collaborative-workspace-00.txt)
[![Status](https://img.shields.io/badge/Status-Beta-orange)](https://github.com/sripadkarthik/scswp)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/sripadkarthik/scswp/pulls)

</div>

---

## Table of Contents

- [Overview](#overview)
- [Why SCSWP?](#why-scswp)
- [Features](#features)
- [Architecture](#architecture)
- [Cryptographic Design](#cryptographic-design)
- [Protocol Lifecycle](#protocol-lifecycle)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Project Structure](#project-structure)
- [OpCode Reference](#opcode-reference)
- [Error Codes](#error-codes)
- [Configuration](#configuration)
- [IETF Internet Draft](#ietf-internet-draft)
- [Contributing](#contributing)
- [Authors](#authors)
- [License](#license)

---

## Overview

**SCSWP** (Secure Collaborative State Workspace Protocol) is a stateful, continuously authenticated protocol that enables multiple clients — operating from geographically separated, heterogeneous networks — to securely access and collaboratively manage a shared file workspace hosted on a central authoritative server.

> Unlike traditional approaches that address **security** and **collaboration** as separate concerns, SCSWP unifies them into a single, coherent protocol with **continuous trust evaluation** as a first-class requirement.

---

## Why SCSWP?

| Traditional Approach | SCSWP |
|---|---|
| Trust established once at login | Trust evaluated **continuously** every 5 seconds |
| Binary authenticated/not state | Graduated **Trust Score** [0–100] with rekeying and suspension |
| Shared keys for all clients | Per-session **K1 → K2 → K3** cryptographic key hierarchy |
| No session recovery | **DNAC** hash-chain enables cryptographic session recovery |
| No fine-grained access control | **Capability bitmask ACL** per client per workspace |
| No fairness across clients | **Priority-scheduled min-heap worker pool** with resource debt |

---

## Features

### Security

- **Mutual X.509 Authentication** — Server CA (ECDSA P-384) issues and validates client certificates.
- **ECDH Ephemeral Key Exchange** — Fresh P-384 key pair per session; no long-term symmetric keys.
- **Three-Level Key Hierarchy** — K1 (identity) → K2 (authorization) → K3 (active session subkeys).
- **AES-256-GCM Envelopes** — File payloads and control messages encrypted with per-purpose subkeys.
- **HMAC-SHA-256 Signed Trust Signals** — Every D/N/P/S update is authenticated.
- **Key-Dissolving Bootstrap** — Single-use, time-limited tokens; irrevocably consumed on first use.
- **Epoch-Based Key Rotation** — K3 rotated on trust threshold breach, explicit rekey, or DNAC recovery.

### Collaboration

- **Mandatory Server-Side Locking** — Exclusive write locks prevent undefined concurrent writes.
- **Optimistic Version Control** — Five conflict resolution policies: `REJECT`, `RETRY`, `MERGE`, `REBASE`, `CONFLICT VERSION`.
- **Operation Idempotency** — UUID-keyed deduplication prevents duplicate writes on reconnection.
- **DNAC Session Recovery** — Cryptographic hash-chain recovery; no full re-authentication on transient disconnects.

### Operations

- **Hash-Chained Audit Ledger** — Tamper-evident, exportable (CSV) audit log of every operation.
- **Priority Worker Pool** — Min-heap scheduler with anti-starvation wait-boost and resource-debt fairness.
- **SQLite Persistence** — Full session, version history, and idempotency records via SQLAlchemy.
- **Health Monitoring** — CPU, memory, and connection metrics via `psutil`.
- **Server-Sent Events (SSE)** — Real-time workspace update notifications to dashboard.

---

## Architecture

```
Client Request
      │
      ▼
┌─────────────────────┐
│   IDENTITY PLANE    │  X.509 certificate validation
│                     │  Key-Dissolving bootstrap
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│    TRUST PLANE      │  D/N/P/S context evaluation (every 5s)
│                     │  Trust Score [0–100] with HMAC-signed signals
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│   SECURITY PLANE    │  K1 / K2 / K3 key hierarchy
│                     │  AES-256-GCM envelope + HMAC-SHA-256
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ AUTHORIZATION PLANE │  Capability bitmask ACL
│                     │  Per-client, per-workspace
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│   RESOURCE PLANE    │  Min-heap worker pool (N=8)
│                     │  Backpressure + resource-debt fairness
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│  WORKSPACE PLANE    │  Exclusive write locks
│                     │  Optimistic version control
│                     │  UUID idempotency
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│   STORAGE PLANE     │  SQLite file I/O + version history
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ AUDIT / STATE PLANE │  Hash-chained audit ledger
│                     │  DNAC chain advancement
└─────────────────────┘
           │
           ▼
     Client Response
```

---

## Cryptographic Design

```
                 ECDH (P-384)
                      │
                      ▼
              IKM (shared secret)
                      │
                      ▼
         HKDF-SHA256 ("SCSWP_K1:" ‖ session_id)
                      │
                      ▼
              ┌───────┴───────┐
              K1 (Session Root Key)
              └───────┬───────┘
                      │
         HKDF-SHA256 ("SCSWP_K2:" ‖ workspace ‖ session_id)
                      │
                      ▼
              ┌───────┴───────┐
              K2 (Workspace Auth Key)
              └───────┬───────┘
                      │
         HKDF-SHA256 ("SCSWP_K3:epoch:" ‖ epoch, salt=epoch_nonce)  [96 bytes]
                      │
          ┌───────────┼───────────┐
          │           │           │
          ▼           ▼           ▼
    K3.auth_key  K3.ctrl_key  K3.payload_key
    (HMAC-SHA256) (AES-256-GCM) (AES-256-GCM)
    D/N/P/S sigs  control msgs  file payloads
```

| Layer | Algorithm | Key Size |
|---|---|---|
| Key Exchange | ECDH P-384 | 384-bit |
| Key Derivation | HKDF-SHA256 | 256-bit output |
| Symmetric Cipher | AES-256-GCM | 256-bit |
| MAC | HMAC-SHA-256 | 256-bit |
| Certificates | X.509 / ECDSA P-384 | 384-bit |
| Digest | SHA-256 | 256-bit |
| Password Hashing | bcrypt | adaptive |

---

## Protocol Lifecycle

```
UNREGISTERED ──[OP_PROVISION]──► BOOTSTRAP
                                      │
                              [OP_AUTH / ECDH]
                                      │
                                      ▼
                               AUTHENTICATING
                                      │
                               [K1 derived]
                                      │
                                      ▼
                               [K2, K3 derived]
                                      │
                      ┌───────────────▼──────────────────┐
                      │            ACTIVE                 │◄──────────┐
                      └──┬──────────────┬────────────┬───┘           │
                         │              │             │               │
                  trust<REKEY    trust<=SUSPEND   disconnect          │
                         │              │             │               │
                         ▼              ▼             ▼               │
                      REKEYING     SUSPENDED    DISCONNECTED          │
                      (new K3)                       │                │
                         │                     DNAC valid?            │
                         │                    ┌────┴────┐             │
                         │                   YES        NO            │
                         │                    │          │            │
                         │                    ▼          ▼            │
                         │               RECOVERED  [re-auth]         │
                         └──────────────────►┴────────────────────────┘
```

---

## Installation

### From PyPI

```bash
pip install scswp
```

### From Source

```bash
git clone https://github.com/sripadkarthik/scswp.git
cd scswp
pip install -e ".[dev]"
```

### Windows (Batch Installer)

```bat
install_deps.bat
```

### Requirements

- Python 3.10+
- See [requirements.txt](requirements.txt) for full dependency list.

---

## Quick Start

### 1. Start the Server

```bash
scswp-server
```

The server will:
1. Generate a CA key pair and self-signed X.509 certificate.
2. Bind to a dynamic port and print the WebSocket URL.
3. Open the admin dashboard in your browser.

### 2. Register a Client (via Admin Dashboard)

In the dashboard:
1. Click **"Add Client"**.
2. Enter a client name and workspace folder.
3. Copy the generated **bootstrap token** (valid for 24 hours, single-use).

### 3. Start a Client

```bash
scswp-client
```

Enter the server URL and the bootstrap token when prompted. The client will:
1. Complete the Key-Dissolving bootstrap.
2. Perform mutual X.509 authentication.
3. Execute ECDH key exchange and derive K1 → K2 → K3.
4. Begin sending D/N/P/S trust signals.
5. Open the workspace UI.

---

## Project Structure

```
scswp/
├── src/
│   └── scswp/
│       ├── server/
│       │   ├── __init__.py
│       │   ├── server_main.py       # FastAPI hub, WebSocket handler, trust engine
│       │   ├── worker_pool.py       # Min-heap priority scheduler
│       │   ├── database.py          # SQLAlchemy / SQLite persistence layer
│       │   ├── acl.py               # Capability-based access control
│       │   ├── state_manager.py     # Session + DNAC state management
│       │   ├── builder.py           # X.509 certificate builder
│       │   └── static/
│       │       ├── index.html       # Server admin dashboard
│       │       └── style.css        # Glassmorphism UI
│       ├── client/
│       │   ├── __init__.py
│       │   ├── client_main.py       # Client entry point + UI
│       │   ├── protocol_worker.py   # SCSWP protocol state machine
│       │   └── static/              # Client workspace UI
│       └── shared/
│           ├── __init__.py
│           ├── opcodes.py           # OpCode and error code registry
│           └── crypto_utils.py      # ECDH, AES-GCM, HKDF, HMAC utilities
├── tests/
│   ├── test_crypto.py
│   ├── test_worker_pool.py
│   └── test_protocol.py
├── draft-hebbar-hiremani-scswp-secure-collaborative-workspace-00.txt
├── draft-hebbar-hiremani-scswp-secure-collaborative-workspace-00.xml
├── pyproject.toml
├── README.md
├── LICENSE
├── CHANGELOG.md
├── requirements.txt
└── install_deps.bat
```

---

## OpCode Reference

| Value | Name | Direction | Description |
|---|---|---|---|
| `0x01` | `OP_PROVISION` | C→S | Bootstrap / Key-Dissolving |
| `0x02` | `OP_AUTH` | C→S | ECDH identity authentication |
| `0x03` | `OP_TRUST_EVAL` | C→S | D/N/P/S context signal |
| `0x04` | `OP_WORKSPACE_AUTH` | C→S | Workspace authorization |
| `0x05` | `OP_FILE_OP` | C→S | File operation (LIST/READ/WRITE/APPEND) |
| `0x06` | `OP_LOCK` | C→S | Acquire exclusive write lock |
| `0x07` | `OP_UNLOCK` | C→S | Release write lock |
| `0x08` | `OP_DNAC_RECOVERY` | C→S | Session recovery via DNAC |
| `0x09` | `OP_REKEY` | C→S | Explicit K3 epoch rotation |
| `0x0A` | `OP_HEARTBEAT` | C→S | Keep-alive |
| `0x0B` | `OP_ACK` | S→C | Generic success response |
| `0x0C` | `OP_ERROR` | S→C | Error response |
| `0x0D` | `OP_NACK` | S→C | Negative acknowledgement |

---

## Error Codes

| Code | Name | Description |
|---|---|---|
| `0x01` | `INVALID_BOOTSTRAP_TOKEN` | Token not found or already used |
| `0x02` | `TOKEN_EXPIRED` | Token validity period elapsed |
| `0x03` | `AUTH_FAILED` | ECDH or certificate verification failed |
| `0x04` | `NO_SESSION` | session_id not found |
| `0x05` | `FILE_LOCKED` | File held by another session |
| `0x06` | `VERSION_CONFLICT` | expected_version mismatch |
| `0x07` | `RETRY_REQUIRED` | Client should re-fetch and retry |
| `0x08` | `PERMISSION_DENIED` | Client lacks required capability |
| `0x09` | `SESSION_SUSPENDED` | Trust score at or below threshold |
| `0x0A` | `SERVER_BUSY` | outstanding_ops limit reached |
| `0x0B` | `SIGNATURE_INVALID` | HMAC verification failed |
| `0x0C` | `DNAC_MISMATCH` | DNAC recovery hash mismatch |
| `0x0D` | `UNKNOWN_OPCODE` | Received opcode not recognized |
| `0x0E` | `FILE_NOT_FOUND` | Requested file does not exist |
| `0x0F` | `WORKSPACE_NOT_FOUND` | Workspace folder does not exist |

---

## Configuration

Key protocol parameters (configurable in `server_main.py`):

| Parameter | Default | Description |
|---|---|---|
| `T_TRUST` | `5s` | D/N/P/S evaluation interval |
| `T_HEARTBEAT` | `10s` | Heartbeat interval |
| `T_TRUST_TIMEOUT` | `15s` | Max silence before trust penalty |
| `REKEY_THRESHOLD` | `80.0` | Trust score below which K3 rotates |
| `SUSPEND_THRESHOLD` | `10.0` | Trust score below which session suspends |
| `N_WORKERS` | `8` | Worker pool size |
| `MAX_OPS_PER_CLIENT` | `10` | Max concurrent ops per client |
| `DEBT_INCREMENT` | `5.0` | Resource debt per completed op |
| `DEBT_DECAY` | `0.9` | Resource debt decay per scheduler cycle |
| `MAX_LOCK_DURATION` | `300s` | Max time a write lock can be held |
| `TOKEN_TTL` | `24h` | Bootstrap token validity period |

### Trust Score Penalties

| Signal | Penalty |
|---|---|
| Network address change | −15.0 |
| Device identifier change | −60.0 |
| Operation rate > 20 ops / 10s | −5.0 per evaluation |
| HMAC signature invalid | −25.0 |
| Authentication failure | −25.0 |
| Clean evaluation (heal) | +0.5 |

---

## IETF Internet Draft

This repository includes the formal protocol specification as an IETF Internet Draft:

- **Plain Text:** [`draft-hebbar-hiremani-scswp-secure-collaborative-workspace-00.txt`](draft-hebbar-hiremani-scswp-secure-collaborative-workspace-00.txt)
- **RFC XML (v3):** [`draft-hebbar-hiremani-scswp-secure-collaborative-workspace-00.xml`](draft-hebbar-hiremani-scswp-secure-collaborative-workspace-00.xml)

The draft covers:
- Normative protocol message format and OpCode space.
- Cryptographic procedures for K1, K2, and K3 derivation.
- DNAC construction and validation procedure.
- File-state record and concurrency control rules.
- Audit record format and hash-chain construction.
- Security considerations and threat analysis.
- IANA registrations.

---

## Contributing

Contributions are welcome! Please:

1. Fork the repository.
2. Create a feature branch: `git checkout -b feature/your-feature`.
3. Commit your changes: `git commit -m "feat: add your feature"`.
4. Push to the branch: `git push origin feature/your-feature`.
5. Open a Pull Request.

### Development Setup

```bash
git clone https://github.com/sripadkarthik/scswp.git
cd scswp
pip install -e ".[dev]"
pytest
```

### Code Style

```bash
black src/ tests/
isort src/ tests/
mypy src/
```

---

## Authors

<table>
  <tr>
    <td align="center">
      <b>Sripad Hebbar</b><br/>
      <sub>First Author</sub><br/>
      <a href="mailto:sripadkarthik@gmail.com">sripadkarthik@gmail.com</a>
    </td>
    <td align="center">
      <b>Sharan Hiremani</b><br/>
      <sub>Second Author</sub><br/>
      <a href="mailto:sharanrhiremani@gmail.com">sharanrhiremani@gmail.com</a>
    </td>
  </tr>
</table>

---

## License

This project is licensed under the **MIT License** — see the [LICENSE](LICENSE) file for details.

---

<div align="center">
<sub>
Built with security-first principles. SCSWP — because trust should be continuous, not assumed.
</sub>
</div>
