s3verless


Names3verless JSON
Version 0.1.1 PyPI version JSON
download
home_pageNone
SummaryA framework for building serverless applications using S3 as a backend
upload_time2025-11-03 23:33:24
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT
keywords aws backend fastapi s3 serverless
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # S3verless ๐Ÿš€

[![PyPI version](https://badge.fury.io/py/s3verless.svg)](https://badge.fury.io/py/s3verless)
[![Python Versions](https://img.shields.io/pypi/pyversions/s3verless.svg)](https://pypi.org/project/s3verless/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Tests](https://github.com/alexjacobs08/s3verless/workflows/Tests/badge.svg)](https://github.com/alexjacobs08/s3verless/actions)
[![Development Status](https://img.shields.io/badge/status-alpha-orange.svg)](https://pypi.org/project/s3verless/)

**S3verless** is a Python framework that lets you build complete web applications using only Amazon S3 as your backend. No databases, no servers, no complicated infrastructure - just S3 and your Python code.

> โš ๏ธ **Alpha Software**: S3verless is currently in early development (v0.1.0). The API may change between releases. Use in production at your own risk.

## โœจ Features

- ๐Ÿ—„๏ธ **S3 as a Database**: Store all your data as JSON objects in S3
- ๐Ÿ”Œ **Drop-in FastAPI Integration**: Automatic REST API generation for your models
- ๐ŸŽจ **Admin Interface**: Auto-generated admin panel for managing your data
- ๐Ÿ” **Advanced Querying**: Filter, sort, paginate, and search your S3 data
- ๐Ÿ” **Built-in Auth**: JWT-based authentication with users stored in S3
- ๐Ÿ“ฆ **Zero Config**: Works out of the box with sensible defaults
- ๐Ÿš€ **Truly Serverless**: Deploy to AWS Lambda or any container platform
- ๐Ÿ’ฐ **Cost-Effective**: Pay only for S3 storage and requests

## ๐ŸŽฏ Why S3verless?

Traditional web applications require multiple services:
- โŒ Database server (RDS, DynamoDB, MongoDB)
- โŒ File storage (S3)
- โŒ Cache layer (Redis, Memcached)  
- โŒ Session storage
- โŒ Complex deployment and scaling

With S3verless:
- โœ… Everything in S3
- โœ… Infinite scalability built-in
- โœ… Simple deployment
- โœ… Minimal operational overhead
- โœ… Perfect for MVPs, prototypes, and small to medium applications

## ๐Ÿš€ Quick Start

### Installation

```bash
# Using uv (recommended)
uv pip install s3verless

# Or using pip
pip install s3verless
```

### Create Your First Model

```python
from s3verless import BaseS3Model
from pydantic import Field

class Product(BaseS3Model):
    name: str = Field(..., min_length=1)
    price: float = Field(..., gt=0)
    description: str = ""
    in_stock: bool = True

# That's it! S3verless automatically creates:
# - POST /products
# - GET /products
# - GET /products/{id}
# - PUT /products/{id}
# - DELETE /products/{id}
# - GET /products/search
# - Admin interface at /admin
```

### Create Your App

```python
from s3verless import create_s3verless_app

# Create the FastAPI app with S3 backend
app = create_s3verless_app(
    title="My S3 Store",
    model_packages=["models"],  # Where your models live
    enable_admin=True,
)

# Run with any ASGI server
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

### Configure S3

Create a `.env` file:

```env
AWS_ACCESS_KEY_ID=your-key
AWS_SECRET_ACCESS_KEY=your-secret
AWS_BUCKET_NAME=my-app-bucket
AWS_DEFAULT_REGION=us-east-1

# For local development with LocalStack
AWS_URL=http://localhost:4566
```

## ๐Ÿ“š Advanced Usage

### Custom API Configuration

```python
class Product(BaseS3Model):
    # Customize API behavior
    _plural_name = "products"        # API endpoint name
    _enable_api = True              # Auto-generate CRUD endpoints
    _enable_admin = True            # Show in admin interface
    _indexes = ["category", "price"] # Fields to index
    _unique_fields = ["sku"]        # Enforce uniqueness
    
    name: str
    sku: str
    category: str
    price: float
```

### Advanced Queries

```python
from s3verless import get_s3_client, query

async def find_products():
    s3 = get_s3_client()
    
    # Filter and sort
    products = await query(Product, s3, "my-bucket").filter(
        category="electronics",
        price__lt=1000,
        in_stock=True
    ).order_by("-created_at").limit(10).all()
    
    # Pagination
    page = await query(Product, s3, "my-bucket").paginate(
        page=1, 
        page_size=20
    )
    
    # Complex queries
    results = await query(Product, s3, "my-bucket").filter(
        name__contains="iPhone"
    ).exclude(
        price__gt=1500
    ).all()
```

### Relationships

```python
import uuid

class Order(BaseS3Model):
    customer_id: uuid.UUID
    items: list[dict]  # Embedded items
    total: float
    
    async def get_customer(self, s3_client):
        """Fetch related customer."""
        return await query(Customer, s3_client, "bucket").get(
            id=self.customer_id
        )
```

### Hooks and Events

```python
from s3verless.core.registry import add_model_hook

async def send_welcome_email(user):
    print(f"Welcome {user.email}!")

# Register a post-creation hook
add_model_hook("User", "post_create", send_welcome_email)
```

## ๐Ÿ” Authentication & Authorization

S3verless includes built-in JWT-based authentication with users stored in S3, plus automatic ownership checks and admin roles.

### Basic Authentication

Simple JWT token authentication:

```python
from s3verless.auth.service import S3AuthService
from s3verless.core.settings import S3verlessSettings

settings = S3verlessSettings()
auth_service = S3AuthService(settings)

# Register a new user
user = await auth_service.create_user(
    s3_client=s3_client,
    username="john",
    email="john@example.com",
    password="SecurePass123!",
    full_name="John Doe"
)

# Authenticate and get JWT token
authenticated_user = await auth_service.authenticate_user(
    s3_client=s3_client,
    username="john",
    password="SecurePass123!"
)

# Create access token
token = auth_service.create_access_token(
    data={"sub": authenticated_user.username}
)
```

### Protected Routes

```python
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = auth_service.decode_token(token)
        username = payload.get("sub")
        user = await auth_service.get_user_by_username(s3_client, username)
        if not user:
            raise HTTPException(status_code=401)
        return user
    except Exception:
        raise HTTPException(status_code=401)

@app.get("/protected")
async def protected_route(user = Depends(get_current_user)):
    return {"message": f"Hello {user.username}"}
```

### Current Limitations

The authentication system uses a **single global secret key** for signing all JWT tokens:

- โœ… Simple and stateless (standard JWT pattern)
- โœ… No database lookups for token validation
- โœ… Works great for most use cases
- โš ๏ธ Changing the secret invalidates ALL user tokens
- โš ๏ธ Cannot revoke individual user tokens (tokens valid until expiry)
- โš ๏ธ No per-user token invalidation (e.g., after password change)

For most applications, this is acceptable. See the [Future Work](#-future-work--roadmap) section for planned improvements.

**Security Best Practices:**
- Use a strong, random `SECRET_KEY` (32+ characters)
- Keep tokens short-lived (15-30 minutes recommended)
- Use HTTPS in production
- Store the secret key securely (environment variables, AWS Secrets Manager)
- Consider implementing token refresh for better UX

See the [auth example](examples/auth_example/) for a complete implementation.

### Automatic Ownership & Admin Roles

Protect resources with automatic ownership checks and admin bypass:

```python
class Post(BaseS3Model):
    _require_ownership = True  # Users can only modify their own posts
    _owner_field = "user_id"   # Field that stores the owner ID
    
    user_id: str  # Automatically set to current user on creation
    title: str
    content: str

# Now automatically:
# โœ… POST /posts/ - Sets user_id to current user
# โœ… PUT /posts/{id} - Only owner (or admin) can update
# โœ… DELETE /posts/{id} - Only owner (or admin) can delete
# โœ… Admins bypass all ownership checks
```

#### Three Levels of Protection

**1. Public (default)** - No authentication required:
```python
class Product(BaseS3Model):
    # No security flags - anyone can CRUD
    name: str
    price: float
```

**2. Auth Required** - Must be logged in:
```python
class SiteSettings(BaseS3Model):
    _require_auth = True  # Any logged-in user can modify
    
    site_name: str
    maintenance_mode: bool
```

**3. Ownership Required** - Must be owner or admin:
```python
class BlogPost(BaseS3Model):
    _require_ownership = True  # Only owner can modify
    _owner_field = "user_id"   # Field containing owner ID
    
    user_id: str  # Auto-set on creation
    title: str
```

#### Admin Users

Users with `is_admin=True` can bypass all ownership checks.

**Default Admin (Development)**:

S3verless automatically creates a default admin account on startup:
- Username: `admin`
- Password: `Admin123!`  
- Can be customized via environment variables

```bash
# Customize default admin (optional)
export DEFAULT_ADMIN_USERNAME=myadmin
export DEFAULT_ADMIN_PASSWORD=SecurePass123!
export DEFAULT_ADMIN_EMAIL=admin@mysite.com

# Disable in production
export CREATE_DEFAULT_ADMIN=false
```

**Programmatic Admin Creation**:

```python
# Create an admin user
admin = await auth_service.create_user(
    s3_client, "admin", "admin@site.com", "SecurePass123!"
)
admin.is_admin = True  # Make them admin
await user_service.update(s3_client, str(admin.id), admin)

# Admin can now:
# - Modify ANY post (even if user_id doesn't match)
# - Delete ANY comment (even if not theirs)
# - Full access to all ownership-protected resources
```

See the [blog platform example](examples/blog_platform/) for a complete implementation.

## ๐Ÿ› ๏ธ CLI Tool

S3verless includes a CLI for common tasks:

```bash
# Create a new project
s3verless init my-app --template ecommerce

# Inspect models
s3verless inspect models.py

# List S3 data
s3verless list-data --bucket my-bucket --prefix products/

# Show version
s3verless version
```

## ๐Ÿ—๏ธ Architecture

S3verless uses a simple but powerful architecture:

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   FastAPI   โ”‚โ”€โ”€โ”€โ”€โ–ถโ”‚  S3verless   โ”‚โ”€โ”€โ”€โ”€โ–ถโ”‚     S3      โ”‚
โ”‚   Routes    โ”‚     โ”‚  Data Layer  โ”‚     โ”‚   Bucket    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                           โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚             โ”‚
              โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”
              โ”‚  Query   โ”‚  โ”‚  Auth    โ”‚
              โ”‚  Engine  โ”‚  โ”‚  System  โ”‚
              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

## ๐Ÿš€ Deployment

### AWS Lambda

```python
# lambda_function.py
from mangum import Mangum
from main import app

handler = Mangum(app)
```

### Docker

```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```

### Local Development

Use LocalStack for S3 emulation:

```bash
docker run -d -p 4566:4566 localstack/localstack
```

## ๐Ÿ“Š Performance Considerations

- **Caching**: S3verless caches frequently accessed objects
- **Indexing**: Use `_indexes` for faster queries
- **Pagination**: Always paginate large datasets
- **Batch Operations**: Use bulk endpoints for multiple operations

## ๐Ÿงช Testing

S3verless includes comprehensive tests:

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=s3verless --cov-report=term-missing

# Run specific test file
pytest tests/test_base.py
```

## ๐Ÿ“– Documentation

- **[Getting Started Guide](docs/getting-started.md)** - Your first S3verless app
- **[API Reference](docs/api-reference.md)** - Complete API documentation
- **[Deployment Guide](docs/deployment.md)** - Deploy to production
- **[Best Practices](docs/best-practices.md)** - Tips and patterns
- **[Contributing](CONTRIBUTING.md)** - How to contribute

## ๐Ÿ”ฎ Future Work & Roadmap

We're actively working on improving S3verless. Here are some planned features:

### Authentication & Security
- **Refresh Tokens**: Implement refresh token pattern for better security
  - Short-lived access tokens (15 min)
  - Long-lived refresh tokens (7 days)
  - Token rotation on refresh
- **Token Versioning**: Per-user token version for selective invalidation
- **Token Blacklist**: Ability to revoke specific tokens
- **Secret Rotation**: Support multiple valid secrets during rotation period
- **OAuth2 Integration**: Social login (Google, GitHub, etc.)
- **Multi-factor Authentication**: 2FA/MFA support

### Performance & Scalability
- **Caching Layer**: Redis/Elasticache integration for hot data
- **Connection Pooling**: Improved S3 connection management
- **Batch Operations**: Optimized bulk insert/update/delete
- **Smart Indexing**: Automatic index suggestions based on query patterns
- **Query Optimization**: Query plan analysis and optimization

### Features
- **Full-Text Search**: Integration with OpenSearch/Elasticsearch
- **File Uploads**: Direct S3 upload with presigned URLs
- **Real-time Subscriptions**: WebSocket support for live updates
- **Backup & Restore**: Automated backup strategies
- **Audit Logging**: Track all data changes
- **GraphQL Support**: Alternative to REST API
- **Database Migration**: Import from/export to traditional databases

### Developer Experience
- **Interactive CLI**: Better model scaffolding and management
- **Type Stubs**: Complete type hints for better IDE support
- **Visual Admin**: Enhanced admin interface with charts
- **Testing Utilities**: Mock S3 helpers and test fixtures
- **Performance Profiling**: Built-in query performance monitoring

Want to contribute to any of these? Check out our [Contributing Guide](CONTRIBUTING.md)!

## ๐Ÿค Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

```bash
# Clone the repository
git clone https://github.com/alexjacobs08/s3verless.git
cd s3verless

# Install uv (if needed)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install dependencies
uv sync --all-extras

# Run tests
uv run pytest

# Format and lint
uv run ruff format .
uv run ruff check .
```

## ๐Ÿ“ License

S3verless is MIT licensed. See [LICENSE](LICENSE) for details.

## ๐Ÿ™ Acknowledgments

Inspired by the serverless movement and the desire to simplify backend development.

## ๐Ÿ“ฆ Publishing to PyPI

See [PUBLISH.md](PUBLISH.md) for instructions on publishing the package to PyPI.

## ๐Ÿ”— Links

- **PyPI**: https://pypi.org/project/s3verless/
- **GitHub**: https://github.com/alexjacobs08/s3verless
- **Issues**: https://github.com/alexjacobs08/s3verless/issues
- **Changelog**: [CHANGELOG.md](CHANGELOG.md)

## ๐Ÿ’ฌ Support

- **GitHub Issues**: For bugs and feature requests
- **GitHub Discussions**: For questions and discussions

---

**Built with โค๏ธ by the S3verless community**

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "s3verless",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "aws, backend, fastapi, s3, serverless",
    "author": null,
    "author_email": "S3verless Contributors <alex.jacobs08+s3verless@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/57/f8/28969e91eec4f1e2b3bf5ff387d25eb64b8253be1ba5f94b6a030268a1e9/s3verless-0.1.1.tar.gz",
    "platform": null,
    "description": "# S3verless \ud83d\ude80\n\n[![PyPI version](https://badge.fury.io/py/s3verless.svg)](https://badge.fury.io/py/s3verless)\n[![Python Versions](https://img.shields.io/pypi/pyversions/s3verless.svg)](https://pypi.org/project/s3verless/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Tests](https://github.com/alexjacobs08/s3verless/workflows/Tests/badge.svg)](https://github.com/alexjacobs08/s3verless/actions)\n[![Development Status](https://img.shields.io/badge/status-alpha-orange.svg)](https://pypi.org/project/s3verless/)\n\n**S3verless** is a Python framework that lets you build complete web applications using only Amazon S3 as your backend. No databases, no servers, no complicated infrastructure - just S3 and your Python code.\n\n> \u26a0\ufe0f **Alpha Software**: S3verless is currently in early development (v0.1.0). The API may change between releases. Use in production at your own risk.\n\n## \u2728 Features\n\n- \ud83d\uddc4\ufe0f **S3 as a Database**: Store all your data as JSON objects in S3\n- \ud83d\udd0c **Drop-in FastAPI Integration**: Automatic REST API generation for your models\n- \ud83c\udfa8 **Admin Interface**: Auto-generated admin panel for managing your data\n- \ud83d\udd0d **Advanced Querying**: Filter, sort, paginate, and search your S3 data\n- \ud83d\udd10 **Built-in Auth**: JWT-based authentication with users stored in S3\n- \ud83d\udce6 **Zero Config**: Works out of the box with sensible defaults\n- \ud83d\ude80 **Truly Serverless**: Deploy to AWS Lambda or any container platform\n- \ud83d\udcb0 **Cost-Effective**: Pay only for S3 storage and requests\n\n## \ud83c\udfaf Why S3verless?\n\nTraditional web applications require multiple services:\n- \u274c Database server (RDS, DynamoDB, MongoDB)\n- \u274c File storage (S3)\n- \u274c Cache layer (Redis, Memcached)  \n- \u274c Session storage\n- \u274c Complex deployment and scaling\n\nWith S3verless:\n- \u2705 Everything in S3\n- \u2705 Infinite scalability built-in\n- \u2705 Simple deployment\n- \u2705 Minimal operational overhead\n- \u2705 Perfect for MVPs, prototypes, and small to medium applications\n\n## \ud83d\ude80 Quick Start\n\n### Installation\n\n```bash\n# Using uv (recommended)\nuv pip install s3verless\n\n# Or using pip\npip install s3verless\n```\n\n### Create Your First Model\n\n```python\nfrom s3verless import BaseS3Model\nfrom pydantic import Field\n\nclass Product(BaseS3Model):\n    name: str = Field(..., min_length=1)\n    price: float = Field(..., gt=0)\n    description: str = \"\"\n    in_stock: bool = True\n\n# That's it! S3verless automatically creates:\n# - POST /products\n# - GET /products\n# - GET /products/{id}\n# - PUT /products/{id}\n# - DELETE /products/{id}\n# - GET /products/search\n# - Admin interface at /admin\n```\n\n### Create Your App\n\n```python\nfrom s3verless import create_s3verless_app\n\n# Create the FastAPI app with S3 backend\napp = create_s3verless_app(\n    title=\"My S3 Store\",\n    model_packages=[\"models\"],  # Where your models live\n    enable_admin=True,\n)\n\n# Run with any ASGI server\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n### Configure S3\n\nCreate a `.env` file:\n\n```env\nAWS_ACCESS_KEY_ID=your-key\nAWS_SECRET_ACCESS_KEY=your-secret\nAWS_BUCKET_NAME=my-app-bucket\nAWS_DEFAULT_REGION=us-east-1\n\n# For local development with LocalStack\nAWS_URL=http://localhost:4566\n```\n\n## \ud83d\udcda Advanced Usage\n\n### Custom API Configuration\n\n```python\nclass Product(BaseS3Model):\n    # Customize API behavior\n    _plural_name = \"products\"        # API endpoint name\n    _enable_api = True              # Auto-generate CRUD endpoints\n    _enable_admin = True            # Show in admin interface\n    _indexes = [\"category\", \"price\"] # Fields to index\n    _unique_fields = [\"sku\"]        # Enforce uniqueness\n    \n    name: str\n    sku: str\n    category: str\n    price: float\n```\n\n### Advanced Queries\n\n```python\nfrom s3verless import get_s3_client, query\n\nasync def find_products():\n    s3 = get_s3_client()\n    \n    # Filter and sort\n    products = await query(Product, s3, \"my-bucket\").filter(\n        category=\"electronics\",\n        price__lt=1000,\n        in_stock=True\n    ).order_by(\"-created_at\").limit(10).all()\n    \n    # Pagination\n    page = await query(Product, s3, \"my-bucket\").paginate(\n        page=1, \n        page_size=20\n    )\n    \n    # Complex queries\n    results = await query(Product, s3, \"my-bucket\").filter(\n        name__contains=\"iPhone\"\n    ).exclude(\n        price__gt=1500\n    ).all()\n```\n\n### Relationships\n\n```python\nimport uuid\n\nclass Order(BaseS3Model):\n    customer_id: uuid.UUID\n    items: list[dict]  # Embedded items\n    total: float\n    \n    async def get_customer(self, s3_client):\n        \"\"\"Fetch related customer.\"\"\"\n        return await query(Customer, s3_client, \"bucket\").get(\n            id=self.customer_id\n        )\n```\n\n### Hooks and Events\n\n```python\nfrom s3verless.core.registry import add_model_hook\n\nasync def send_welcome_email(user):\n    print(f\"Welcome {user.email}!\")\n\n# Register a post-creation hook\nadd_model_hook(\"User\", \"post_create\", send_welcome_email)\n```\n\n## \ud83d\udd10 Authentication & Authorization\n\nS3verless includes built-in JWT-based authentication with users stored in S3, plus automatic ownership checks and admin roles.\n\n### Basic Authentication\n\nSimple JWT token authentication:\n\n```python\nfrom s3verless.auth.service import S3AuthService\nfrom s3verless.core.settings import S3verlessSettings\n\nsettings = S3verlessSettings()\nauth_service = S3AuthService(settings)\n\n# Register a new user\nuser = await auth_service.create_user(\n    s3_client=s3_client,\n    username=\"john\",\n    email=\"john@example.com\",\n    password=\"SecurePass123!\",\n    full_name=\"John Doe\"\n)\n\n# Authenticate and get JWT token\nauthenticated_user = await auth_service.authenticate_user(\n    s3_client=s3_client,\n    username=\"john\",\n    password=\"SecurePass123!\"\n)\n\n# Create access token\ntoken = auth_service.create_access_token(\n    data={\"sub\": authenticated_user.username}\n)\n```\n\n### Protected Routes\n\n```python\nfrom fastapi import Depends, HTTPException\nfrom fastapi.security import OAuth2PasswordBearer\n\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n\nasync def get_current_user(token: str = Depends(oauth2_scheme)):\n    try:\n        payload = auth_service.decode_token(token)\n        username = payload.get(\"sub\")\n        user = await auth_service.get_user_by_username(s3_client, username)\n        if not user:\n            raise HTTPException(status_code=401)\n        return user\n    except Exception:\n        raise HTTPException(status_code=401)\n\n@app.get(\"/protected\")\nasync def protected_route(user = Depends(get_current_user)):\n    return {\"message\": f\"Hello {user.username}\"}\n```\n\n### Current Limitations\n\nThe authentication system uses a **single global secret key** for signing all JWT tokens:\n\n- \u2705 Simple and stateless (standard JWT pattern)\n- \u2705 No database lookups for token validation\n- \u2705 Works great for most use cases\n- \u26a0\ufe0f Changing the secret invalidates ALL user tokens\n- \u26a0\ufe0f Cannot revoke individual user tokens (tokens valid until expiry)\n- \u26a0\ufe0f No per-user token invalidation (e.g., after password change)\n\nFor most applications, this is acceptable. See the [Future Work](#-future-work--roadmap) section for planned improvements.\n\n**Security Best Practices:**\n- Use a strong, random `SECRET_KEY` (32+ characters)\n- Keep tokens short-lived (15-30 minutes recommended)\n- Use HTTPS in production\n- Store the secret key securely (environment variables, AWS Secrets Manager)\n- Consider implementing token refresh for better UX\n\nSee the [auth example](examples/auth_example/) for a complete implementation.\n\n### Automatic Ownership & Admin Roles\n\nProtect resources with automatic ownership checks and admin bypass:\n\n```python\nclass Post(BaseS3Model):\n    _require_ownership = True  # Users can only modify their own posts\n    _owner_field = \"user_id\"   # Field that stores the owner ID\n    \n    user_id: str  # Automatically set to current user on creation\n    title: str\n    content: str\n\n# Now automatically:\n# \u2705 POST /posts/ - Sets user_id to current user\n# \u2705 PUT /posts/{id} - Only owner (or admin) can update\n# \u2705 DELETE /posts/{id} - Only owner (or admin) can delete\n# \u2705 Admins bypass all ownership checks\n```\n\n#### Three Levels of Protection\n\n**1. Public (default)** - No authentication required:\n```python\nclass Product(BaseS3Model):\n    # No security flags - anyone can CRUD\n    name: str\n    price: float\n```\n\n**2. Auth Required** - Must be logged in:\n```python\nclass SiteSettings(BaseS3Model):\n    _require_auth = True  # Any logged-in user can modify\n    \n    site_name: str\n    maintenance_mode: bool\n```\n\n**3. Ownership Required** - Must be owner or admin:\n```python\nclass BlogPost(BaseS3Model):\n    _require_ownership = True  # Only owner can modify\n    _owner_field = \"user_id\"   # Field containing owner ID\n    \n    user_id: str  # Auto-set on creation\n    title: str\n```\n\n#### Admin Users\n\nUsers with `is_admin=True` can bypass all ownership checks.\n\n**Default Admin (Development)**:\n\nS3verless automatically creates a default admin account on startup:\n- Username: `admin`\n- Password: `Admin123!`  \n- Can be customized via environment variables\n\n```bash\n# Customize default admin (optional)\nexport DEFAULT_ADMIN_USERNAME=myadmin\nexport DEFAULT_ADMIN_PASSWORD=SecurePass123!\nexport DEFAULT_ADMIN_EMAIL=admin@mysite.com\n\n# Disable in production\nexport CREATE_DEFAULT_ADMIN=false\n```\n\n**Programmatic Admin Creation**:\n\n```python\n# Create an admin user\nadmin = await auth_service.create_user(\n    s3_client, \"admin\", \"admin@site.com\", \"SecurePass123!\"\n)\nadmin.is_admin = True  # Make them admin\nawait user_service.update(s3_client, str(admin.id), admin)\n\n# Admin can now:\n# - Modify ANY post (even if user_id doesn't match)\n# - Delete ANY comment (even if not theirs)\n# - Full access to all ownership-protected resources\n```\n\nSee the [blog platform example](examples/blog_platform/) for a complete implementation.\n\n## \ud83d\udee0\ufe0f CLI Tool\n\nS3verless includes a CLI for common tasks:\n\n```bash\n# Create a new project\ns3verless init my-app --template ecommerce\n\n# Inspect models\ns3verless inspect models.py\n\n# List S3 data\ns3verless list-data --bucket my-bucket --prefix products/\n\n# Show version\ns3verless version\n```\n\n## \ud83c\udfd7\ufe0f Architecture\n\nS3verless uses a simple but powerful architecture:\n\n```\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502   FastAPI   \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  S3verless   \u2502\u2500\u2500\u2500\u2500\u25b6\u2502     S3      \u2502\n\u2502   Routes    \u2502     \u2502  Data Layer  \u2502     \u2502   Bucket    \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                           \u2502\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n                    \u2502             \u2502\n              \u250c\u2500\u2500\u2500\u2500\u2500\u25bc\u2500\u2500\u2500\u2500\u2510  \u250c\u2500\u2500\u2500\u2500\u25bc\u2500\u2500\u2500\u2500\u2500\u2510\n              \u2502  Query   \u2502  \u2502  Auth    \u2502\n              \u2502  Engine  \u2502  \u2502  System  \u2502\n              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\n\n## \ud83d\ude80 Deployment\n\n### AWS Lambda\n\n```python\n# lambda_function.py\nfrom mangum import Mangum\nfrom main import app\n\nhandler = Mangum(app)\n```\n\n### Docker\n\n```dockerfile\nFROM python:3.11-slim\nWORKDIR /app\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nCOPY . .\nCMD [\"uvicorn\", \"main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n```\n\n### Local Development\n\nUse LocalStack for S3 emulation:\n\n```bash\ndocker run -d -p 4566:4566 localstack/localstack\n```\n\n## \ud83d\udcca Performance Considerations\n\n- **Caching**: S3verless caches frequently accessed objects\n- **Indexing**: Use `_indexes` for faster queries\n- **Pagination**: Always paginate large datasets\n- **Batch Operations**: Use bulk endpoints for multiple operations\n\n## \ud83e\uddea Testing\n\nS3verless includes comprehensive tests:\n\n```bash\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=s3verless --cov-report=term-missing\n\n# Run specific test file\npytest tests/test_base.py\n```\n\n## \ud83d\udcd6 Documentation\n\n- **[Getting Started Guide](docs/getting-started.md)** - Your first S3verless app\n- **[API Reference](docs/api-reference.md)** - Complete API documentation\n- **[Deployment Guide](docs/deployment.md)** - Deploy to production\n- **[Best Practices](docs/best-practices.md)** - Tips and patterns\n- **[Contributing](CONTRIBUTING.md)** - How to contribute\n\n## \ud83d\udd2e Future Work & Roadmap\n\nWe're actively working on improving S3verless. Here are some planned features:\n\n### Authentication & Security\n- **Refresh Tokens**: Implement refresh token pattern for better security\n  - Short-lived access tokens (15 min)\n  - Long-lived refresh tokens (7 days)\n  - Token rotation on refresh\n- **Token Versioning**: Per-user token version for selective invalidation\n- **Token Blacklist**: Ability to revoke specific tokens\n- **Secret Rotation**: Support multiple valid secrets during rotation period\n- **OAuth2 Integration**: Social login (Google, GitHub, etc.)\n- **Multi-factor Authentication**: 2FA/MFA support\n\n### Performance & Scalability\n- **Caching Layer**: Redis/Elasticache integration for hot data\n- **Connection Pooling**: Improved S3 connection management\n- **Batch Operations**: Optimized bulk insert/update/delete\n- **Smart Indexing**: Automatic index suggestions based on query patterns\n- **Query Optimization**: Query plan analysis and optimization\n\n### Features\n- **Full-Text Search**: Integration with OpenSearch/Elasticsearch\n- **File Uploads**: Direct S3 upload with presigned URLs\n- **Real-time Subscriptions**: WebSocket support for live updates\n- **Backup & Restore**: Automated backup strategies\n- **Audit Logging**: Track all data changes\n- **GraphQL Support**: Alternative to REST API\n- **Database Migration**: Import from/export to traditional databases\n\n### Developer Experience\n- **Interactive CLI**: Better model scaffolding and management\n- **Type Stubs**: Complete type hints for better IDE support\n- **Visual Admin**: Enhanced admin interface with charts\n- **Testing Utilities**: Mock S3 helpers and test fixtures\n- **Performance Profiling**: Built-in query performance monitoring\n\nWant to contribute to any of these? Check out our [Contributing Guide](CONTRIBUTING.md)!\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/alexjacobs08/s3verless.git\ncd s3verless\n\n# Install uv (if needed)\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Install dependencies\nuv sync --all-extras\n\n# Run tests\nuv run pytest\n\n# Format and lint\nuv run ruff format .\nuv run ruff check .\n```\n\n## \ud83d\udcdd License\n\nS3verless is MIT licensed. See [LICENSE](LICENSE) for details.\n\n## \ud83d\ude4f Acknowledgments\n\nInspired by the serverless movement and the desire to simplify backend development.\n\n## \ud83d\udce6 Publishing to PyPI\n\nSee [PUBLISH.md](PUBLISH.md) for instructions on publishing the package to PyPI.\n\n## \ud83d\udd17 Links\n\n- **PyPI**: https://pypi.org/project/s3verless/\n- **GitHub**: https://github.com/alexjacobs08/s3verless\n- **Issues**: https://github.com/alexjacobs08/s3verless/issues\n- **Changelog**: [CHANGELOG.md](CHANGELOG.md)\n\n## \ud83d\udcac Support\n\n- **GitHub Issues**: For bugs and feature requests\n- **GitHub Discussions**: For questions and discussions\n\n---\n\n**Built with \u2764\ufe0f by the S3verless community**\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A framework for building serverless applications using S3 as a backend",
    "version": "0.1.1",
    "project_urls": {
        "Documentation": "https://s3verless.readthedocs.io",
        "Homepage": "https://github.com/alexjacobs08/s3verless",
        "Issues": "https://github.com/alexjacobs08/s3verless/issues",
        "Repository": "https://github.com/alexjacobs08/s3verless"
    },
    "split_keywords": [
        "aws",
        " backend",
        " fastapi",
        " s3",
        " serverless"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f9e51ec7fb0e2860faf5481e8e98150952edb03142b7964e11c09b1d1a014cde",
                "md5": "fabb259e6aa7b4bbc4ea74ab485bcf70",
                "sha256": "6396f377418de845f446b84dc09817afc477f4cf1af7c35ed8143f90ad76d638"
            },
            "downloads": -1,
            "filename": "s3verless-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "fabb259e6aa7b4bbc4ea74ab485bcf70",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 45701,
            "upload_time": "2025-11-03T23:33:23",
            "upload_time_iso_8601": "2025-11-03T23:33:23.734584Z",
            "url": "https://files.pythonhosted.org/packages/f9/e5/1ec7fb0e2860faf5481e8e98150952edb03142b7964e11c09b1d1a014cde/s3verless-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "57f828969e91eec4f1e2b3bf5ff387d25eb64b8253be1ba5f94b6a030268a1e9",
                "md5": "047f526808c183f24fb5749bde14d723",
                "sha256": "2e7686ced15574ec311e75410ef478a8d35468b409476815b2a2c339300ca7f8"
            },
            "downloads": -1,
            "filename": "s3verless-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "047f526808c183f24fb5749bde14d723",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 67111,
            "upload_time": "2025-11-03T23:33:24",
            "upload_time_iso_8601": "2025-11-03T23:33:24.828566Z",
            "url": "https://files.pythonhosted.org/packages/57/f8/28969e91eec4f1e2b3bf5ff387d25eb64b8253be1ba5f94b6a030268a1e9/s3verless-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-11-03 23:33:24",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "alexjacobs08",
    "github_project": "s3verless",
    "github_not_found": true,
    "lcname": "s3verless"
}
        
Elapsed time: 2.80831s