What is GritShield?
GritShield is an async-first, security-hardened web framework for Rust that eliminates the majority of OWASP Top 10 vulnerabilities by design.
Key Features
- Native Default Asynchrony – Built entirely from the ground up on non-blocking
async/awaitdesign patterns, leveraging a multi-threaded Tokio runtime context to sustain massive concurrent execution throughput without thread starvation. - XSS-Safe Templating – Untrusted data cannot reach HTML without explicit sanitisation.
- CSRF Protection – Automatic token validation for state-changing requests.
- Signed Cookies – Cryptographic HMAC-SHA256 signatures prevent client-side cookie tampering.
- Session Management – Thread-safe, in-memory store protected by asynchronous synchronization locks with automatic expiration hooks.
- JWT Support – Stateless authentication via securely managed HS256 tokens.
- Rate Limiting – Sliding-window rate tracking per IP address, backed by low-overhead atomic counters.
- IP Blacklisting – Instantly drops connection sockets for malicious clients directly at the early middleware layer.
- File-Based Routing – Auto-discovery of structural endpoint handlers mapped straight to your local filesystem hierarchy.
Quick Navigation
- Getting Started - First steps with GritShield
- Architecture Overview - Understand the kernel design
- Security Guide - Learn about security features
- Routing Guide - Master the routing system
GritShield Documentation
Installation
Add to your Cargo.toml:
[]
= { = "https://github.com/digiator42/gritshield", = "0.1" }
= { = "1", = ["full"] }
Quick Start – Hello World
Create src/main.rs:
use *;
async
async
Run with cargo run and open http://localhost:8080.
Core Concepts
1. Request Context
There is no more importing this::that or constantly checking the docs just to find out where a feature lives.
Every handler receives a RequestContext that holds the HTTP request, dynamic parameters, session, cookies, parsed form data, JSON body, and security helpers all in one place.
async
2. Routing
-
a) Attribute Macros
async asyncSupported methods:
#[get]#[post]#[put]#[patch]#[delete]
-
b) Manual Registration
router.add_route; -
c) File‑Based Routing (Next.js style)
Place your handlers in
src/pages/:src/pages/index.rs→ route/src/pages/users/[id].rs→ route/users/:idsrc/pages/api/[..path].rs→ route/api/**(catch‑all)
Inside the file, use the
register_page!macro:use *; register_page!;GritShield automatically discovers
.rsfiles undersrc/pagesand mounts them.
3. Middleware Stack
-
Middleware implements the
Middlewaretrait. They run in the order they are added.Built‑in middleware
LoggerMiddleware– logs method, path, status, duration, authentication state.RateLimitMiddleware– sliding‑window rate limiting.IPBlacklistMiddleware– blocks requests from configured IP addresses.AuthMiddleware– session + JWT + CSRF gatekeeper.
Adding custom middleware
; router = router.add_middleware;
4. Responses
Handlers can return any type that implements IntoResponse:
Response– full control over status, headers, cookies.&'static str / String– automatically wrapped as HTML.Result<T, ShieldError>– maps errors to a safe error page.SafeHtml– pre‑sanitised HTML content.
Constructors
new
new;
redirect;
json;
static_file;
5. Static Files
Place files in the static/ folder.
Serve them with:
static_file
Serve static files in one go
async
Directory traversal is prevented automatically.
AuthMiddleware – Session vs JWT
By using AuthMiddleware you have a full authentication system that exposes only /login&/register routes, set signed hmac cookies, generate a new CSRF token immediately, logs out user automatically and redirects unauthenticated users to /login
Session mode (default)
let auth = new_session;
router = router.add_middleware;
Features:
- Creates a signed
GSESSION_IDcookie. - Stores user data in an in‑memory
SessionStore. - Use
ctx.login_user_id("123")to authenticate. ctx.is_user_authenticated()checks login state (expects to setuser_idin session once user login).
JWT stateless mode
let jwt_handler = new;
let auth = new_jwt;
Features:
- Expects
Authorization: Bearer <token>. - Stateless authentication.
- Claims available through
ctx.claims.
CSRF Protection
Enabled automatically in session mode.
HTML forms must include csrf_token value:
Retrieve the token:
let token = ctx.get_csrf_token;
// using maud
render!
Cookies – Signed & Secure
// Read a signed cookie
if let Some = ctx.get_signed_cookie
// Set a signed cookie
let cookie = new
.set_secure
.set_same_site;
ctx.set_signed_cookie;
// Delete a cookie
ctx.remove_cookie;
Unsigned cookies are also available:
ctx.get_cookie
ctx.set_cookie
XSS Prevention
All user input arrives as UntrustedString.
To display safely:
let safe_html = encode;
To return trusted HTML:
trust
Only use for strings you fully control.
Rate Limiting
let limiter = new;
let rate_middleware = RateLimitMiddleware ;
router = router.add_middleware;
IP Blacklisting
let blacklist = new;
router = router.add_middleware;
Database Integration
GritShield integrates with SeaORM.
let db = connect.await.unwrap;
let router = new.mound_db;
Access the connection inside handlers:
async
Request Data Parsing
Supported formats:
- JSON →
ctx.json::<T>() - Form URL‑encoded →
ctx.form.fields - Multipart uploads →
ctx.form.files - Query parameters →
ctx.query - Raw body →
ctx.raw_body
Example file upload
async
Templating
Place templates in the templates/ folder.
use TemplateEngine;
// Precompile templates, this should be used once, then get template will be cashed
precompile_all.unwrap;
// Render template
let html = get;
new
You can integrate with templating crates like Handlebars.
Configuration & Environment
Environment variables are loaded from .env or the system.
Important variables
APP_ENVJWT_SECRET
Access variables
let db_url = get_env;
Telemetry & Logging
Enable request logging:
router = new.mount_logger;
Example log output:
🗲 [200] GET /dashboard ➔ Size: 2.34 KB | Time: 12ms | Auth: 🍪 Session ID: a1b2c3d4
Supports custom telemetry hooks and metrics collection.
Hot Reload (Development)
run_server.await;
Automatically rebuilds and reloads on source changes.
Error Handling
The framework catches errors globally.
Development mode
- Detailed technical information shown.
Production mode
- Generic user‑safe error page.
- Errors logged server‑side.
Custom error handler
router.global_error_handler.handler = Some;
Deployment
Recommended production setup
- Set
APP_ENV=production - Use strong
JWT_SECRET - Use reverse proxy (Nginx/Caddy)
- Compile with
--release
Example Dockerfile
FROM rust:1.70 as builder
WORKDIR /app
COPY . .
RUN cargo build --release
FROM debian:bookworm-slim
COPY --from=builder /app/target/release/myapp /usr/local/bin/
ENV APP_ENV=production
CMD ["myapp"]
Testing Helpers
async
API Reference (Selected)
| Type / Function | Description |
|---|---|
Router::new() |
Creates empty router. |
router.add_route(method, path, handler) |
Manual route registration. |
router.add_middleware(M) |
Appends middleware to the pipeline. |
RequestContext::get_signed_cookie(name) |
Reads signed cookie. |
RequestContext::set_signed_cookie(cookie) |
Writes signed cookie. |
RequestContext::remove_cookie(name) |
Deletes cookie. |
RequestContext::login_user_id(id) |
Sets authenticated user ID. |
RequestContext::get_csrf_token() |
Returns CSRF token. |
Response::redirect(status, location) |
Redirect response. |
Response::json(status, &data) |
Serialises JSON response. |
Sanitizer::encode(UntrustedString) |
Escapes HTML safely. |
Sanitizer::trust(str) |
Creates trusted HTML. |
RateLimiter::new(max, window) |
Creates rate limiter. |
JwtHandler::sign(claims) |
Signs JWT token. |
JwtHandler::verify(token) |
Verifies JWT token. |
TemplateEngine::get(name) |
Returns template content. |
Contributing
GritShield is built with security as the highest priority.
Contributions, bug reports, and security advisories are welcome.
Please open an issue before submitting a PR.
License
Apache‑2.0.