The IP Whitelist Manager is a robust, backend-only application designed to provide a secure and efficient way to manage and enforce IP-based access restrictions for various services and endpoints. Built with Node.js and Express.js, it exposes a suite of RESTful APIs to handle IP whitelist CRUD operations, associate IPs with specific services, and control access based on client IP addresses.
This project implements all core requirements and several bonus features to deliver a comprehensive IP management solution.
-
User Authentication (JWT-based):
- Securely registers and authenticates users using JSON Web Tokens (JWT).
- Implements a robust authentication flow with both short-lived Access Tokens and long-lived Refresh Tokens for enhanced security and seamless user experience.
- Endpoints protected by
verifyJWTmiddleware.
-
IP Whitelist CRUD:
- Create: Add new IP addresses or CIDR ranges.
- Read: Retrieve single or multiple whitelisted entries with pagination and filtering.
- Update: Modify existing whitelist entries.
- Delete: Remove whitelist entries.
-
Service Association:
- Whitelisted IPs can be explicitly associated with specific
serviceNameidentifiers, allowing granular control over which IPs can access which parts of your system.
- Whitelisted IPs can be explicitly associated with specific
-
Access Middleware:
- A custom middleware (
enforceIpWhitelist) restricts API access based on the client's IP address and its association with a requested service, ensuring only authorized IPs can reach sensitive endpoints.
- A custom middleware (
-
Audit Logging:
- Comprehensive logging of all critical events, including:
- Whitelist modifications (create, update, delete).
- Access attempts (granted or denied).
- User authentication events (login, register, failed attempts).
- Logs include timestamps, user information, IP addresses, and detailed context.
- Comprehensive logging of all critical events, including:
-
Pagination and Filtering:
- The
GET /api/v1/whitelistendpoint supports pagination (page,limit) and filtering (search,serviceName) for efficient data retrieval.
- The
-
API Documentation (OpenAPI/Swagger):
- Comprehensive and interactive API documentation is generated using
swagger-jsdocand served viaswagger-ui-express.
- Comprehensive and interactive API documentation is generated using
-
Environment Configuration:
- Sensitive configuration parameters (e.g., MongoDB URI, JWT secrets, email credentials) are managed securely using environment variables (
dotenv).
- Sensitive configuration parameters (e.g., MongoDB URI, JWT secrets, email credentials) are managed securely using environment variables (
-
Rate Limiting:
- Implemented using
express-rate-limitfor sensitive endpoints like user login and general API access. This helps protect against brute-force attacks and API abuse.
- Implemented using
-
Role-based Access Control (RBAC):
- Differentiates permissions between
adminanduserroles. - The
authorizeRolesmiddleware ensures that onlyadminusers can perform critical operations like creating, updating, or deleting whitelist entries. New user registrations default touserrole unless explicitly set.
- Differentiates permissions between
- Runtime: Node.js (v14+)
- Web Framework: Express.js
- Database: MongoDB
- ODM: Mongoose
- Authentication: JWT (JSON Web Tokens),
bcryptjsfor password hashing - Environment Variables:
dotenv - Validation:
express-validator,ip(for IP/CIDR validation) - API Documentation:
swagger-jsdoc,swagger-ui-express,yamljs - Error Handling: Custom
ApiErrorclass and global error handling middleware for consistent responses. - Asynchronous Operations:
asyncHandlerutility for cleanerasync/awaiterror handling.
Before running the application, ensure you have the following installed:
- Node.js: v14 or higher (nodejs.org)
- npm: (Comes with Node.js)
- MongoDB: A running instance of MongoDB (mongodb.com/try/download/community)
- Postman/Insomnia (Optional): For API testing.
-
Clone the repository:
gh repo clone Vedant005/IP-Whitelist-Manager cd ip-whitelist-manager -
Install Node.js dependencies:
npm install
-
Create and Configure
.envfile:- Create a file named
.envin the root directory of the project. - Copy the contents from
.env.exampleinto your new.envfile. - Crucially, update the placeholder values:
PORT=8000 MONGO_URI=mongodb://localhost:27017/ipwhitelistdb JWT_SECRET=YOUR_SUPER_STRONG_JWT_SECRET_HERE # Make this very long and random JWT_EXPIRES_IN=1h # Access token expiry JWT_REFRESH_SECRET=YOUR_VERY_STRONG_REFRESH_SECRET # Make this very long and random JWT_REFRESH_EXPIRES_IN=7d # Refresh token expiry ADMIN_NOTIFICATION_EMAIL=alerts@yourdomain.com # Email to send security alerts
- Create a file named
-
Ensure MongoDB is running: The application will attempt to connect to the MongoDB instance specified in
MONGO_URI.
- Start the server:
For development with automatic restarts on file changes:
npm start
npm run dev
The server will start on the port specified in your .env file (default: 8000).
Once the server is running, you can access the interactive API documentation at:
http://localhost:8000/api-docs
This documentation provides details on all available endpoints, their request/response formats, security requirements, and allows you to test them directly within your browser.
- Method:
POST - Path:
/api/v1/auth/register - Body:
{ "email": "testuser@example.com", "password": "password123", "role": "user" } - Response:
201 CreatedwithaccessTokenandrefreshToken.
- Method:
POST - Path:
/api/v1/auth/login - Body:
{ "email": "admin@example.com", "password": "adminpassword" }(or your registered user) - Response:
200 OKwithaccessTokenandrefreshToken.- IMPORTANT: Copy the
accessToken. You will use this in theAuthorization: Bearer <accessToken>header for all protected endpoints.
- IMPORTANT: Copy the
- Method:
POST - Path:
/api/v1/auth/refresh-token - Body:
{ "refreshToken": "YOUR_REFRESH_TOKEN" } - Response:
200 OKwith a newaccessToken(and potentially a newrefreshToken).
- Get All Entries:
- Method:
GET - Path:
/api/v1/whitelist - Query Params:
page,limit,search,serviceName - Auth:
Bearer Token(any role)
- Method:
- Create Entry (Admin Only):
- Method:
POST - Path:
/api/v1/whitelist - Body:
{ "ipAddress": "192.168.1.100", "serviceName": "api-gateway", "description": "Office IP" } - Auth:
Bearer Token(adminrole)
- Method:
- Update Entry (Admin Only):
- Method:
PUT - Path:
/api/v1/whitelist/:id - Body:
{ "ipAddress": "192.168.1.101" } - Auth:
Bearer Token(adminrole)
- Method:
- Delete Entry (Admin Only):
- Method:
DELETE - Path:
/api/v1/whitelist/:id - Auth:
Bearer Token(adminrole)
- Method:
These endpoints demonstrate the enforceIpWhitelist middleware in action.
- Protected Resource 1:
- Method:
GET - Path:
/api/v1/service/verifyJWTed-resource-1 - Auth:
Bearer Token+ Client IP must be whitelisted forservice-1
- Method:
- Protected Resource 2:
- Method:
GET - Path:
/api/v1/service/verifyJWTed-resource-2 - Auth:
Bearer Token+ Client IP must be whitelisted forservice-2
- Method:
The API follows a consistent response structure:
- Success:
{ "success": true, "message": "Operation successful", "data": { /* response data */ } } - Error:
Appropriate HTTP status codes are used (e.g.,
{ "success": false, "message": "Descriptive error message", "errors": [ /* optional: array of specific validation errors */ ] }200 OK,201 Created,400 Bad Request,401 Unauthorized,403 Forbidden,404 Not Found,500 Internal Server Error).
Custom ApiError and ApiResponse classes ensure standardization, while a global error handling middleware catches unhandled exceptions, providing clean responses and preventing server crashes.
- All critical system events, access attempts, and modifications are meticulously logged to the MongoDB
AuditLogcollection.
Refer to the interactive Swagger UI (http://localhost:8000/api-docs) for details on each endpoint. Use a tool like Postman or Insomnia to send requests.
Basic Testing Flow:
- Login:
POST /api/v1/auth/loginwithadmin@example.comandadminpasswordto get anaccessToken. - Create Whitelist Entry:
POST /api/v1/whitelistusing theaccessTokenin theAuthorization: Bearer <token>header. Add your current testing machine's IP forservice-1. - Test Access Granted:
GET /api/v1/service/verifyJWTed-resource-1with youraccessToken. - Test Access Denied: Delete the whitelist entry for your IP and
service-1, then retryGET /api/v1/service/verifyJWTed-resource-1. - Explore other endpoints for CRUD, bulk operations, and token refresh.
- Check MongoDB: Verify
auditlogscollection to see all recorded events.
- Advanced Rate Limiting: Implement dynamic rate limiting based on user role or subscription tier.
- Webhooks for Alerts: Send alerts to messaging platforms (e.g., Slack, Teams) instead of/in addition to email.
- Admin Dashboard (Frontend): Develop a simple UI for managing whitelist entries and viewing audit logs.
- IP Geolocation: Integrate a geolocation service to provide more context for IP addresses in audit logs.
- Database Indexes: Add appropriate indexes to MongoDB collections (especially
AuditLogandWhitelistEntry) for performance optimization.