Skip to content

feat(backend): security, health checks, graceful shutdown, and contribution guide - #505

Merged
ritik4ever merged 1 commit into
ritik4ever:mainfrom
williamedvard:backend-security-health-graceful-shutdown
Jun 29, 2026
Merged

feat(backend): security, health checks, graceful shutdown, and contribution guide#505
ritik4ever merged 1 commit into
ritik4ever:mainfrom
williamedvard:backend-security-health-graceful-shutdown

Conversation

@williamedvard

@williamedvard williamedvard commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Summary

Implemented backend security hardening with helmet middleware, comprehensive health checks, graceful shutdown handling, and expanded contribution documentation.

Issues Resolved

Closes #224
Closes #226
Closes #227
Closes #228

Changes

Issue #224: Add helmet security headers to Express app

  • Helmet Integration: Installed and configured helmet middleware as the first middleware
  • CSP Configuration: Set Content-Security-Policy to default-src 'none' for API-only responses
  • X-Powered-By Removal: Automatically removed by helmet
  • Additional Headers: HSTS, X-Frame-Options, and other security headers configured
  • Tests: Added comprehensive tests for all security headers

Issue #226: Expand CONTRIBUTING.md with backend setup

  • Prerequisites Section: Clear documentation of Node.js and npm requirements
  • Setup Instructions: Step-by-step guide for environment configuration
  • Environment Variables: Detailed explanation of all backend config options
  • Running Backend: Development mode, production mode, and watch mode commands
  • Testing Guide: Instructions for running tests, watch mode, and coverage reports
  • Database: Seeding, viewing, and resetting instructions
  • Troubleshooting: Common issues (SQLITE_CANTOPEN, database locked, port conflicts) with solutions

Issue #227: Add GET /api/health/deep endpoint

  • Component Checks:
    • SQLite database: reachability and read capability
    • Soroban RPC: HTTP endpoint accessibility (5-second timeout)
    • Contract: CONFIG validation (CONTRACT_ID presence)
  • Response Format:
    • overall: 'up' or 'down'
    • components: Per-component status with details
    • timestamp: ISO 8601 timestamp
    • uptimeSeconds: Server uptime
  • Status Codes: Returns 200 if all components up, 503 if any critical component down
  • Rate Limiting: Endpoint has separate rate limit bucket to prevent abuse

Issue #228: Add graceful shutdown to Express server

  • Signal Handling: Catches SIGTERM and SIGINT signals
  • Grace Period: 10-second window for in-flight requests to complete
  • Service Unavailable: New incoming requests return 503 during shutdown
  • Database Cleanup: SQLite connection explicitly closed before process exit
  • Logging: Shutdown events logged with appropriate levels
  • Docker Compatible: Works with Docker's stop_grace_period

Technical Details

Middleware Order

  • Helmet (security headers)
  • CORS (cross-origin requests)
  • Compression (response compression)
  • Express.json (body parser)
  • API Key Auth (production only)
  • Cache (production only)
  • Rate Limiter
  • Request ID
  • Shutdown check middleware

Health Check Hierarchy

  1. Regular /api/health: Basic SQLite reachability
  2. Deep /api/health/deep: Full dependency verification
    • Excluded from rate limiting to allow monitoring tools unrestricted access
    • Component-level failure reporting for debugging

Database Update

  • Modified checkDbHealth() to include error details for deep health checks
  • Maintains backward compatibility with existing health endpoint

Testing

  • Security headers test: Verifies all helmet headers are present
  • Deep health endpoint tests: Component status and response format validation
  • Graceful shutdown tested manually (signal handling)

Acceptance Criteria

  • ✅ Helmet middleware installed and configured as first middleware
  • ✅ CSP set to default-src 'none' for API
  • ✅ X-Powered-By header removed
  • ✅ Security header test coverage added
  • ✅ CONTRIBUTING.md includes complete backend dev setup
  • ✅ Backend dev setup includes env vars, test commands, seed instructions
  • ✅ Troubleshooting section covers common SQLite errors
  • ✅ Deep health endpoint checks SQLite, Soroban RPC, CONTRACT_ID
  • ✅ Returns per-component status with details
  • ✅ Returns 503 if any critical component down
  • ✅ Excluded from rate limiting
  • ✅ SIGTERM/SIGINT signal handling implemented
  • ✅ 10-second grace period for shutdown
  • ✅ New requests return 503 during shutdown
  • ✅ Database connection explicitly closed

Summary by CodeRabbit

  • New Features

    • Added a deeper health status check that reports overall service health and component-level status, including database, external service reachability, and configuration presence.
    • Improved server shutdown handling so new requests are rejected during shutdown and the service exits more cleanly.
  • Bug Fixes

    • Health checks now provide clearer error details when a database check fails.
    • Added stronger security headers to the app.
  • Documentation

    • Expanded backend setup, testing, database, and troubleshooting guidance.

…ceful shutdown, and contributing guide

- feat(security): integrate helmet middleware with CSP configured for API-only responses
- feat(health): add GET /api/health/deep endpoint with per-component status checks
  - Checks SQLite database reachability and read/write capability
  - Verifies Soroban RPC endpoint accessibility
  - Validates CONTRACT_ID configuration
  - Returns 503 if any critical component is down
- feat(shutdown): implement graceful shutdown handling for SIGTERM/SIGINT signals
  - 10-second grace period for in-flight requests to complete
  - New requests receive 503 Service Unavailable during shutdown
  - Explicit database connection closure before exit
- docs(contributing): expand CONTRIBUTING.md with detailed backend setup section
  - Node.js and npm prerequisites
  - Environment variable configuration guide
  - Development server startup instructions
  - Test running (watch mode and coverage)
  - Database seeding and troubleshooting guide
- deps: add helmet package for security headers
- test(security): add comprehensive tests for helmet headers and deep health endpoint
@vercel

vercel Bot commented Jun 29, 2026

Copy link
Copy Markdown

@williamedvard is attempting to deploy a commit to the ritik4ever's projects Team on Vercel.

A member of the Team first needs to authorize it.

@drips-wave

drips-wave Bot commented Jun 29, 2026

Copy link
Copy Markdown

@williamedvard Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: eaeb6191-5543-47ad-b87b-cf581ad63542

📥 Commits

Reviewing files that changed from the base of the PR and between 3e92b9c and f8f68b3.

📒 Files selected for processing (5)
  • CONTRIBUTING.md
  • backend/package.json
  • backend/src/index.ts
  • backend/src/security.test.ts
  • backend/src/services/db.ts

📝 Walkthrough

Walkthrough

Adds helmet security middleware with restrictive CSP, a new GET /api/health/deep endpoint aggregating DB, Soroban RPC, and contract ID checks, graceful SIGTERM/SIGINT shutdown with 503 rejection during drain, error detail in checkDbHealth, a new security/health test suite, and expanded CONTRIBUTING.md backend setup documentation.

Changes

Backend Security and Ops

Layer / File(s) Summary
Helmet dependency and middleware wiring
backend/package.json, backend/src/index.ts
Adds helmet and @types/helmet to package.json, switches to createServer from http, and registers helmet with default-src 'none' CSP as first Express middleware.
checkDbHealth error detail
backend/src/services/db.ts
Extends checkDbHealth return type with optional error?: string and populates it from caught exception messages on failure.
GET /api/health/deep endpoint
backend/src/index.ts
Adds async, rate-limited deep health route that aggregates DB reachability, Soroban RPC getHealth (5s timeout), and CONTRACT_ID presence into a { overall, components } response; returns 503 on any failure.
Graceful shutdown on SIGTERM/SIGINT
backend/src/index.ts
Introduces isShuttingDown flag, middleware returning 503 during drain, gracefulShutdown closing the HTTP server with a 10s force-exit timer, wired to SIGTERM/SIGINT; startServer() now returns the server instance.
Security headers and deep health tests
backend/src/security.test.ts
Adds test suite asserting Helmet headers on /api/health and verifying /api/health/deep response shape, per-component fields, contract status, timestamp, and 503 on overall: down.

CONTRIBUTING.md Backend Docs

Layer / File(s) Summary
Backend dev setup and troubleshooting
CONTRIBUTING.md
Adds backend prerequisites, setup steps, run modes, test/watch/coverage commands, database seeding/viewing/reset instructions, and troubleshooting subsections; updates test command to npm test.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HealthDeepRoute as GET /api/health/deep
  participant checkDbHealth
  participant SorobanRPC as Soroban RPC (getHealth)

  Client->>HealthDeepRoute: GET /api/health/deep
  HealthDeepRoute->>checkDbHealth: check DB reachability
  checkDbHealth-->>HealthDeepRoute: {status, reachable, error?}
  HealthDeepRoute->>SorobanRPC: fetch getHealth (5s timeout)
  SorobanRPC-->>HealthDeepRoute: ok or throws
  HealthDeepRoute-->>Client: 200 {overall, components: {db, soroban, contract}} or 503
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐇 Hop, hop, helmet on!
No headers left unguarded,
Deep health checks the DB and beyond,
SIGTERM? We shut down graceful and fond.
The docs now guide each new dev along~

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed: one or more packages not found in the registry.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Warning

⚠️ This pull request shows signs of AI-generated slop (trivial_assertion). It has been flagged by CodeRabbit slop detection and should be reviewed carefully.

@ritik4ever
ritik4ever merged commit 8f68e03 into ritik4ever:main Jun 29, 2026
1 of 16 checks passed
Comment thread backend/src/index.ts
import "dotenv/config";
import express, { Request, Response } from "express";
import helmet from "helmet";
import http, { Server } from "http";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants