# Aegis

## Open-Source Multi-Tenant API Gateway with Self-Service Dashboard

[![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](LICENSE)
[![Rust](https://img.shields.io/badge/rust-1.70+-orange.svg)](https://www.rust-lang.org/)
[![React](https://img.shields.io/badge/react-19-blue.svg)](https://reactjs.org/)

### Overview

Aegis is an open-source, high-performance API gateway designed for multi-tenant SaaS applications. Built on OpenResty with a Rust admin backend and React dashboard, it enables SaaS companies to register applications, manage API keys, and protect their APIs with authentication, RBAC, and rate limiting.

### Why Aegis?

There are many excellent API gateways available. Here's an honest comparison to help you decide:

#### How Aegis Compares

| Feature | Aegis | Kong | AWS API Gateway | Traefik |
|---------|-------|------|-----------------|---------|
| **Self-hosted** | Yes | Yes | No (AWS only) | Yes |
| **Open source** | AGPL-3.0 | Apache 2.0 | N/A | Apache 2.0 |
| **Admin UI included** | Yes (free) | Enterprise only ($$$) | AWS Console | No built-in |
| **Multi-tenant RBAC** | Built-in | Plugin | Lambda Authorizer | ForwardAuth |
| **External auth callout** | Subrequest | Custom plugin | Lambda Authorizer | ForwardAuth |
| **Pricing** | Free | Free/Enterprise | Per-request | Free |
| **Cold start latency** | None (Lua) | None | Lambda cold starts | None |
| **Setup complexity** | Docker Compose | Kubernetes preferred | AWS ecosystem | Docker/K8s |

#### When to Choose Aegis

**Choose Aegis if you want:**
- Self-hosted solution with no vendor lock-in
- Built-in admin dashboard without enterprise pricing
- Simple Docker Compose deployment
- Multi-tenant SaaS with per-tenant isolation
- Low latency without cold starts

**Choose alternatives if you need:**
- Enterprise support contracts (Kong Enterprise)
- Deep AWS ecosystem integration (AWS API Gateway)
- Kubernetes-native service mesh (Traefik, Envoy)
- Production-proven at massive scale (Kong, AWS)

#### Feature Parity

To be clear: features like external authorization callouts, multi-tenancy, and RBAC are available in other gateways:
- **Kong**: [Custom Auth Plugins](https://docs.konghq.com/gateway/latest/plugin-development/)
- **AWS**: [Lambda Authorizers](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)
- **Traefik**: [ForwardAuth Middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/)

Aegis provides these capabilities in a simpler, self-contained package with a free admin UI.

### Architecture

```
┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│  Admin Frontend │────▶│  Admin Service  │────▶│   PostgreSQL    │
│  (React/Vite)   │     │  (Rust/Axum)    │     │                 │
│  :5173          │     │  :3001          │     │  :5434          │
└─────────────────┘     └────────┬────────┘     └─────────────────┘
                                 │
                                 ▼
┌─────────────────┐     ┌─────────────────┐
│  Gateway Core   │────▶│     Redis       │
│  (OpenResty)    │     │  :7979          │
│  :8000          │     └─────────────────┘
└─────────────────┘
```

### Features

#### Self-Service Dashboard
- Customer registration with email verification
- SaaS application management
- API key generation (production/staging/development)
- SSL certificate provisioning (Let's Encrypt ACME)
- Usage analytics and billing

#### Gateway Core
- Sub-2ms latency with OpenResty/Lua
- JWT validation with tenant context
- Hierarchical RBAC with Redis caching
- Subrequest fallback to backend for dynamic auth
- Rate limiting (fixed window, sliding window, token bucket, leaky bucket)
- Hot-reload configuration

#### Add-on Marketplace
- Heroku-style add-on provisioning
- Provider API for third-party integrations
- Revenue sharing (70/30 split)
- SSO for add-on dashboards
- Usage-based billing support

#### CLI Tool (aegis-cli)
- Customer management
- Cache operations (health, warm, invalidate)
- Platform metrics
- SSL certificate management
- Gateway health checks

#### Multi-Tenancy
- Complete tenant data isolation
- Per-tenant resource quotas
- Tenant-aware RBAC permissions
- Subrequest authorization for dynamic access control

## Quick Start

#### Prerequisites
- Docker & Docker Compose
- Rust (latest stable)
- Node.js 18+

#### Installation

```bash
# Clone the repository
git clone https://github.com/your-org/aegis.git
cd aegis

# Start infrastructure (PostgreSQL, Redis)
docker-compose -f docker-compose.dev.yml up -d

# Start backend
cd admin-service
DATABASE_URL="postgresql://aegis_user:aegis_password@localhost:5434/aegis" \
REDIS_URL="redis://localhost:7979" \
JWT_SECRET="your-secret-key" \
cargo run

# Start frontend (in another terminal)
cd admin-frontend
npm install
npm run dev
```

#### Try the Sample App

We include a sample multi-tenant backend to demonstrate Aegis features:

```bash
cd sample-backend
npm install
npm start
```

See [sample-backend/GETTING_STARTED.md](sample-backend/GETTING_STARTED.md) for the full walkthrough.

#### Access Points

| Service | URL |
|---------|-----|
| Dashboard | http://localhost:5173 |
| Admin API | http://localhost:3001 |
| Gateway | http://localhost:8000 |
| Sample Backend | http://localhost:4000 |

## Project Structure

```
aegis/
├── admin-frontend/         # React dashboard (Vite + TypeScript)
│   ├── src/
│   │   ├── pages/          # Dashboard, Apps, API Keys, Billing, SSL
│   │   ├── services/       # API client modules
│   │   └── components/     # Reusable UI components
│
├── admin-service/          # Rust backend (Axum)
│   ├── src/
│   │   ├── bin/            # aegis-cli binary
│   │   ├── cli/            # CLI command modules
│   │   ├── handlers/       # HTTP endpoints
│   │   ├── services/       # Database, Redis, ACME
│   │   └── utils/          # Crypto, API keys
│   └── migrations/         # SQL migrations
│
├── core/                   # OpenResty gateway
│   ├── lib/                # Lua modules
│   │   ├── jwt_aegis.lua   # Main orchestrator
│   │   ├── saas_app_resolver.lua
│   │   ├── tenant_manager.lua
│   │   └── plugins/        # Rate limit, observability
│   ├── test/               # Lua unit tests
│   └── config/nginx.conf
│
├── sample-backend/         # Demo multi-tenant API (not in releases)
│   ├── routes/
│   │   ├── multitenant.js  # Tenant-isolated endpoints
│   │   └── authorize.js    # Subrequest auth endpoint
│   └── data/tenants.js     # Multi-tenant data model
│
├── docs/                   # Documentation
│   ├── adrs/               # Architecture decisions
│   ├── operations/         # Deployment and operations guides
│   └── api-reference.md
│
└── scripts/
    └── e2e-test.sh         # End-to-end tests
```

## Multi-Tenant Subrequest Flow

Aegis can delegate authorization decisions to your backend:

```
Client Request with JWT
        ↓
┌─────────────────────────────────┐
│     Aegis Gateway               │
│  1. Validate JWT                │
│  2. Extract tenant_id, user_id  │
│  3. Check RBAC cache            │
│     ↓ (cache miss)              │
│  4. Subrequest to backend       │
└─────────────────────────────────┘
        ↓
┌─────────────────────────────────┐
│  POST /aegis/authorize          │
│  {                              │
│    tenant_id, user_id,          │
│    resource, action             │
│  }                              │
└─────────────────────────────────┘
        ↓
┌─────────────────────────────────┐
│  Your Backend Response          │
│  { allowed: true,               │
│    permissions: [...] }         │
└─────────────────────────────────┘
        ↓
   Aegis caches result, forwards request (or blocks)
```

This enables dynamic, context-aware authorization without gateway restarts.

## API Endpoints

#### Public
- `POST /register` - Customer registration
- `GET /health` - Health check

#### Authenticated (`/api/v1/*`)
- `POST /auth/login` - Login
- `GET /dashboard` - Dashboard metrics
- `GET /apps` - List applications
- `POST /apps` - Create application
- `GET /apps/:id` - Get application details
- `GET /api-keys` - List all API keys
- `POST /apps/:id/api-keys` - Create API key
- `GET /ssl/certificates` - List SSL certificates
- `GET /settings/notifications` - Notification preferences

### Technology Stack

| Layer | Technology | Purpose |
|-------|------------|---------|
| Gateway | OpenResty 1.25.x | High-performance request routing |
| Backend | Rust + Axum | Admin API, business logic |
| Frontend | React 19 + Vite | Self-service dashboard |
| Database | PostgreSQL 18 | Persistent storage |
| Cache | Redis 8 | Session, RBAC cache |
| Styling | Tailwind CSS 4 | UI components |

### Documentation

- [Getting Started](sample-backend/GETTING_STARTED.md) - Full walkthrough with sample app
- [Architecture](docs/architecture.md) - System design and overview
- [API Reference](docs/api-reference.md) - Endpoint documentation
- [Add-on Marketplace](docs/addon-marketplace.md) - Provider integration guide
- [Caching Strategy](docs/caching-strategy.md) - Multi-tier caching design
- [Operations](docs/operations/) - Deployment and monitoring guides
- [Branding](docs/branding.md) - Logo and design guidelines

#### CLI Usage

```bash
# Build the CLI
cd admin-service
cargo build --release --bin aegis-cli

# Gateway management
aegis-cli gateway status          # Show gateway health
aegis-cli gateway reload          # Hot reload configuration
aegis-cli gateway metrics         # Show gateway metrics
aegis-cli gateway list            # List registered instances

# Customer management
aegis-cli customers list --status active
aegis-cli customers get <customer-id>

# Plugin management
aegis-cli plugin list             # List installed plugins
aegis-cli plugin enable <name>    # Enable a plugin
aegis-cli plugin disable <name>   # Disable a plugin
aegis-cli plugin reload           # Hot reload plugins
aegis-cli plugin create my-plugin # Create plugin template

# Analytics and reporting
aegis-cli analytics export --customer <id> --format csv
aegis-cli analytics report --type summary --period month
aegis-cli analytics top-consumers --limit 10

# Backup and restore
aegis-cli backup create --output ./backups
aegis-cli backup list
aegis-cli backup restore <file> --yes

# Configuration
aegis-cli config show             # Show current config
aegis-cli config validate         # Validate configuration
aegis-cli config env              # List environment variables

# Cache operations
aegis-cli cache health
aegis-cli cache warm
aegis-cli cache invalidate --pattern "app:*"

# Platform metrics
aegis-cli metrics platform

# SSL certificates
aegis-cli ssl list

# Add-on marketplace
aegis-cli addons list
aegis-cli addons providers list
aegis-cli addons revenue
```

#### Development

```bash
# Backend with auto-reload
cargo watch -x run

# Frontend (hot reload automatic)
npm run dev

# Run Lua unit tests
cd core/test && ./run_tests.sh

# Run E2E tests
./scripts/e2e-test.sh

# Build for production
cd admin-frontend && npm run build
```

### Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

### License

AGPL-3.0 License - see [LICENSE](LICENSE)

This means:
- You can use, modify, and distribute Aegis freely
- If you modify Aegis and offer it as a service, you must open-source your modifications
- This protects the community from proprietary forks while keeping Aegis truly open

---

### Author

Created by **Ken C. Demanawa** ([@kanutocd](https://github.com/kanutocd))

See [AUTHORS](AUTHORS) for all contributors.

---

*Aegis: Open-source API gateway for multi-tenant SaaS applications*

*Built with purpose. Shared with love. Made to last.*
