Skip to content

Riktastic/Axium

Repository files navigation

πŸ¦– Axium

An example API built with Rust, Axum, SQLx, and PostgreSQL.
License: MIT

Summary

Axium is a high-performance, security-focused API boilerplate built using Rust, Axum, SQLx, and PostgreSQL. It provides a ready-to-deploy solution with modern best practices, including JWT authentication, role-based access control (RBAC), structured logging, and enterprise-grade security. With a focus on developer experience, Axium offers auto-generated API documentation, efficient database interactions, and an ergonomic code structure for ease of maintenance and scalability.

Table of Contents

  1. πŸš€ Core Features
  2. πŸ› οΈ Technology Stack
  3. πŸ“‚ Project Structure
  4. 🌐 Default API Endpoints
  5. πŸ“¦ Installation & Usage
  6. 🀝 Contributing

πŸš€ Core Features

Effortless Deployment

From zero to production in minutes

  • 🐳 Docker Compose stack with pre-configured services
  • 20-minute setup timeline with docker-compose up simplicity

Developer-First API Experience

Spec-driven development workflow

  • Auto-generated OpenAPI 3.1 specifications
  • Interactive Swagger UI endpoint at /docs
// Endpoint registration example
.route("/docs", get(serve_swagger_ui))

Enterprise-Grade Security

Security by design architecture

  • JWT authentication with Argon2id password hashing (OWASP recommended)
  • TLS 1.3/HTTP2 via AWS-LC (FIPS 140-3 compliant cryptography)
  • Key rotation & expiration
  • Role-Based Access Control (RBAC) implementation:
.layer(middleware::from_fn(|req, next| 
    authorize(req, next, vec![1, 2]) // Admin+Mod roles
))

PostgreSQL Integration

Relational data made simple

  • SQLx-powered async database operations
  • Migration system with transactional safety
  • Connection pooling for high concurrency

Performance Optimizations

Engineered for speed at scale

  • Brotli compression (11-level optimization)
  • Intelligent request caching strategies
  • Zero-copy deserialization pipelines

Operational Visibility

Production monitoring made easy

  • Docker-healthcheck compatible endpoint:
{
  "status": "degraded",
  "details": {
    "database": {"status": "ok"},
    "memory": {"available_mb": 21613, "status": "normal"},
    "cpu_usage": {"available_percentage": "9.85", "status": "low"}, 
    "disk_usage": {"used_percentage": "74.00", "status": "ok"}
  }
}

Developer Ergonomics

Code with confidence

  • Context-aware user injection system:
async fn create_todo(
    Extension(User { id, role, .. }): Extension<User>, // Auto-injected
    Json(payload): Json<TodoRequest>
) -> Result<impl IntoResponse> {
    // Business logic with direct user context
}
  • Structured logging with OpenTelemetry integration
  • Compile-time configuration validation

Maintenance & Compliance

Future-proof codebase management

  • Security-focused dependency tree (cargo-audit compliant)
  • Comprehensive inline documentation:
/// JWT middleware - Validates Authorization header
/// # Arguments
/// * `req` - Incoming request
/// * `next` - Next middleware layer
/// # Security
/// - Validates Bearer token format
/// - Checks token expiration
/// - Verifies cryptographic signature

πŸ› οΈ Technology stack

Category Key Technologies
Web Framework Axum 0.8 + Tower
Database PostgreSQL + SQLx 0.8
Security JWT + Argon2 + Rustls
Monitoring Tracing + Sysinfo

πŸ“‚ Project structure

axium/                              # Root project directory
β”œβ”€β”€ πŸ“ migrations/                  # Database schema migrations (SQLx)
β”‚
β”œβ”€β”€ πŸ“ src/                         # Application source code
β”‚   β”œβ”€β”€ πŸ“ core/                    # Core application infrastructure
β”‚   β”‚   β”œβ”€β”€ config.rs               # Configuration loader (.env, env vars)
β”‚   β”‚   └── server.rs               # HTTP/HTTPS server initialization
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ database/                # Database access layer
β”‚   β”‚   β”œβ”€β”€ connection.rs           # Connection pool management
β”‚   β”‚   β”œβ”€β”€ queries/                # SQL query modules
β”‚   β”‚   └── models.rs               # Database entity definitions
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ middlewares/             # Axum middleware components
β”‚   β”œβ”€β”€ πŸ“ routes/                  # API endpoint routing
β”‚   β”‚   └── mod.rs                  # Route aggregator
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ handlers/                # Request handlers
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ utils/                   # Common utilities
β”‚   β”‚
β”‚   └── main.rs                     # Application entry point
β”‚
β”œβ”€β”€ πŸ“„ .env                         # Environment configuration
β”œβ”€β”€ πŸ“„ .env.example                 # Environment template
β”œβ”€β”€ πŸ“„ Dockerfile                   # Production container build
β”œβ”€β”€ πŸ“„ docker-compose.yml           # Local development stack
└── πŸ“„ Cargo.toml                   # Rust dependencies & metadata

Each folder has a detailed README.md file which explains the folder in more detail.

🌐 Default API endpoints

Method Endpoint Auth Required Administrator only Description
POST /signin 🚫 🚫 Authenticate user and get JWT token
GET /protected βœ… 🚫 Test endpoint for authenticated users
GET /health 🚫 🚫 System health check with metrics
Apikey routes
GET /apikeys/all βœ… 🚫 Get all apikeys of the current user.
POST /apikeys/ βœ… 🚫 Create a new apikey.
GET /apikeys/{id} βœ… 🚫 Get an apikey by ID.
DELETE /apikeys/{id} βœ… 🚫 Delete an apikey by ID.
POST /apikeys/rotate/{id} βœ… 🚫 Rotates an API key, disables the old one (grace period 24 hours), returns a new one.
User routes
GET /users/all βœ… βœ… Get all users.
POST /users/ βœ… βœ… Create a new user.
GET /users/{id} βœ… βœ… Get a user by ID.
DELETE /users/{id} βœ… βœ… Delete a user by ID.
Usage routes
GET /usage/lastweek βœ… 🚫 Amount of API calls withim the last week of the current user.
GET /usage/lastday βœ… 🚫 Amount of API calls within last day of the current user.
Todo routes
GET /todos/all βœ… 🚫 Get all todos of the current user.
POST /todos/ βœ… 🚫 Create a new todo.
GET /todos/{id} βœ… 🚫 Get a todo by ID.
DELETE /todos/{id} βœ… 🚫 Delete a todo by ID.

πŸ“¦ Installation & usage

To get started with Axium, you'll need to install it on your system. We provide detailed installation guides for different environments:

  • Docker setup: Follow the instructions in Docker setup guide to run Axium using Docker Compose.
  • Ubuntu setup: For users on Ubuntu or other Debian-based systems, refer to the Ubuntu setup Guide.
  • Windows setup: Windows users can find their setup instructions in the Windows setup guide.

These guides cover cloning the repository, setting up the environment, configuring the database, and running the application.

πŸ” Default accounts

Warning: These accounts should only be used for initial testing. Always change or disable them in production environments.

Email Password Role
[email protected] test User
[email protected] test Administrator

⚠️ Security recommendations:

  1. Rotate passwords immediately after initial setup.
  2. Disable default accounts before deploying to production.
  3. Implement proper user management endpoints.

Administrative password resets

For emergency access recovery only

  1. Database Access
    Connect to PostgreSQL using privileged credentials:

    psql -U admin_user -d axium_db -h localhost  
  2. Secure Hash Generation
    Use the integrated CLI tool (never user online generators):

    cargo run --bin argon2-cli -- "new_password"  
    # Output: $argon2id$v=19$m=19456,t=2,p=1$b2JqZWN0X2lkXzEyMzQ1$R7Zx7Y4W...
  3. Database Update

    UPDATE users  
    SET 
        password_hash = '$argon2id...',  
        updated_at = NOW()  
    WHERE email = '[email protected]';  
  4. Verification

    • Immediately test new credentials
    • Force user password change on next login

βš™οΈ Configuration

Create a .env file in the root of the project or configure the application using environment variables.

Make sure to change the JWT_SECRET_KEY.

# ==============================
# βš™οΈ GENERAL CONFIGURATION
# ==============================
ENVIRONMENT="development" # "production"

# ==============================
# 🌍 SERVER CONFIGURATION
# ==============================

# IP address the server will bind to (0.0.0.0 allows all network interfaces)
SERVER_IP="0.0.0.0"

# Port the server will listen on
SERVER_PORT="3000"

# Enable tracing for debugging/logging (true/false)
SERVER_TRACE_ENABLED=true

# Amount of threads used to run the server
SERVER_WORKER_THREADS=2


# ==============================
# πŸ›’οΈ DATABASE CONFIGURATION
# ==============================

# PostgreSQL connection URL (format: postgres://user:password@host/database)
DATABASE_URL="postgres://postgres:1234@localhost/database_name"

# Maximum number of connections in the database pool
DATABASE_MAX_CONNECTIONS=20

# Minimum number of connections in the database pool
DATABASE_MIN_CONNECTIONS=5


# ==============================
# πŸ”’ HTTPS CONFIGURATION
# ==============================

# Enable HTTPS (true/false)
SERVER_HTTPS_ENABLED=false

# Enable HTTP/2 when using HTTPS (true/false)
SERVER_HTTPS_HTTP2_ENABLED=true

# Path to the SSL certificate file (only used if SERVER_HTTPS_ENABLED=true)
SERVER_HTTPS_CERT_FILE_PATH=cert.pem

# Path to the SSL private key file (only used if SERVER_HTTPS_ENABLED=true)
SERVER_HTTPS_KEY_FILE_PATH=key.pem


# ==============================
# 🚦 RATE LIMIT CONFIGURATION
# ==============================

# Maximum number of requests allowed per period
SERVER_RATE_LIMIT=5

# Time period (in seconds) for rate limiting
SERVER_RATE_LIMIT_PERIOD=1


# ==============================
# πŸ“¦ COMPRESSION CONFIGURATION
# ==============================

# Enable Brotli compression (true/false)
SERVER_COMPRESSION_ENABLED=true

# Compression level (valid range: 0-11, where 11 is the highest compression)
SERVER_COMPRESSION_LEVEL=6


# ==============================
# πŸ”‘ AUTHENTICATION CONFIGURATION
# ==============================

# JWT secret key.
JWT_SECRET_KEY="Change me!"

🀝 Contributing

We welcome contributions to the Axium project! Whether it's fixing bugs, improving documentation, or adding new features, your help is greatly appreciated. Please follow these guidelines to ensure a smooth contribution process.

πŸ“ How to Contribute

  1. Fork the Repository
    Start by forking the repository to your own GitHub account.

  2. Clone Your Fork
    Clone your forked repository to your local machine:

    git clone https://github.com/your-username/Axium.git
    cd Axium
  3. Create a New Branch
    Create a new branch for your feature or bug fix:

    git checkout -b feature-name
  4. Make Your Changes
    Make the necessary changes to the code or documentation. Make sure to write tests for new features and adhere to the existing code style.

  5. Commit Your Changes
    Commit your changes with a clear, descriptive message:

    git commit -m "Add feature XYZ or fix issue ABC"
  6. Push to Your Fork
    Push your changes to your fork:

    git push origin feature-name
  7. Open a Pull Request
    Open a pull request against the main branch of the original repository. In the description, provide details about the changes you made, the problem they solve, and any testing you performed.

πŸ” Code Style

  • Follow the Rust style guidelines outlined in the Rust Style Guide.
  • Use cargo fmt to automatically format your code:
    cargo fmt
  • Write meaningful commit messages that describe the changes you've made.

πŸ› οΈ Reporting Bugs

If you encounter a bug or issue, please check if it has already been reported in the GitHub issues. If not, create a new issue, providing the following information:

  • A clear description of the problem.
  • Steps to reproduce the issue.
  • Expected vs. actual behavior.
  • Any relevant logs or error messages.

πŸ’¬ Discussion

Feel free to open discussions in the Discussions section for general questions, ideas, or advice on how to improve the project.

πŸ§‘β€πŸ’» Code of Conduct

Please be respectful and follow the Code of Conduct while interacting with other contributors. Let's maintain a positive and welcoming environment.

πŸŽ‰ Thanks for Contributing!

Your contributions help make Axium better for everyone! πŸ™