Skip to content

quintbotha/secure-rust-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Secure REST API in Rust

CI License: MIT Rust

A production-ready, secure REST API built with Rust, featuring JWT authentication, password hashing with Argon2, and CORS support.

⚠️ Disclaimer

THIS SOFTWARE IS PROVIDED "AS IS" FOR EDUCATIONAL AND DEMONSTRATION PURPOSES ONLY.

This project is a reference implementation and should not be used directly in production without:

  • Proper security auditing
  • Thorough testing in your specific environment
  • Additional security hardening based on your requirements
  • Regular security updates and maintenance

The author assumes no liability for any damages, security breaches, or data loss that may occur from using this software. Use at your own risk.

πŸ” Security Features

  • JWT Authentication: Stateless authentication using JSON Web Tokens
  • Argon2 Password Hashing: Industry-standard password hashing algorithm
  • Rate Limiting: In-memory IP-based rate limiting on authentication endpoints
  • CORS Configuration: Cross-Origin Resource Sharing protection
  • Secure Headers: HTTP security headers implementation
  • Token Expiration: Automatic token expiration (24 hours)
  • Environment Variables: Sensitive configuration via environment variables
  • Persistent Storage: Redb embedded database for user data

πŸš€ Tech Stack

  • actix-web: High-performance async web framework
  • tokio: Async runtime
  • jsonwebtoken: JWT implementation
  • argon2: Password hashing
  • serde: Serialization/deserialization
  • chrono: Date and time handling
  • dotenvy: Environment variable management
  • redb: High-performance embedded database
  • governor: Rate limiting

πŸ“ Project Structure

secure-rust-api/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ handlers/       # Request handlers
β”‚   β”‚   β”œβ”€β”€ auth.rs     # Authentication endpoints
β”‚   β”‚   └── api.rs      # API endpoints
β”‚   β”œβ”€β”€ middleware/     # Custom middleware
β”‚   β”‚   └── auth.rs     # JWT authentication middleware
β”‚   β”œβ”€β”€ models/         # Data models
β”‚   β”‚   └── user.rs     # User and Claims models
β”‚   β”œβ”€β”€ utils/          # Utility functions
β”‚   β”‚   └── auth.rs     # Auth utilities (hashing, JWT)
β”‚   └── main.rs         # Application entry point
β”œβ”€β”€ Cargo.toml          # Dependencies
β”œβ”€β”€ .env.example        # Environment variables template
└── README.md           # This file

πŸ› οΈ Setup

Prerequisites

  • Rust 1.70+ (install from rustup.rs)
  • Cargo (comes with Rust)

Installation

  1. Clone the repository:

    git clone https://github.com/quintbotha/secure-rust-api.git
    cd secure-rust-api
  2. Create environment file:

    cp .env.example .env
  3. Edit .env and set a strong JWT secret:

    JWT_SECRET=your-very-strong-random-secret-key-here
  4. Build the project:

    cargo build --release
  5. Run the server:

    cargo run

The server will start on http://127.0.0.1:8080

πŸ“‘ API Endpoints

Public Endpoints

Health Check

GET /api/health

Response:

{
  "status": "healthy",
  "timestamp": "2024-01-01T12:00:00Z"
}

Register User

POST /api/auth/register
Content-Type: application/json

{
  "username": "john_doe",
  "email": "john@example.com",
  "password": "securepassword123"
}

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "username": "john_doe",
    "email": "john@example.com"
  }
}

Login User

POST /api/auth/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "password123"
}

Response: Same as register

Protected Endpoints

These endpoints require a valid JWT token in the Authorization header.

Get Secure Data

GET /api/secure/data
Authorization: Bearer <your-jwt-token>

Response:

{
  "message": "This is protected data",
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "data": ["Sensitive item 1", "Sensitive item 2", "Sensitive item 3"]
}

Get User Profile

GET /api/secure/profile
Authorization: Bearer <your-jwt-token>

Response:

{
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "john@example.com",
  "exp": 1704117600
}

Update User Profile

PATCH /api/secure/profile
Authorization: Bearer <your-jwt-token>
Content-Type: application/json

{
  "username": "new_username",
  "email": "newemail@example.com"
}

Response:

{
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "username": "new_username",
  "email": "newemail@example.com",
  "updated_at": "2024-01-01T12:00:00Z"
}

Change Password

POST /api/secure/change-password
Authorization: Bearer <your-jwt-token>
Content-Type: application/json

{
  "old_password": "currentpassword123",
  "new_password": "newpassword456"
}

Response:

{
  "message": "Password changed successfully",
  "changed_at": "2024-01-01T12:00:00Z"
}

Delete Account

DELETE /api/secure/account
Authorization: Bearer <your-jwt-token>

Response:

{
  "message": "Account deleted successfully",
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "deleted_at": "2024-01-01T12:00:00Z"
}

πŸ§ͺ Testing with cURL

Register a new user

curl -X POST http://localhost:8080/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "email": "test@example.com",
    "password": "securepass123"
  }'

Login (demo credentials)

curl -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "password123"
  }'

Access protected endpoint

# Replace <TOKEN> with the JWT from login/register
curl -X GET http://localhost:8080/api/secure/data \
  -H "Authorization: Bearer <TOKEN>"

Update profile

curl -X PATCH http://localhost:8080/api/secure/profile \
  -H "Authorization: Bearer <TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "newusername",
    "email": "newemail@example.com"
  }'

Change password

curl -X POST http://localhost:8080/api/secure/change-password \
  -H "Authorization: Bearer <TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "old_password": "oldpassword123",
    "new_password": "newpassword456"
  }'

Delete account

curl -X DELETE http://localhost:8080/api/secure/account \
  -H "Authorization: Bearer <TOKEN>"

πŸ”§ Configuration

Edit .env to customize:

# Server Configuration
HOST=127.0.0.1      # Bind address
PORT=8080           # Port number

# JWT Configuration
JWT_SECRET=your-secret-key  # Change this!

# Logging
RUST_LOG=info       # Log level (debug, info, warn, error)

πŸ›‘οΈ Security Best Practices

  1. Change the JWT Secret: Always use a strong, random secret in production
  2. Use HTTPS: Deploy behind a reverse proxy with TLS/SSL
  3. Rate Limiting: Implement rate limiting for authentication endpoints
  4. Database: Connect to a real database instead of in-memory storage
  5. Input Validation: Add comprehensive input validation
  6. Error Handling: Avoid exposing sensitive information in error messages
  7. Token Refresh: Implement refresh tokens for long-lived sessions
  8. Password Requirements: Enforce strong password policies

πŸ“ Development

Run in development mode

cargo run

Run with debug logging

RUST_LOG=debug cargo run

Format code

cargo fmt

Run linter

cargo clippy

Run tests

cargo test

🐳 Docker Deployment

Quick Start

# Build and start with Docker Compose
docker-compose up -d

# View logs
docker-compose logs -f api

# Stop services
docker-compose down

See DOCKER.md for complete Docker deployment guide.

Features

  • πŸ”’ Distroless base image (minimal attack surface)
  • πŸ‘€ Non-root user (UID 65532)
  • πŸ“¦ Multi-stage build (~50MB final image)
  • πŸ” Health checks
  • πŸ’Ύ Persistent volumes

πŸš€ Production Deployment

Native Binary

  1. Build optimized release binary:

    cargo build --release
  2. Binary location: ./target/release/secure-rust-api

  3. Set environment variables securely (never commit .env)

  4. Use a process manager (systemd, PM2, etc.)

  5. Deploy behind a reverse proxy (nginx, Caddy)

Docker Production

See DOCKER.md for:

  • Reverse proxy setup
  • Resource limits
  • Security hardening
  • Backup/restore procedures

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Key Points:

  • βœ… Free to use, modify, and distribute
  • βœ… Commercial use allowed
  • ❌ No warranty provided
  • ❌ Author not liable for damages

🀝 Contributing

Contributions welcome! Please feel free to submit a Pull Request.

By contributing, you agree that your contributions will be licensed under the MIT License.

πŸ“š Resources

About

An implementation of a secure API in Rust

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •