diff --git a/COLOR_SCHEME_MODERNIZATION.md b/COLOR_SCHEME_MODERNIZATION.md deleted file mode 100644 index d2357c5..0000000 --- a/COLOR_SCHEME_MODERNIZATION.md +++ /dev/null @@ -1,79 +0,0 @@ -# CVE Dashboard - Color Scheme Modernization - -## Overview -Successfully modernized the color scheme from retro 80s/neon arcade aesthetic to a professional, sophisticated tactical intelligence platform look. - -## Color Palette Changes - -### Before (Neon/Retro) -- **Accent**: `#00D9FF` - Bright cyan (too neon) -- **Warning**: `#FFB800` - Bright yellow/orange (too saturated) -- **Danger**: `#FF3366` - Neon pink/red -- **Success**: `#00FF88` - Bright green (too bright) -- **Background Dark**: `#0A0E27`, `#131937`, `#1E2749` - -### After (Modern Professional) -- **Accent**: `#0EA5E9` - Sky Blue (professional, refined cyan) -- **Warning**: `#F59E0B` - Amber (sophisticated, warm) -- **Danger**: `#EF4444` - Modern Red (urgent but refined) -- **Success**: `#10B981` - Emerald (professional green) -- **Background Dark**: `#0F172A`, `#1E293B`, `#334155` (Tailwind Slate palette) - -## Design Philosophy - -### Refinement Approach -1. **Reduced Glow Intensity**: Lowered opacity and blur radius on all glows from 0.9 to 0.4-0.5 -2. **Subtler Borders**: Changed from 3px bright borders to 1.5-2px refined borders -3. **Professional Gradients**: Updated background gradients to use slate tones instead of stark blues -4. **Sophisticated Shadows**: Reduced shadow intensity while maintaining depth -5. **Text Shadow Refinement**: Reduced from aggressive glows to subtle halos - -### Key Changes - -#### Severity Badges -- **Critical**: Neon pink → Modern red with refined glow -- **High**: Bright yellow → Amber with warm tones -- **Medium**: Bright cyan → Sky blue professional -- **Low**: Bright green → Emerald sophisticated - -#### Interactive Elements -- **Buttons**: Reduced glow from 25px to 20px radius, lowered opacity -- **Input Fields**: More subtle focus states, refined borders -- **Cards**: Gentler hover effects, professional elevation -- **Stat Cards**: Refined top accent lines, subtle glows - -#### Layout Components -- **Wiki Panel**: Updated to emerald accent with professional borders -- **Calendar**: Sky blue accent with refined styling -- **Tickets Panel**: Amber accent maintaining urgency without neon feel -- **CVE Cards**: Slate-based gradients with professional depth - -## Technical Implementation - -### Files Modified -1. **App.css**: Updated all CSS variables, component styles, and utility classes -2. **App.js**: Updated inline STYLES object and all JSX color references - -### CSS Variables Updated -```css ---intel-darkest: #0F172A ---intel-dark: #1E293B ---intel-medium: #334155 ---intel-accent: #0EA5E9 ---intel-warning: #F59E0B ---intel-danger: #EF4444 ---intel-success: #10B981 ---intel-grid: rgba(14, 165, 233, 0.08) -``` - -### Maintained Features -✓ Pulsing button effects on hover/click -✓ Scanning line animation -✓ Card hover elevations -✓ Badge glow dots -✓ Grid background effect -✓ Three-column layout -✓ All interactive functionality - -## Result -The dashboard now presents a modern, professional tactical intelligence platform aesthetic while preserving all the visual interest, depth, and functionality that made the original design engaging. The color scheme feels premium and sophisticated rather than arcade-like, suitable for enterprise security operations. diff --git a/DESIGN_SYSTEM.md b/DESIGN_SYSTEM.md index fc80a1d..a77f571 100644 --- a/DESIGN_SYSTEM.md +++ b/DESIGN_SYSTEM.md @@ -1,6 +1,6 @@ # CVE Intelligence Dashboard - Design System Reference -## 🎨 Color Palette +## Color Palette ### Primary Colors ```css @@ -33,7 +33,7 @@ | **Medium** | `#0EA5E9` | `rgba(14, 165, 233, 0.25)` | `#7DD3FC` | `#0EA5E9` | | **Low** | `#10B981` | `rgba(16, 185, 129, 0.25)` | `#6EE7B7` | `#10B981` | -## 📐 Layout Structure +## Layout Structure ### Three-Column Grid Layout ``` @@ -60,7 +60,7 @@ - **Desktop (lg+)**: 3-column layout (3-6-3 grid) - **Tablet/Mobile**: Stacked single column -## 🎯 Component Specifications +## Component Specifications ### Stat Cards ```css @@ -117,7 +117,7 @@ Letter Spacing: 0.5px Glow Dot: 8px circle with pulse animation ``` -## ✨ Interactions & Animations +## Interactions & Animations ### Hover Effects - **Cards**: `translateY(-2px)`, enhanced border, subtle glow @@ -151,7 +151,7 @@ Fast: all 0.2s ease Ripple: width/height 0.5s ``` -## 🔤 Typography +## Typography ### Font Families ```css @@ -178,7 +178,7 @@ Accent Headings: 0 0 16px rgba(14, 165, 233, 0.3), 0 0 32px rgba(14, 165, 233, 0 Badge Text: 0 0 8px rgba([color], 0.5) ``` -## 🎨 Visual Effects +## Visual Effects ### Shadows ```css @@ -223,7 +223,7 @@ linear-gradient(rgba(14, 165, 233, 0.025) 1px, transparent 1px) Size: 20px × 20px ``` -## 🧩 Specific Component Patterns +## Specific Component Patterns ### Wiki/Knowledge Base Entry ```css @@ -261,7 +261,7 @@ Chevron: Rotate -90deg (collapsed) to 0deg (expanded) Vendor Cards: Nested with reduced opacity borders ``` -## 📱 Accessibility +## Accessibility ### Contrast Ratios - Primary text on dark: 18.5:1 (AAA) @@ -278,7 +278,7 @@ Vendor Cards: Nested with reduced opacity borders - Line height: 1.5 for body text - Letter spacing: Generous for uppercase labels -## 🎯 Design Principles +## Design Principles 1. **Professional Sophistication**: Modern enterprise feel, not arcade 2. **Tactical Intelligence**: Purpose-driven, information-dense @@ -288,7 +288,3 @@ Vendor Cards: Nested with reduced opacity borders 6. **Monospace Data**: Technical data uses JetBrains Mono for clarity 7. **Generous Spacing**: Breathing room prevents overwhelming density ---- - -**Last Updated**: February 10, 2026 -**Version**: 2.0 (Modern Professional Redesign) diff --git a/README.md b/README.md index 973b985..c1b3d52 100644 --- a/README.md +++ b/README.md @@ -1,1642 +1,515 @@ # CVE Dashboard -A comprehensive vulnerability management system designed for tracking CVE (Common Vulnerabilities and Exposures) remediation status and maintaining vendor documentation compliance. - -![Charter Communications](https://img.shields.io/badge/Charter-Communications-0476D9) -![Version](https://img.shields.io/badge/version-1.1.0-blue) -![License](https://img.shields.io/badge/license-Internal-red) +A self-hosted vulnerability management dashboard for tracking CVE remediation status, maintaining vendor documentation, and managing risk acceptance workflows. --- -## 📋 Table of Contents +## Table of Contents - [Overview](#overview) -- [Key Features](#key-features) -- [Architecture](#architecture) +- [Tech Stack](#tech-stack) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Configuration](#configuration) -- [Usage Guide](#usage-guide) -- [API Documentation](#api-documentation) +- [Running the Application](#running-the-application) +- [Features](#features) +- [API Reference](#api-reference) +- [Architecture](#architecture) - [Database Schema](#database-schema) -- [File Organization](#file-organization) -- [Troubleshooting](#troubleshooting) -- [Roadmap](#roadmap) -- [Contributing](#contributing) -- [Author](#author) +- [Security Model](#security-model) +- [Migrations](#migrations) --- -## 🎯 Overview +## Overview -The CVE Dashboard solves a critical problem in vulnerability management: **quickly determining whether a CVE has been addressed and if required vendor documentation exists** before requesting false positive designations from security teams. +The CVE Dashboard answers a common problem in vulnerability management: before requesting false positive designations, you need to know whether a CVE has already been addressed, and whether the supporting vendor documentation exists. This application provides: -### Problem Statement - -Security teams report vulnerabilities that may not apply to your environment. Before requesting a false positive designation, you need to: -1. ✅ Verify if the CVE has already been addressed -2. ✅ Confirm you have required vendor documentation (advisories, correspondence, proof of remediation) -3. ✅ Maintain organized records for audits and compliance - -### Solution - -This dashboard provides: -- **Instant CVE status verification** via Quick Check -- **Document compliance tracking** to ensure you have required vendor documentation -- **Automated file organization** maintaining the structure: `CVE-ID/Vendor/Documents` -- **Searchable database** with filters for vendor, severity, and status -- **RESTful API** for integration with other systems +- A searchable, filterable CVE list with per-vendor tracking +- Document storage attached to each CVE/vendor pair (advisories, emails, screenshots, patches) +- NVD API integration to auto-populate CVE metadata +- Archer risk acceptance ticket tracking (EXC numbers) +- Weekly vulnerability report upload and processing +- A knowledge base for internal documentation and policies +- Role-based access control with a full audit trail --- -## ✨ Key Features +## Tech Stack -### 🔐 User Authentication & Roles -- **Secure login**: Session-based authentication with encrypted passwords -- **Role-based access control**: Three user roles with different permissions - - **Admin**: Full access including user management and document deletion - - **Editor**: Can add/edit CVEs and upload documents - - **Viewer**: Read-only access to CVEs and documents -- **User management**: Admins can create, edit, and deactivate users -- **Session persistence**: Stay logged in across browser sessions (24-hour expiry) - -### 🔍 Quick CVE Status Check -- **Instant verification**: Enter any CVE ID and immediately see if it's been addressed -- **Multi-vendor display**: Shows all vendors associated with a CVE -- **Document compliance**: Shows which documents are present per vendor (Advisory ✓, Email ○, Screenshot ○) -- **Visual indicators**: Color-coded results (green = addressed, yellow = not found, red = missing required docs) - -### 📂 Document Management -- **Upload documents**: PDF, images, Word docs, text files (up to 10MB) -- **Automatic organization**: Files stored as `uploads/CVE-2024-1234/Microsoft/advisory.pdf` -- **Per-vendor storage**: Each vendor's documents are organized separately -- **Document types**: Advisory, Email, Screenshot, Patch, Other -- **View & Delete**: Direct links to view documents, admin-only deletion - -### 🏢 Multi-Vendor Support -- **Same CVE, multiple vendors**: Track a single CVE across different vendors (e.g., CVE-2024-1234 for both Microsoft and Cisco) -- **Vendor-specific tracking**: Each vendor entry has its own status, documents, and compliance -- **Flexible organization**: Documents organized by CVE ID and vendor - -### 🔎 Search & Filter -- **Search by CVE ID or description**: Find vulnerabilities quickly -- **Filter by vendor**: Microsoft, Cisco, Oracle, VMware, Adobe, etc. -- **Filter by severity**: Critical, High, Medium, Low -- **Real-time results**: Updates as you type - -### 📊 Compliance Tracking -- **Document status badges**: "✓ Docs Complete" or "⚠ Incomplete" -- **Required documents**: Advisory (mandatory), Email (optional), Screenshot (optional) -- **Vendor-specific requirements**: Customizable per vendor -- **Per-vendor compliance**: Track documentation status for each vendor separately - -### 🎨 Charter/Spectrum Branding -- **Corporate colors**: Charter Blue (#0476D9) throughout -- **Professional design**: Clean, modern interface -- **Responsive layout**: Works on desktop and tablets +| Layer | Technology | +|---|---| +| Backend | Node.js, Express 5 | +| Database | SQLite3 | +| File uploads | Multer 2 | +| Auth | bcryptjs, cookie-based sessions | +| Frontend | React 19, lucide-react, react-markdown | +| Report processing | Python 3 (pandas, openpyxl) | --- -## 🏗️ Architecture -``` -┌─────────────────────────────────────────────────────────┐ -│ CVE Dashboard │ -├─────────────────────────────────────────────────────────┤ -│ │ -│ ┌──────────────┐ ┌──────────────────────┐ │ -│ │ Frontend │ │ Backend API │ │ -│ │ │ HTTP │ │ │ -│ │ React + │◄───────►│ Express.js │ │ -│ │ Tailwind │ :3001 │ + Auth Middleware │ │ -│ │ │ │ │ │ -│ │ Port: 3000 │ │ ┌─────────────────┐ │ │ -│ └──────────────┘ │ │ SQLite DB │ │ │ -│ │ │ - cves │ │ │ -│ │ │ - documents │ │ │ -│ │ │ - required_docs│ │ │ -│ │ │ - users │ │ │ -│ │ │ - sessions │ │ │ -│ │ └─────────────────┘ │ │ -│ └──────────────────────┘ │ -│ │ │ -│ ▼ │ -│ ┌──────────────────────┐ │ -│ │ File Storage │ │ -│ │ │ │ -│ │ uploads/ │ │ -│ │ └─ CVE-2024-1234/ │ │ -│ │ ├─ Microsoft/ │ │ -│ │ │ └─ advisory.pdf│ │ -│ │ └─ Cisco/ │ │ -│ │ └─ advisory.pdf│ │ -│ └──────────────────────┘ │ -└─────────────────────────────────────────────────────────┘ -``` +## Prerequisites -### Technology Stack - -**Frontend:** -- React 18 -- Tailwind CSS (via CDN) -- Lucide React (icons) -- Fetch API -- Context API (AuthContext) - -**Backend:** -- Node.js v18+ -- Express.js 4 -- SQLite3 -- Multer (file uploads) -- CORS -- bcryptjs (password hashing) -- cookie-parser (session management) -- dotenv (environment configuration) - -**Database:** -- SQLite (development/production) -- Easily upgradeable to PostgreSQL +- Node.js 18 or later +- npm +- Python 3 with pip (required only for weekly report processing) --- -## 📦 Prerequisites +## Installation -- **Node.js**: v18.0.0 or higher -- **npm**: v8.0.0 or higher -- **Git**: For version control -- **Linux/Unix environment**: Tested on Ubuntu 20.04+ +### 1. Clone the repository -Check your versions: ```bash -node --version -npm --version -git --version -``` - ---- - -## 🚀 Installation - -### 1. Clone the Repository -```bash -git clone https://vulcan.apophisnetworking.net/jramos/cve-dashboard.git +git clone cd cve-dashboard ``` -### 2. Install Backend Dependencies +### 2. Install backend dependencies + ```bash cd backend npm install ``` -Expected packages: -- express -- sqlite3 -- multer -- cors -- bcryptjs -- cookie-parser -- dotenv +The root `package.json` lists the backend dependencies. Install them from the `backend/` directory where `server.js` lives. + +### 3. Install frontend dependencies -### 3. Install Frontend Dependencies ```bash -cd ../frontend +cd frontend npm install ``` -Expected packages: -- react -- react-dom -- react-scripts -- lucide-react +### 4. Install Python dependencies (for weekly report upload feature) -### 4. Initialize the Database ```bash -cd ../backend +cd backend/scripts +pip install -r requirements.txt +``` + +Required packages: `pandas>=2.0.0`, `openpyxl>=3.0.0` + +### 5. Initialize the database + +Run this once from the `backend/` directory to create the SQLite database, all tables, indexes, the uploads directory, and a default admin user: + +```bash +cd backend node setup.js ``` -This will: -- ✅ Create `cve_database.db` -- ✅ Create tables: `cves`, `documents`, `required_documents`, `users`, `sessions` -- ✅ Set up multi-vendor support with UNIQUE(cve_id, vendor) constraint -- ✅ Create indexes for fast queries -- ✅ Create `cve_document_status` view -- ✅ Create `uploads/` directory -- ✅ Insert default required documents for major vendors -- ✅ Create default admin user (admin/admin123) +This creates `backend/cve_database.db` and a default admin account: +- Username: `admin` +- Password: `admin123` -Expected output: -``` -🚀 CVE Database Setup (Multi-Vendor Support) +**Change the admin password immediately after first login.** -════════════════════════════════════════ +### 6. Run database migrations -✓ Uploads directory already exists -✓ Database initialized successfully -✓ Created default admin user (admin/admin123) +After the initial setup, apply the feature migrations in order: -📝 Adding sample CVE data for testing... - ✓ Added sample: CVE-2024-SAMPLE-1 / Microsoft - ✓ Added sample: CVE-2024-SAMPLE-1 / Cisco -ℹ️ Sample data added - demonstrates multi-vendor support - -╔════════════════════════════════════════════════════════╗ -║ CVE DATABASE SETUP COMPLETE! ║ -╚════════════════════════════════════════════════════════╝ -``` - -### 5. Configure Environment Variables - -Run the environment setup script to configure server IP addresses: ```bash cd backend -chmod +x setup-env.sh -./setup-env.sh +node migrations/add_weekly_reports_table.js +node migrations/add_knowledge_base_table.js +node migrations/add_archer_tickets_table.js ``` -The script will: -- Auto-detect your server's IP address -- Create `backend/.env` with CORS and API settings -- Create `frontend/.env` with API base URL +--- -**Manual Configuration (Alternative):** +## Configuration -Create `backend/.env`: -```bash -# Backend Configuration +The application is configured via `.env` files. These files are gitignored and must be created manually per environment. + +### Backend: `backend/.env` + +``` PORT=3001 -API_HOST=YOUR_SERVER_IP -CORS_ORIGINS=http://YOUR_SERVER_IP:3000 -SESSION_SECRET=your-secure-secret-key +API_HOST=localhost +CORS_ORIGINS=http://YOUR_IP:3000 +SESSION_SECRET=change-this-to-a-random-secret +NODE_ENV=development + +# Optional: NVD API key for higher rate limits +# Register at https://nvd.nist.gov/developers/request-an-api-key +NVD_API_KEY=your-key-here ``` -Create `frontend/.env`: +### Frontend: `frontend/.env` + +``` +REACT_APP_API_BASE=http://YOUR_IP:3001/api +REACT_APP_API_HOST=http://YOUR_IP:3001 +``` + +Replace `YOUR_IP` with the machine's IP address or `localhost` for local development. + +**Important:** React caches environment variables at build/start time. After changing `frontend/.env`, you must fully restart the frontend process. A page refresh alone is not sufficient. + +--- + +## Running the Application + +### Using the helper scripts (recommended) + +From the project root: + ```bash -# Frontend Configuration -REACT_APP_API_BASE=http://YOUR_SERVER_IP:3001/api -REACT_APP_API_HOST=http://YOUR_SERVER_IP:3001 +./start-servers.sh # Starts backend and frontend in the background +./stop-servers.sh # Stops all servers ``` -### 6. Add Tailwind CSS to Frontend +The start script saves PIDs to `backend.pid` and `frontend.pid`. Logs are written to `backend/backend.log` and `frontend/frontend.log`. -Edit `frontend/public/index.html` and add this line in the `` section: -```html - -``` +### Running manually -### 7. Create Startup Scripts (Optional but Recommended) - -**Create start-servers.sh:** ```bash -cd /home/cve-dashboard -cat > start-servers.sh << 'EOF' -#!/bin/bash -echo "Starting CVE Dashboard servers..." - -# Start backend +# Terminal 1 - backend cd backend -nohup node server.js > backend.log 2>&1 & -BACKEND_PID=$! -echo "Backend started (PID: $BACKEND_PID)" - -# Start frontend -cd ../frontend -nohup npm start > frontend.log 2>&1 & -FRONTEND_PID=$! -echo "Frontend started (PID: $FRONTEND_PID)" - -# Save PIDs -echo $BACKEND_PID > ../backend.pid -echo $FRONTEND_PID > ../frontend.pid - -echo "✓ Both servers running in background" -echo " Backend: http://localhost:3001" -echo " Frontend: http://localhost:3000" -EOF - -chmod +x start-servers.sh -``` - -**Create stop-servers.sh:** -```bash -cat > stop-servers.sh << 'EOF' -#!/bin/bash -echo "Stopping CVE Dashboard servers..." - -if [ -f backend.pid ]; then - kill $(cat backend.pid) 2>/dev/null - rm backend.pid - echo "✓ Backend stopped" -fi - -if [ -f frontend.pid ]; then - kill $(cat frontend.pid) 2>/dev/null - rm frontend.pid - echo "✓ Frontend stopped" -fi - -pkill -f "node server.js" -pkill -f "react-scripts start" -echo "All servers stopped" -EOF - -chmod +x stop-servers.sh -``` - ---- - -## ⚙️ Configuration - -### Backend Configuration - -**Environment Variables** (`backend/.env`): -```bash -PORT=3001 # API server port -API_HOST=192.168.2.117 # Server IP address -CORS_ORIGINS=http://192.168.2.117:3000 # Allowed frontend origins (comma-separated) -SESSION_SECRET=your-secure-secret # Session encryption key -``` - -**File Upload Limits** (`backend/server.js`): -```javascript -const upload = multer({ - storage: storage, - limits: { fileSize: 10 * 1024 * 1024 } // 10MB limit -}); -``` - -### Frontend Configuration - -**Environment Variables** (`frontend/.env`): -```bash -REACT_APP_API_BASE=http://192.168.2.117:3001/api # API endpoint with /api path -REACT_APP_API_HOST=http://192.168.2.117:3001 # Base URL for file downloads -``` - -**Severity Levels** (`frontend/src/App.js`): -```javascript -const severityLevels = ['All Severities', 'Critical', 'High', 'Medium', 'Low']; -``` - -### Database Configuration - -**Add Required Documents for New Vendor:** -```bash -sqlite3 backend/cve_database.db -``` -```sql -INSERT INTO required_documents (vendor, document_type, is_mandatory, description) -VALUES ('Adobe', 'advisory', 1, 'Adobe Security Bulletin'); -``` - -**Update CVE Status Values:** - -Modify in `backend/server.js` or directly in database: -- `Open` - CVE identified, not yet addressed -- `Addressed` - CVE has been remediated -- `False Positive Requested` - Submitted to security team -- `False Positive Approved` - Confirmed false positive -- `Closed` - No action required - ---- - -## 📖 Usage Guide - -### Starting the Application - -**Option 1: Manual Start** -```bash -# Terminal 1 - Backend -cd /home/cve-dashboard/backend node server.js -# Terminal 2 - Frontend -cd /home/cve-dashboard/frontend +# Terminal 2 - frontend +cd frontend npm start ``` -**Option 2: Using Startup Scripts** -```bash -cd /home/cve-dashboard -./start-servers.sh -``` +### Default ports -**Access the application:** -- Frontend: `http://YOUR_SERVER_IP:3000` -- Backend API: `http://YOUR_SERVER_IP:3001` - -### Logging In - -1. Navigate to `http://YOUR_SERVER_IP:3000` -2. You'll see the login page -3. Enter credentials: - - **Default admin**: username `admin`, password `admin123` -4. Click **"Sign In"** -5. You'll be redirected to the dashboard - -**First-Time Setup:** -- After initial setup, change the default admin password -- Create additional users based on their roles: - - **Viewers**: Read-only access (security auditors, stakeholders) - - **Editors**: Can add/edit CVEs and upload documents (analysts) - - **Admins**: Full access including user management (team leads) - -### User Management (Admin Only) - -1. Click on your username in the top right -2. Select **"User Management"** -3. From here you can: - - View all users and their roles - - Create new users - - Edit user roles and status - - Deactivate users (soft delete) - -### Adding a New CVE - -**Required Role:** Editor or Admin - -1. Click the **"+ Add New CVE"** button (top right) -2. Fill in the form: - - **CVE ID**: e.g., `CVE-2024-1234` - - **Vendor**: e.g., `Microsoft` - - **Severity**: Critical, High, Medium, or Low - - **Description**: Brief description of the vulnerability - - **Published Date**: Date the CVE was published -3. Click **"Add CVE"** -4. CVE appears in the dashboard immediately - -**Multi-Vendor Note:** You can add the same CVE ID multiple times with different vendors. For example, CVE-2024-1234 can exist for both Microsoft and Cisco with separate tracking. - -### Uploading Documents - -**Required Role:** Editor or Admin - -1. Find the CVE in the list -2. Click **"View Documents"** to expand -3. Click **"Upload New Document"** -4. Select your file (PDF, PNG, JPG, TXT, DOC, DOCX) -5. When prompted, specify: - - **Vendor**: Select the vendor this document applies to - - **Document type**: advisory, email, screenshot, patch, other - - **Notes** (optional): Description or context -6. File uploads and organizes automatically - -**File Organization Example (Multi-Vendor):** -``` -uploads/ -└── CVE-2024-1234/ - ├── Microsoft/ - │ ├── 1706140800000-MS-Security-Advisory.pdf - │ └── 1706140850000-Vendor-Email.pdf - └── Cisco/ - └── 1706140900000-Cisco-Advisory.pdf -``` - -### Using Quick Check - -**Scenario: Security team reports CVE-2024-5678** - -1. Enter `CVE-2024-5678` in the **Quick Check** box -2. Click **"Check Status"** - -**Result A - Already Addressed (Multi-Vendor):** -``` -✓ CVE Addressed - -Vendor: Microsoft -Severity: Critical | Status: Addressed -Documents: 3 attached -✓ Advisory ✓ Email ✓ Screenshot - -Vendor: Cisco -Severity: High | Status: Open -Documents: 1 attached -✓ Advisory ○ Email ○ Screenshot - -Ready for false positive request (Microsoft) -``` - -**Result B - Not Found:** -``` -⚠ Not Found -This CVE has not been addressed yet. -No entry exists in the database. - -Action Required: Create entry and gather vendor documentation -``` - -**Result C - Incomplete:** -``` -✓ CVE Addressed -Vendor: Oracle -Documents: 1 attached -✗ Advisory ○ Email ○ Screenshot - -Missing required advisory - obtain before requesting false positive -``` - -### Searching and Filtering - -**Search by CVE ID or Description:** -- Type in the search box -- Results filter in real-time - -**Filter by Vendor:** -- Select from dropdown: All Vendors, Microsoft, Cisco, Oracle, VMware, Adobe - -**Filter by Severity:** -- Select from dropdown: All Severities, Critical, High, Medium, Low - -**Combine Filters:** -- Search for "remote code" + Vendor: Microsoft + Severity: Critical - -### Viewing Documents - -1. Click **"View Documents"** on any CVE -2. See list of attached documents with: - - Document name - - Type (advisory, email, screenshot) - - File size - - Notes -3. Click **"View"** to open document in new tab -4. Select checkboxes to export multiple documents - -### Deleting Documents (Admin Only) - -1. Expand documents for a CVE -2. Click red **"Delete"** button next to document (only visible to admins) -3. Confirm deletion in popup -4. Document removed from database and filesystem - -### Exporting Documents - -1. Expand documents for one or more CVEs -2. Check boxes next to documents you want to export -3. Click **"Export X Documents for Report"** at top -4. Currently shows alert (ready for integration with report system) +- Frontend: http://localhost:3000 +- Backend API: http://localhost:3001 --- -## 🔌 API Documentation +## Features -Base URL: `http://YOUR_SERVER_IP:3001/api` +### Authentication and User Roles -**Authentication Required:** All endpoints except `/api/auth/login` require authentication via session cookie. +All routes require authentication. Three roles are supported: -### Authentication Endpoints +| Role | Permissions | +|---|---| +| `viewer` | Read-only access to CVEs, documents, weekly reports, knowledge base, Archer tickets | +| `editor` | All viewer permissions plus: create/update CVEs, upload documents, upload weekly reports, manage knowledge base articles, manage Archer tickets | +| `admin` | All editor permissions plus: delete documents, delete weekly reports, manage users, view audit logs | -#### Login -```http -POST /api/auth/login -Content-Type: application/json -``` +Sessions expire after 24 hours. Session tokens are stored in `httpOnly` cookies. -**Body:** -```json -{ - "username": "admin", - "password": "admin123" -} -``` +### CVE Management -**Response:** -```json -{ - "message": "Login successful", - "user": { - "id": 1, - "username": "admin", - "email": "admin@localhost", - "role": "admin" - } -} -``` +- Add CVEs with full metadata: CVE ID, vendor, severity (Critical/High/Medium/Low), description, published date, and status (Open/In Progress/Addressed/Resolved) +- The same CVE ID can be tracked across multiple vendors independently +- Filter the CVE list by search term, vendor, severity, and status +- Edit any field on an existing CVE entry; file paths are updated automatically when CVE ID or vendor changes +- Delete a single vendor entry or all vendor entries for a CVE ID +- Paginated list view to prevent performance issues with large datasets +- Quick Check: look up a CVE ID and see all vendors tracking it with their current status -Sets a session cookie (`session_id`) for subsequent requests. +### NVD Integration -#### Logout -```http -POST /api/auth/logout -``` +- Auto-fill CVE description, severity, and published date from the NIST NVD API 2.0 when adding a new CVE +- Bulk NVD Sync: fetch updated metadata for all CVEs in the database in one operation (editor/admin) +- CVSS severity mapping cascades: v3.1 preferred, then v3.0, then v2.0 +- NVD API key support via `NVD_API_KEY` environment variable for higher rate limits -**Response:** -```json -{ - "message": "Logged out successfully" -} -``` +### Document Management -#### Get Current User -```http -GET /api/auth/me -``` +Documents are attached to a CVE/vendor pair and stored on disk under `backend/uploads///`. -**Response:** -```json -{ - "id": 1, - "username": "admin", - "email": "admin@localhost", - "role": "admin" -} -``` +Supported document types: `advisory`, `email`, `screenshot`, `patch`, `other` -### User Management Endpoints (Admin Only) +Allowed file extensions: PDF, images (PNG, JPG, GIF, BMP, TIFF), Office documents (DOC, DOCX, XLS, XLSX, PPT, PPTX), text files (TXT, MD, CSV, LOG), email files (MSG, EML), and others (RTF, HTML, XML, JSON, YAML, ODF variants). -#### Get All Users -```http -GET /api/users -``` +File size limit: 10 MB per upload. -#### Create User -```http -POST /api/users -Content-Type: application/json -``` +### Weekly Reports -**Body:** -```json -{ - "username": "newuser", - "email": "user@example.com", - "password": "password123", - "role": "editor" -} -``` +Editors and admins can upload weekly vulnerability reports as `.xlsx` files. The report is processed by a Python script (`backend/scripts/split_cve_report.py`) that: -#### Update User -```http -PUT /api/users/:id -Content-Type: application/json -``` +1. Reads the `Vulnerabilities` sheet +2. Splits rows where multiple CVE IDs are comma-separated in the `CVE ID` column into individual rows +3. Saves the processed file alongside the original -#### Delete User -```http -DELETE /api/users/:id -``` +Both the original and processed files can be downloaded from the weekly reports list. Only the most recently uploaded report is marked as current. Admins can delete old report records and their associated files. -### CVE Endpoints +### Archer Risk Acceptance Tickets -#### Get All CVEs -```http -GET /api/cves -``` -**Required Role:** Any authenticated user +Track Archer exception tickets (EXC numbers) linked to specific CVE/vendor pairs. -**Query Parameters:** -- `search` (optional): Search term for CVE ID or description -- `vendor` (optional): Filter by vendor name -- `severity` (optional): Filter by severity level +- EXC number format: `EXC-NNNNN` +- Statuses: `Draft`, `Open`, `Under Review`, `Accepted` +- Optional Archer URL field for deep-linking to the Archer record +- Filter tickets by CVE ID, vendor, or status +- EXC numbers are unique across the system -**Example:** -```bash -curl -b cookies.txt "http://192.168.2.117:3001/api/cves?vendor=Microsoft&severity=Critical" -``` +### Knowledge Base -**Response:** -```json -[ - { - "id": 1, - "cve_id": "CVE-2024-1234", - "vendor": "Microsoft", - "severity": "Critical", - "description": "Remote code execution vulnerability", - "published_date": "2024-01-15", - "status": "Addressed", - "created_at": "2024-01-26 10:30:00", - "updated_at": "2024-01-26 10:30:00", - "document_count": 3, - "doc_status": "Complete" - } -] -``` +A document library for internal reference material such as policies, runbooks, and vendor advisories. -#### Check CVE Status -```http -GET /api/cves/check/:cveId -``` -**Required Role:** Any authenticated user +- Upload documents with a title, optional description, and category +- View documents inline in the browser (PDFs render in an iframe; markdown files are rendered as HTML) +- Download any document +- Filter and browse by category +- Editors and admins can upload and delete; all authenticated users can view -**Example:** -```bash -curl -b cookies.txt "http://192.168.2.117:3001/api/cves/check/CVE-2024-1234" -``` +Allowed file types: PDF, Markdown, TXT, Office documents, HTML, JSON, YAML, and images. -**Response (Found - Multi-Vendor):** -```json -{ - "exists": true, - "vendors": [ - { - "vendor": "Microsoft", - "severity": "Critical", - "status": "Addressed", - "total_documents": 3, - "compliance": { - "advisory": true, - "email": true, - "screenshot": true - } - }, - { - "vendor": "Cisco", - "severity": "High", - "status": "Open", - "total_documents": 1, - "compliance": { - "advisory": true, - "email": false, - "screenshot": false - } - } - ], - "addressed": true, - "has_required_docs": true -} -``` +### User Management (Admin) -**Response (Not Found):** -```json -{ - "exists": false, - "message": "CVE not found - not yet addressed" -} -``` +Admins can create, update, and delete user accounts from the UI. Supported operations: -#### Get Vendors for CVE -```http -GET /api/cves/:cveId/vendors -``` -**Required Role:** Any authenticated user +- Create users with a role assignment +- Change username, email, password, role, or active status +- Deactivating a user immediately invalidates all their active sessions +- Admins cannot demote themselves or deactivate their own account -**Example:** -```bash -curl -b cookies.txt "http://192.168.2.117:3001/api/cves/CVE-2024-1234/vendors" -``` +### Audit Log (Admin) -**Response:** -```json -[ - { - "vendor": "Microsoft", - "severity": "Critical", - "status": "Addressed", - "description": "Remote code execution vulnerability", - "published_date": "2024-01-15" - }, - { - "vendor": "Cisco", - "severity": "High", - "status": "Open", - "description": "Remote code execution vulnerability", - "published_date": "2024-01-15" - } -] -``` - -#### Create CVE -```http -POST /api/cves -Content-Type: application/json -``` -**Required Role:** Editor or Admin - -**Body:** -```json -{ - "cve_id": "CVE-2024-1234", - "vendor": "Microsoft", - "severity": "Critical", - "description": "Remote code execution vulnerability in Windows Server", - "published_date": "2024-01-15" -} -``` - -**Note:** The same CVE ID can be added multiple times with different vendors. The combination of (cve_id, vendor) must be unique. - -**Example:** -```bash -curl -b cookies.txt -X POST http://192.168.2.117:3001/api/cves \ - -H "Content-Type: application/json" \ - -d '{ - "cve_id": "CVE-2024-1234", - "vendor": "Microsoft", - "severity": "Critical", - "description": "Remote code execution vulnerability", - "published_date": "2024-01-15" - }' -``` - -**Response:** -```json -{ - "id": 1, - "cve_id": "CVE-2024-1234", - "message": "CVE created successfully for vendor: Microsoft" -} -``` - -**Error (Duplicate):** -```json -{ - "error": "This CVE already exists for this vendor. Choose a different vendor or update the existing entry." -} -``` - -#### Update CVE Status -```http -PATCH /api/cves/:cveId/status -Content-Type: application/json -``` -**Required Role:** Editor or Admin - -**Body:** -```json -{ - "status": "False Positive Requested" -} -``` - -**Example:** -```bash -curl -b cookies.txt -X PATCH http://192.168.2.117:3001/api/cves/CVE-2024-1234/status \ - -H "Content-Type: application/json" \ - -d '{"status": "False Positive Requested"}' -``` - -### Document Endpoints - -#### Get Documents for CVE -```http -GET /api/cves/:cveId/documents -``` -**Required Role:** Any authenticated user - -**Query Parameters:** -- `vendor` (optional): Filter documents by vendor - -**Example:** -```bash -curl -b cookies.txt "http://192.168.2.117:3001/api/cves/CVE-2024-1234/documents?vendor=Microsoft" -``` - -**Response:** -```json -[ - { - "id": 1, - "cve_id": "CVE-2024-1234", - "vendor": "Microsoft", - "name": "MS-Security-Advisory.pdf", - "type": "advisory", - "file_path": "uploads/CVE-2024-1234/Microsoft/1706140800000-MS-Security-Advisory.pdf", - "file_size": "245.50 KB", - "mime_type": "application/pdf", - "uploaded_at": "2024-01-26 10:35:00", - "notes": "Official Microsoft Security Advisory" - } -] -``` - -#### Upload Document -```http -POST /api/cves/:cveId/documents -Content-Type: multipart/form-data -``` -**Required Role:** Editor or Admin - -**Form Fields:** -- `file`: The file to upload -- `vendor`: Vendor name (required - determines storage folder) -- `type`: Document type (advisory, email, screenshot, patch, other) -- `notes` (optional): Description - -**Example:** -```bash -curl -b cookies.txt -X POST http://192.168.2.117:3001/api/cves/CVE-2024-1234/documents \ - -F "file=@/path/to/advisory.pdf" \ - -F "vendor=Microsoft" \ - -F "type=advisory" \ - -F "notes=Official security advisory" -``` - -**Response:** -```json -{ - "id": 1, - "message": "Document uploaded successfully", - "file": { - "name": "advisory.pdf", - "path": "uploads/CVE-2024-1234/Microsoft/1706140800000-advisory.pdf", - "size": "245.50 KB" - } -} -``` - -#### Delete Document -```http -DELETE /api/documents/:id -``` -**Required Role:** Admin only - -**Example:** -```bash -curl -b cookies.txt -X DELETE http://192.168.2.117:3001/api/documents/1 -``` - -**Response:** -```json -{ - "message": "Document deleted successfully" -} -``` - -### Utility Endpoints - -#### Get All Vendors -```http -GET /api/vendors -``` -**Required Role:** Any authenticated user - -**Example:** -```bash -curl -b cookies.txt "http://192.168.2.117:3001/api/vendors" -``` - -**Response:** -```json -["Microsoft", "Cisco", "Oracle", "VMware", "Adobe"] -``` - -#### Get Statistics -```http -GET /api/stats -``` -**Required Role:** Any authenticated user - -**Example:** -```bash -curl -b cookies.txt "http://192.168.2.117:3001/api/stats" -``` - -**Response:** -```json -{ - "total_cves": 25, - "critical_count": 8, - "addressed_count": 20, - "total_documents": 75, - "compliant_count": 18 -} -``` +Every state-changing action is recorded with the user identity, IP address, action type, target entity, and a before/after details payload. Admins can view the audit log with filtering by user, action type, entity type, and date range. Results are paginated. --- -## 🗄️ Database Schema +## API Reference -### Tables +All endpoints are prefixed with `/api`. All endpoints except `/api/auth/login` and `/api/auth/logout` require a valid session cookie. -#### `cves` -Stores CVE metadata and remediation status. +### Auth -| Column | Type | Description | -|--------|------|-------------| -| id | INTEGER PRIMARY KEY | Auto-incrementing ID | -| cve_id | VARCHAR(20) | CVE identifier (e.g., CVE-2024-1234) | -| vendor | VARCHAR(100) | Vendor name | -| severity | VARCHAR(20) | Critical, High, Medium, Low | -| description | TEXT | Vulnerability description | -| published_date | DATE | Date CVE was published | -| status | VARCHAR(50) | Open, Addressed, False Positive Requested, Closed | -| created_at | TIMESTAMP | Record creation timestamp | -| updated_at | TIMESTAMP | Last update timestamp | +| Method | Path | Auth | Description | +|---|---|---|---| +| POST | `/api/auth/login` | Public | Log in, receive session cookie | +| POST | `/api/auth/logout` | Public | Invalidate session | +| GET | `/api/auth/me` | Session | Get current user info | +| POST | `/api/auth/cleanup-sessions` | Session | Delete expired sessions | -**Unique Constraint:** `UNIQUE(cve_id, vendor)` - Allows same CVE with different vendors +### CVEs -**Indexes:** -- `idx_cve_id` on `cve_id` -- `idx_vendor` on `vendor` -- `idx_severity` on `severity` -- `idx_status` on `status` +| Method | Path | Role | Description | +|---|---|---|---| +| GET | `/api/cves` | viewer+ | List CVEs with optional filters: `search`, `vendor`, `severity`, `status` | +| POST | `/api/cves` | editor+ | Create a new CVE entry | +| PUT | `/api/cves/:id` | editor+ | Update a CVE entry by row ID | +| PATCH | `/api/cves/:cveId/status` | editor+ | Update status for all vendor rows matching a CVE ID | +| DELETE | `/api/cves/:id` | editor+ | Delete a single CVE vendor entry | +| DELETE | `/api/cves/by-cve-id/:cveId` | editor+ | Delete all vendor entries for a CVE ID | +| GET | `/api/cves/check/:cveId` | viewer+ | Quick check: does this CVE exist and what is its status? | +| GET | `/api/cves/distinct-ids` | viewer+ | List all distinct CVE IDs (used by NVD sync) | +| GET | `/api/cves/:cveId/vendors` | viewer+ | List all vendor entries for a specific CVE ID | -#### `documents` -Stores document metadata and file locations. +### Documents -| Column | Type | Description | -|--------|------|-------------| -| id | INTEGER PRIMARY KEY | Auto-incrementing ID | -| cve_id | VARCHAR(20) | CVE identifier | -| vendor | VARCHAR(100) | Vendor name (for per-vendor organization) | -| name | VARCHAR(255) | Original filename | -| type | VARCHAR(50) | advisory, email, screenshot, patch, other | -| file_path | VARCHAR(500) | Path to file on filesystem | -| file_size | VARCHAR(20) | File size (e.g., "245.50 KB") | -| mime_type | VARCHAR(100) | MIME type (e.g., "application/pdf") | -| uploaded_at | TIMESTAMP | Upload timestamp | -| notes | TEXT | Optional notes or description | +| Method | Path | Role | Description | +|---|---|---|---| +| GET | `/api/cves/:cveId/documents` | viewer+ | List documents for a CVE, optionally filtered by `?vendor=` | +| POST | `/api/cves/:cveId/documents` | editor+ | Upload a document for a CVE/vendor pair | +| DELETE | `/api/documents/:id` | admin | Delete a document and its file from disk | -**Foreign Key:** `cve_id` → `cves(cve_id)` ON DELETE CASCADE +### NVD -**Indexes:** -- `idx_doc_cve_id` on `cve_id` -- `idx_doc_vendor` on `vendor` -- `idx_doc_type` on `type` +| Method | Path | Role | Description | +|---|---|---|---| +| GET | `/api/nvd/lookup/:cveId` | viewer+ | Look up a single CVE in the NVD API | +| POST | `/api/cves/nvd-sync` | editor+ | Bulk update CVE metadata from NVD | -#### `users` -Stores user accounts for authentication. +### Weekly Reports -| Column | Type | Description | -|--------|------|-------------| -| id | INTEGER PRIMARY KEY | Auto-incrementing ID | -| username | VARCHAR(50) UNIQUE | Login username | -| email | VARCHAR(255) UNIQUE | User email address | -| password_hash | VARCHAR(255) | bcrypt hashed password | -| role | VARCHAR(20) | admin, editor, or viewer | -| is_active | BOOLEAN | Account active status (1=active, 0=disabled) | -| created_at | TIMESTAMP | Account creation timestamp | -| last_login | TIMESTAMP | Last successful login | +| Method | Path | Role | Description | +|---|---|---|---| +| POST | `/api/weekly-reports/upload` | editor+ | Upload and process a `.xlsx` vulnerability report | +| GET | `/api/weekly-reports` | viewer+ | List all uploaded reports | +| GET | `/api/weekly-reports/:id/download/:type` | viewer+ | Download `original` or `processed` file | +| DELETE | `/api/weekly-reports/:id` | admin | Delete a report record and its files | -**Roles:** -- `admin` - Full access: manage users, delete documents, all CVE operations -- `editor` - Can add/edit CVEs, upload documents -- `viewer` - Read-only access to CVEs and documents +### Knowledge Base -**Indexes:** -- `idx_users_username` on `username` +| Method | Path | Role | Description | +|---|---|---|---| +| POST | `/api/knowledge-base/upload` | editor+ | Upload a new knowledge base document | +| GET | `/api/knowledge-base` | viewer+ | List all articles | +| GET | `/api/knowledge-base/:id` | viewer+ | Get article metadata | +| GET | `/api/knowledge-base/:id/content` | viewer+ | Get file content for inline display | +| GET | `/api/knowledge-base/:id/download` | viewer+ | Download the file | +| DELETE | `/api/knowledge-base/:id` | editor+ | Delete article and file | -#### `sessions` -Stores active user sessions. +### Archer Tickets -| Column | Type | Description | -|--------|------|-------------| -| id | INTEGER PRIMARY KEY | Auto-incrementing ID | -| session_id | VARCHAR(255) UNIQUE | Session token (stored in cookie) | -| user_id | INTEGER | Foreign key to users.id | -| expires_at | TIMESTAMP | Session expiration time | -| created_at | TIMESTAMP | Session creation timestamp | +| Method | Path | Role | Description | +|---|---|---|---| +| GET | `/api/archer-tickets` | viewer+ | List tickets, optional filters: `cve_id`, `vendor`, `status` | +| POST | `/api/archer-tickets` | editor+ | Create a new Archer ticket | +| PUT | `/api/archer-tickets/:id` | editor+ | Update an Archer ticket | +| DELETE | `/api/archer-tickets/:id` | editor+ | Delete an Archer ticket | -**Foreign Key:** `user_id` → `users(id)` ON DELETE CASCADE +### Users (Admin only) -**Indexes:** -- `idx_sessions_session_id` on `session_id` -- `idx_sessions_user_id` on `user_id` -- `idx_sessions_expires` on `expires_at` +| Method | Path | Role | Description | +|---|---|---|---| +| GET | `/api/users` | admin | List all users | +| GET | `/api/users/:id` | admin | Get a single user | +| POST | `/api/users` | admin | Create a user | +| PATCH | `/api/users/:id` | admin | Update a user | +| DELETE | `/api/users/:id` | admin | Delete a user | -#### `required_documents` -Defines which document types are mandatory per vendor. +### Audit Logs (Admin only) -| Column | Type | Description | -|--------|------|-------------| -| id | INTEGER PRIMARY KEY | Auto-incrementing ID | -| vendor | VARCHAR(100) | Vendor name | -| document_type | VARCHAR(50) | advisory, email, screenshot, etc. | -| is_mandatory | BOOLEAN | 1 = required, 0 = optional | -| description | TEXT | Description of requirement | +| Method | Path | Role | Description | +|---|---|---|---| +| GET | `/api/audit-logs` | admin | Paginated audit log with filters | +| GET | `/api/audit-logs/actions` | admin | List distinct action types | -**Default Values:** -```sql -('Microsoft', 'advisory', 1, 'Official Microsoft Security Advisory') -('Cisco', 'advisory', 1, 'Cisco Security Advisory') -('Oracle', 'advisory', 1, 'Oracle Security Alert') -('VMware', 'advisory', 1, 'VMware Security Advisory') -('Adobe', 'advisory', 1, 'Adobe Security Bulletin') -``` +### Utility -### Views - -#### `cve_document_status` -Provides real-time compliance status for each CVE. - -**Columns:** -- `cve_id` -- `vendor` -- `severity` -- `status` -- `total_documents` - Count of all documents -- `advisory_count` - Count of advisory documents -- `email_count` - Count of email documents -- `screenshot_count` - Count of screenshot documents -- `compliance_status` - "Complete" or "Missing Required Docs" - -**Example Query:** -```sql -SELECT * FROM cve_document_status -WHERE compliance_status = 'Missing Required Docs'; -``` - -### Database Queries - -**Find all Critical CVEs without required docs:** -```sql -SELECT c.cve_id, c.vendor, c.description, cd.compliance_status -FROM cves c -JOIN cve_document_status cd ON c.cve_id = cd.cve_id -WHERE c.severity = 'Critical' - AND cd.compliance_status = 'Missing Required Docs'; -``` - -**Get document count by type:** -```sql -SELECT type, COUNT(*) as count -FROM documents -GROUP BY type -ORDER BY count DESC; -``` - -**Find CVEs without any documents:** -```sql -SELECT c.cve_id, c.vendor, c.severity -FROM cves c -LEFT JOIN documents d ON c.cve_id = d.cve_id -WHERE d.id IS NULL; -``` +| Method | Path | Role | Description | +|---|---|---|---| +| GET | `/api/vendors` | viewer+ | List all distinct vendor names | +| GET | `/api/stats` | viewer+ | Dashboard statistics (total CVEs, critical count, addressed count, document count) | --- -## 📁 File Organization +## Architecture -### Directory Structure ``` cve-dashboard/ +├── start-servers.sh # Start backend + frontend in background +├── stop-servers.sh # Stop all servers +│ ├── backend/ -│ ├── server.js # Express API server -│ ├── setup.js # Database initialization script -│ ├── setup-env.sh # Environment configuration script -│ ├── .env # Environment variables (create with setup-env.sh) -│ ├── cve_database.db # SQLite database file -│ ├── package.json # Backend dependencies -│ ├── middleware/ -│ │ └── auth.js # Authentication middleware +│ ├── server.js # Express app, CVE/document endpoints, middleware +│ ├── setup.js # One-time DB initialization and default admin creation +│ ├── cve_database.db # SQLite database (gitignored) +│ ├── uploads/ # File storage (gitignored) +│ │ ├── / +│ │ │ └── / # CVE documents stored here +│ │ ├── weekly_reports/ # Uploaded vulnerability reports +│ │ ├── knowledge_base/ # Knowledge base documents +│ │ └── temp/ # Temporary upload staging directory │ ├── routes/ -│ │ ├── auth.js # Login/logout endpoints -│ │ └── users.js # User management endpoints -│ └── backend.log # Backend log file (if using startup script) +│ │ ├── auth.js # Login, logout, session check +│ │ ├── users.js # User CRUD (admin) +│ │ ├── auditLog.js # Audit log viewer (admin) +│ │ ├── nvdLookup.js # NVD API proxy +│ │ ├── weeklyReports.js # Weekly report upload and management +│ │ ├── knowledgeBase.js # Knowledge base document management +│ │ └── archerTickets.js # Archer EXC ticket CRUD +│ ├── middleware/ +│ │ └── auth.js # requireAuth and requireRole middleware +│ ├── helpers/ +│ │ ├── auditLog.js # logAudit helper +│ │ └── excelProcessor.js # Calls Python script for report processing +│ ├── migrations/ +│ │ ├── add_weekly_reports_table.js +│ │ ├── add_knowledge_base_table.js +│ │ └── add_archer_tickets_table.js +│ └── scripts/ +│ ├── split_cve_report.py # Python: splits multi-CVE rows in Excel reports +│ └── requirements.txt # pandas, openpyxl │ -├── frontend/ -│ ├── public/ -│ │ └── index.html # Main HTML (includes Tailwind CDN) -│ ├── src/ -│ │ ├── App.js # Main React component -│ │ ├── index.js # React entry point -│ │ ├── index.css # Global styles -│ │ ├── components/ -│ │ │ ├── LoginForm.js # Login page component -│ │ │ ├── UserMenu.js # User dropdown menu -│ │ │ └── UserManagement.js # Admin user management -│ │ └── contexts/ -│ │ └── AuthContext.js # Authentication state management -│ ├── .env # Environment variables (create with setup-env.sh) -│ ├── package.json # Frontend dependencies -│ └── frontend.log # Frontend log file (if using startup script) -│ -├── uploads/ # File storage (auto-created) -│ ├── temp/ # Temporary upload directory -│ ├── CVE-2024-1234/ -│ │ ├── Microsoft/ # Vendor-specific folder -│ │ │ ├── 1706140800000-advisory.pdf -│ │ │ └── 1706140850000-email.pdf -│ │ └── Cisco/ # Same CVE, different vendor -│ │ └── 1706140900000-advisory.pdf -│ └── CVE-2024-5678/ -│ └── Oracle/ -│ └── 1706140900000-advisory.pdf -│ -├── .gitignore # Git ignore rules -├── README.md # This file -├── test_cases_auth.md # Authentication test cases -├── start-servers.sh # Startup script -├── stop-servers.sh # Shutdown script -├── backend.pid # Backend process ID (when running) -└── frontend.pid # Frontend process ID (when running) -``` - -### File Naming Convention - -Uploaded files are automatically prefixed with a timestamp: -``` -[unix_timestamp]-[original_filename] - -Example: -1706140800000-MS-Security-Advisory.pdf -``` - -This prevents filename collisions and maintains chronological order. - -### Folder Creation - -Folders are created automatically when: -1. Database is initialized (`uploads/` and `uploads/temp/`) -2. First document is uploaded for a CVE (`uploads/CVE-ID/Vendor/`) - ---- - -## 🔧 Troubleshooting - -### Backend Won't Start - -**Error: `Cannot find module 'express'`** -```bash -cd /home/cve-dashboard/backend -npm install -``` - -**Error: `Port 3001 is already in use`** -```bash -# Find process using port 3001 -netstat -tuln | grep 3001 -# or -lsof -i :3001 - -# Kill the process -kill -9 - -# Or change port in server.js -nano server.js -# Change: const PORT = 3002; -``` - -**Error: `Database locked`** -SQLite allows only one write operation at a time. -```bash -# Check if multiple instances are running -ps aux | grep "node server.js" - -# Kill duplicate processes -pkill -f "node server.js" - -# Restart -node server.js -``` - -### Frontend Won't Start - -**Error: `Cannot find module 'lucide-react'`** -```bash -cd /home/cve-dashboard/frontend -npm install lucide-react -``` - -**Error: `Port 3000 is already in use`** -```bash -# Kill process on port 3000 -lsof -i :3000 -kill -9 - -# Or set different port -export PORT=3001 -npm start -``` - -**Styling Not Appearing** -Make sure Tailwind CDN is in `public/index.html`: -```html - -``` - -### Upload Issues - -**Error: `Failed to fetch` during upload** - -1. **Check CORS configuration:** -```bash -nano backend/server.js -``` -Ensure CORS allows your frontend origin: -```javascript -app.use(cors({ - origin: ['http://localhost:3000', 'http://192.168.2.117:3000'], - credentials: true -})); -``` - -2. **Check upload directory permissions:** -```bash -chmod -R 755 uploads/ -mkdir -p uploads/temp -``` - -3. **Check backend logs:** -```bash -tail -f backend/backend.log -``` - -**Error: `CVE ID and Vendor are required`** - -This means form data isn't reaching the backend. Check: -1. Frontend is sending `cveId` and `vendor` in FormData -2. Backend multer is parsing multipart form correctly - -**File Size Limit Exceeded** -Default limit is 10MB. To increase: -```javascript -// In backend/server.js -const upload = multer({ - storage: storage, - limits: { fileSize: 50 * 1024 * 1024 } // 50MB -}); -``` - -### Database Issues - -**View database contents:** -```bash -cd /home/cve-dashboard/backend -sqlite3 cve_database.db - -# View all CVEs -sqlite> SELECT * FROM cves; - -# View all documents -sqlite> SELECT * FROM documents; - -# Check compliance status -sqlite> SELECT * FROM cve_document_status; - -# Exit -sqlite> .quit -``` - -**Reset database:** -```bash -cd /home/cve-dashboard/backend -rm cve_database.db -node setup.js -``` - -**Backup database:** -```bash -cp backend/cve_database.db backend/cve_database_backup_$(date +%Y%m%d).db -``` - -### API Connection Issues - -**Error: `Failed to fetch` on all requests** - -1. **Verify backend is running:** -```bash -ps aux | grep "node server.js" -curl http://192.168.2.117:3001/api/cves -``` - -2. **Check API_BASE URL in App.js:** -```javascript -const API_BASE = 'http://192.168.2.117:3001/api'; -``` - -3. **Check firewall:** -```bash -# Allow port 3001 -sudo ufw allow 3001 -``` - -4. **Test backend directly:** -```bash -curl http://192.168.2.117:3001/api/cves -``` - -### Permission Issues - -**Error: `EACCES: permission denied`** -```bash -# Fix ownership -sudo chown -R $USER:$USER /home/cve-dashboard - -# Fix permissions -chmod -R 755 /home/cve-dashboard -chmod -R 777 /home/cve-dashboard/uploads +└── frontend/ + └── src/ + ├── App.js # Main application, CVE list, filters, modals + ├── App.css # Global styles + ├── contexts/ + │ └── AuthContext.js # Auth state provider + └── components/ + ├── LoginForm.js # Login page + ├── UserMenu.js # User dropdown in header + ├── UserManagement.js # Admin user management panel + ├── AuditLog.js # Admin audit log viewer + ├── NvdSyncModal.js # Bulk NVD sync dialog + ├── WeeklyReportModal.js # Weekly report upload dialog + ├── KnowledgeBaseModal.js # Knowledge base upload/list + └── KnowledgeBaseViewer.js # Inline document viewer ``` --- -## 🗺️ Roadmap +## Database Schema -### Version 1.1 (Current Release) ✅ -- [x] **User Authentication**: Login system with user roles (admin, editor, viewer) -- [x] **Multi-Vendor Support**: Same CVE can be tracked across multiple vendors -- [x] **Environment Configuration**: .env files replace hardcoded IPs -- [ ] **Audit Logging**: Track who added/modified CVEs -- [ ] **Email Notifications**: Alert when new CVEs are added -- [ ] **Export to Excel**: Download CVE list as spreadsheet -- [ ] **Bulk Upload**: Import CVEs from CSV -- [ ] **Advanced Search**: Full-text search across all fields +### Core tables -### Version 1.2 -- [ ] **Dashboard Analytics**: Charts showing CVE trends by vendor/severity -- [ ] **Automated CVSS Scoring**: Fetch CVSS scores from NVD API -- [ ] **Integration with Vulnerability Scanners**: Import from Nessus, Qualys, etc. -- [ ] **Document Templates**: Pre-filled templates for vendor requests -- [ ] **Mobile App**: React Native mobile version +**`cves`** - One row per CVE/vendor pair. `UNIQUE(cve_id, vendor)`. -### Version 2.0 -- [ ] **PostgreSQL Migration**: Production-ready database -- [ ] **Docker Deployment**: Containerized deployment -- [ ] **SSO Integration**: Charter/Spectrum LDAP/SSO -- [ ] **API Keys**: Secure API access for integrations -- [ ] **Webhook Support**: Notify external systems on CVE updates -- [ ] **Multi-tenancy**: Support multiple business units +**`documents`** - Files attached to a CVE/vendor pair. Foreign key to `cves(cve_id)`. -### Proposed Features -- Calendar view for CVE timelines -- Automated false positive workflows -- Integration with JIRA/ServiceNow -- Machine learning for auto-categorization -- PDF report generation -- Compliance reports (SOX, PCI-DSS, HIPAA) +**`required_documents`** - Vendor-specific document requirements (advisory, screenshot, etc.). -**Have a feature request?** Open an issue in Gitea or contact the author. +**`users`** - Accounts with roles: `admin`, `editor`, `viewer`. + +**`sessions`** - Active sessions. Expire after 24 hours. + +**`audit_logs`** - Append-only log of all state-changing actions. + +### Feature tables (added by migrations) + +**`weekly_reports`** - Metadata for uploaded vulnerability reports. Tracks original and processed file paths, row counts, uploader, and a `is_current` flag. + +**`knowledge_base`** - Document library entries with title, slug, category, description, and file metadata. + +**`archer_tickets`** - Archer EXC exception tickets linked to CVE/vendor pairs. `UNIQUE(exc_number)`. + +### View + +**`cve_document_status`** - Aggregates document counts per CVE/vendor and derives a `compliance_status` (`Complete` when an advisory is present, otherwise `Missing Required Docs`). --- -## 🤝 Contributing +## Security Model -This is an internal Charter Communications project. Contributions are welcome from Charter team members. +### File upload security -### Development Workflow +- Extension allowlist enforced by Multer; executables (`.exe`, `.js`, `.sh`, `.py`, `.bat`, etc.) are blocked +- MIME type prefix validation in addition to extension checking +- 10 MB per-file size limit +- Filenames are sanitized: path separators, `..` sequences, null bytes, and non-alphanumeric characters are removed + +### Path traversal prevention + +- `sanitizePathSegment()` strips `/`, `\`, `..`, and null bytes from any value used in `path.join()` +- `isPathWithinUploads()` verifies resolved paths stay within the uploads root before any file operation + +### Input validation + +- CVE ID must match `/^CVE-\d{4}-\d{4,}$/` +- Severity must be one of: `Critical`, `High`, `Medium`, `Low` +- Status must be one of: `Open`, `Addressed`, `In Progress`, `Resolved` +- Archer EXC numbers must match `/^EXC-\d+$/` +- All database operations use prepared statements + +### Error handling + +- 500 responses never leak internal error messages to the client +- Full errors are logged server-side only +- Descriptive 400/409 responses are safe because they contain only validation messages written by the application + +### Security headers + +Applied to all responses: + +- `X-Content-Type-Options: nosniff` +- `X-Frame-Options: SAMEORIGIN` +- `X-XSS-Protection: 1; mode=block` +- `Referrer-Policy: strict-origin-when-cross-origin` +- `Permissions-Policy: camera=(), microphone=(), geolocation=()` + +### Session cookies + +`httpOnly: true`, `sameSite: lax`, `secure: true` in production. + +--- + +## Migrations + +Migrations are standalone Node.js scripts that alter the database directly. Run them in the order listed. They use `CREATE TABLE IF NOT EXISTS`, so they are safe to run again if needed. -1. **Clone the repository:** ```bash -git clone https://vulcan.apophisnetworking.net/jramos/cve-dashboard.git -cd cve-dashboard +cd backend +node migrations/add_weekly_reports_table.js +node migrations/add_knowledge_base_table.js +node migrations/add_archer_tickets_table.js ``` -2. **Create a feature branch:** -```bash -git checkout -b feature/your-feature-name -``` +For an existing deployment upgrading from an earlier schema, also check the legacy migration scripts in `backend/`: -3. **Make your changes and commit:** -```bash -git add . -git commit -m "feat: Add your feature description" -``` - -4. **Push to Gitea:** -```bash -git push origin feature/your-feature-name -``` - -5. **Create a Pull Request** in Gitea - -### Commit Message Convention - -Follow [Conventional Commits](https://www.conventionalcommits.org/): - -- `feat:` New feature -- `fix:` Bug fix -- `docs:` Documentation changes -- `style:` Code style changes (formatting) -- `refactor:` Code refactoring -- `test:` Adding tests -- `chore:` Maintenance tasks - -Examples: -``` -feat: Add bulk CVE import from CSV -fix: Resolve upload timeout issue for large files -docs: Update API documentation with new endpoints -refactor: Improve database query performance -``` - -### Code Style - -**Backend:** -- Use async/await for asynchronous operations -- Error handling with try/catch -- Descriptive variable names -- Comment complex logic - -**Frontend:** -- React functional components with hooks -- Tailwind utility classes for styling -- No inline styles -- Extract reusable components - -### Testing - -Before submitting: -1. Test all CRUD operations -2. Test file upload/download/delete -3. Test Quick Check with various scenarios -4. Test search and filters -5. Verify on clean database - ---- - -## 👤 Author - -**jramos** -Charter Communications -Vulnerability Management Team - -**Contact:** -- Gitea: [@jramos](https://vulcan.apophisnetworking.net/jramos) -- Email: jramos@charter.com (internal) - ---- - -## 📄 License - -**Internal Use Only** - Charter Communications - -This software is proprietary and confidential. Unauthorized copying, distribution, or use of this software, via any medium, is strictly prohibited. - -Copyright © 2024-2026 Charter Communications. All rights reserved. - ---- - -## 📊 Project Statistics - -- **Version**: 1.1.0 -- **Released**: January 2026 -- **Lines of Code**: ~2,500 -- **Dependencies**: 15 -- **Supported Browsers**: Chrome, Edge, Firefox, Safari - ---- - -## 🙏 Acknowledgments - -- Charter Communications Security Team for requirements and testing -- Anthropic Claude AI for development assistance -- Open-source community for dependencies (Express, React, SQLite) - ---- - -## 📚 Additional Resources - -### Related Documentation -- [SQLite Documentation](https://www.sqlite.org/docs.html) -- [Express.js Guide](https://expressjs.com/en/guide/routing.html) -- [React Documentation](https://react.dev/) -- [Tailwind CSS](https://tailwindcss.com/docs) -- [CVE Program](https://www.cve.org/) -- [NVD (National Vulnerability Database)](https://nvd.nist.gov/) - -### Internal Resources -- Charter Security Portal: [link] -- Vulnerability Management SOP: [link] -- False Positive Request Process: [link] - ---- - -## 📝 Changelog - -### [1.1.0] - 2026-01-29 - -#### Added -- **User Authentication**: Complete login system with session-based auth - - Three user roles: admin, editor, viewer - - Default admin account (admin/admin123) - - Session persistence with secure cookies - - Password hashing with bcryptjs -- **User Management**: Admin interface for managing users - - Create, edit, deactivate users - - Role assignment - - Password reset capability -- **Multi-Vendor Support**: Track same CVE across multiple vendors - - UNIQUE constraint on (cve_id, vendor) instead of just cve_id - - Per-vendor document storage - - Quick Check shows all vendors for a CVE - - New API endpoint: GET /api/cves/:cveId/vendors -- **Environment Configuration**: Replaced hardcoded IPs - - setup-env.sh script for easy configuration - - .env files for both frontend and backend - - Auto-detection of server IP address - -#### Changed -- All API endpoints now require authentication -- Document deletion restricted to admin role -- CVE creation/editing restricted to editor and admin roles -- stop-servers.sh improved with better process killing -- Browser tab title changed from "ReactApp" to "Dashboard" -- Document storage now organized by CVE ID AND vendor - -#### Fixed -- Dynamic hostname detection now works via environment variables -- Multiple vendors can now have entries for the same CVE - -### [1.0.0] - 2024-01-26 - -#### Added -- Initial release with core functionality -- CVE management (Create, Read, Update) -- Document upload/view/delete -- Quick CVE status check -- Search and filtering -- SQLite database -- RESTful API -- Charter/Spectrum branding -- Automatic file organization -- Document compliance tracking -- Required document configuration per vendor - -#### Known Issues (Resolved in 1.1.0) -- ~~Dynamic hostname detection not working (hardcoded IP as workaround)~~ Fixed -- ~~No user authentication (single-user system)~~ Fixed -- Export functionality shows alert only (not implemented) - ---- - -**Built with ❤️ for Charter Communications** +- `migrate_multivendor.js` - Adds multi-vendor support to an older single-vendor schema +- `migrate-audit-log.js` - Adds the audit_logs table to pre-auth deployments +- `migrate-to-1.1.js` - General 1.0 to 1.1 schema update diff --git a/WEEKLY_REPORT_FEATURE.md b/WEEKLY_REPORT_FEATURE.md index 22f84f6..43970c6 100644 --- a/WEEKLY_REPORT_FEATURE.md +++ b/WEEKLY_REPORT_FEATURE.md @@ -48,13 +48,13 @@ A new feature has been added to the CVE Dashboard that allows users to upload th 1. **Backend:** ```bash - cd /home/admin/cve-dashboard/backend + cd backend node server.js ``` 2. **Frontend:** ```bash - cd /home/admin/cve-dashboard/frontend + cd frontend npm start ``` diff --git a/frontend/README.md b/frontend/README.md deleted file mode 100644 index 58beeac..0000000 --- a/frontend/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# Getting Started with Create React App - -This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). - -## Available Scripts - -In the project directory, you can run: - -### `npm start` - -Runs the app in the development mode.\ -Open [http://localhost:3000](http://localhost:3000) to view it in your browser. - -The page will reload when you make changes.\ -You may also see any lint errors in the console. - -### `npm test` - -Launches the test runner in the interactive watch mode.\ -See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. - -### `npm run build` - -Builds the app for production to the `build` folder.\ -It correctly bundles React in production mode and optimizes the build for the best performance. - -The build is minified and the filenames include the hashes.\ -Your app is ready to be deployed! - -See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. - -### `npm run eject` - -**Note: this is a one-way operation. Once you `eject`, you can't go back!** - -If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. - -Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. - -You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. - -## Learn More - -You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). - -To learn React, check out the [React documentation](https://reactjs.org/). - -### Code Splitting - -This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) - -### Analyzing the Bundle Size - -This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) - -### Making a Progressive Web App - -This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) - -### Advanced Configuration - -This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) - -### Deployment - -This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) - -### `npm run build` fails to minify - -This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) diff --git a/plan.md b/plan.md deleted file mode 100644 index d2cdbc9..0000000 --- a/plan.md +++ /dev/null @@ -1,297 +0,0 @@ -# NVD Lookup + Retroactive Sync — Implementation Plan - -## Overview -Two capabilities on `feature/nvd-lookup` branch: -1. **Auto-fill on Add CVE** (DONE, stashed) — onBlur NVD lookup fills description/severity/date in the Add CVE modal -2. **Sync with NVD** (TO DO) — bulk tool for editors/admins to retroactively update existing CVE entries from NVD, with per-CVE choice to keep or replace description - -## Current State - -### Git State -- **Branch:** `feature/nvd-lookup` (branched from master post-audit-merge) -- **Stash:** `stash@{0}` contains the auto-fill implementation (4 files) -- **Master** now has audit logging (merged from feature/audit on 2026-01-30) -- Offsite repo is up to date through the feature/audit merge to master - -### What's in the Stash -The stash contains working NVD auto-fill code that needs to be popped and conflict-resolved before continuing: - -**`backend/routes/nvdLookup.js` (NEW file)** -- Factory function: `createNvdLookupRouter(db, requireAuth)` -- `GET /lookup/:cveId` endpoint -- Validates CVE ID format (regex: `CVE-YYYY-NNNNN`) -- Calls `https://services.nvd.nist.gov/rest/json/cves/2.0?cveId=...` -- 10-second timeout via `AbortSignal.timeout(10000)` -- Optional `apiKey` header from `NVD_API_KEY` env var -- CVSS severity cascade: v3.1 → v3.0 → v2.0 -- Maps NVD uppercase severity to app format (CRITICAL→Critical, etc.) -- Returns: `{ description, severity, published_date }` - -**`backend/server.js` (MODIFIED)** -- Adds `const createNvdLookupRouter = require('./routes/nvdLookup');` -- Adds `app.use('/api/nvd', createNvdLookupRouter(db, requireAuth));` - -**`frontend/src/App.js` (MODIFIED)** -- New state: `nvdLoading`, `nvdError`, `nvdAutoFilled` -- New function: `lookupNVD(cveId)` — calls backend, auto-fills form fields -- CVE ID input: `onBlur` triggers lookup, `onChange` resets NVD feedback -- Spinner (Loader icon) in CVE ID field while loading -- Green "Auto-filled from NVD" with CheckCircle on success -- Amber warning with AlertCircle on errors (non-blocking) -- Description only fills if currently empty; severity + published_date always update -- NVD state resets on modal close (X, Cancel) and form submit - -**`backend/.env.example` (MODIFIED)** -- Adds `NVD_API_KEY=` with comment about rate limits - -### Stash Conflict Resolution -Popping the stash will conflict in `server.js` because master now has audit imports that didn't exist when the stash was created. Resolution: - -The conflict is in the imports section. Keep ALL existing audit lines from master: -```js -const createAuditLogRouter = require('./routes/auditLog'); -const logAudit = require('./helpers/auditLog'); -``` -AND add the NVD line: -```js -const createNvdLookupRouter = require('./routes/nvdLookup'); -``` - -Similarly, keep the audit route mount and add the NVD mount after it: -```js -app.use('/api/audit-logs', createAuditLogRouter(db, requireAuth, requireRole)); -app.use('/api/nvd', createNvdLookupRouter(db, requireAuth)); -``` - -Then `git add backend/server.js` to mark resolved and `git stash drop`. - ---- - -## Step 1: Resolve Stash + Rebase onto Master - -```bash -git checkout feature/nvd-lookup -git rebase master # Get audit changes into the branch -git stash pop # Apply NVD changes (will conflict in server.js) -# Resolve conflict in server.js as described above -git add backend/server.js -git stash drop -``` - -Verify: `backend/routes/nvdLookup.js` exists, `server.js` has both audit AND NVD imports/mounts. - ---- - -## Step 2: Backend — New Endpoints in `server.js` - -### 2A: `GET /api/cves/distinct-ids` -Place BEFORE `GET /api/cves/check/:cveId` (to avoid route param conflict): -```js -app.get('/api/cves/distinct-ids', requireAuth(db), (req, res) => { - db.all('SELECT DISTINCT cve_id FROM cves ORDER BY cve_id', [], (err, rows) => { - if (err) return res.status(500).json({ error: err.message }); - res.json(rows.map(r => r.cve_id)); - }); -}); -``` - -### 2B: `POST /api/cves/nvd-sync` -Place after the existing `PATCH /api/cves/:cveId/status`: -```js -app.post('/api/cves/nvd-sync', requireAuth(db), requireRole('editor', 'admin'), (req, res) => { - const { updates } = req.body; - if (!Array.isArray(updates) || updates.length === 0) { - return res.status(400).json({ error: 'No updates provided' }); - } - - let updated = 0; - const errors = []; - let completed = 0; - - db.serialize(() => { - updates.forEach((entry) => { - const fields = []; - const values = []; - if (entry.description !== null && entry.description !== undefined) { - fields.push('description = ?'); - values.push(entry.description); - } - if (entry.severity !== null && entry.severity !== undefined) { - fields.push('severity = ?'); - values.push(entry.severity); - } - if (entry.published_date !== null && entry.published_date !== undefined) { - fields.push('published_date = ?'); - values.push(entry.published_date); - } - if (fields.length === 0) { - completed++; - if (completed === updates.length) sendResponse(); - return; - } - fields.push('updated_at = CURRENT_TIMESTAMP'); - values.push(entry.cve_id); - - db.run( - `UPDATE cves SET ${fields.join(', ')} WHERE cve_id = ?`, - values, - function(err) { - if (err) { - errors.push({ cve_id: entry.cve_id, error: err.message }); - } else { - updated += this.changes; - } - completed++; - if (completed === updates.length) sendResponse(); - } - ); - }); - }); - - function sendResponse() { - logAudit(db, { - userId: req.user.id, - username: req.user.username, - action: 'cve_nvd_sync', - entityType: 'cve', - entityId: null, - details: { count: updated, cve_ids: updates.map(u => u.cve_id) }, - ipAddress: req.ip - }); - const result = { message: 'NVD sync completed', updated }; - if (errors.length > 0) result.errors = errors; - res.json(result); - } -}); -``` - -**How "keep existing description" works:** If the user chooses to keep the existing description, the frontend sends `description: null` for that CVE. The backend skips null fields, so the description is not overwritten. Severity and published_date are always sent (auto-update). - ---- - -## Step 3: Frontend — New `NvdSyncModal.js` Component - -**File:** `frontend/src/components/NvdSyncModal.js` - -### Props -```jsx - -``` - -### Phase Machine -| Phase | What's shown | -|-------|-------------| -| `idle` | CVE count + "Fetch NVD Data" button | -| `fetching` | Progress bar, current CVE being fetched, cancel button | -| `review` | Comparison table with per-CVE description choice | -| `applying` | Spinner | -| `done` | Summary (X updated, Y errors) + Close button | - -### Fetching Logic -- Iterate CVE IDs sequentially -- Call `GET /api/nvd/lookup/:cveId` for each -- 7-second delay between requests (safe for 5 req/30s without API key) -- On 429: wait 35 seconds, retry once -- On 404: mark as "Not found in NVD" (gray, skipped) -- On timeout/error: mark with warning (skipped) -- Support cancellation via AbortController - -### Comparison Table Columns -| Column | Content | -|--------|---------| -| CVE ID | The identifier | -| Status | Icon: check=found, warning=error, dash=no changes | -| Severity | `[Current] → [NVD]` with color badges, or "No change" | -| Published Date | `Current → NVD` or "No change" | -| Description | Truncated preview with expand toggle. Current (red bg) vs NVD (green bg) when different | -| Choice | Radio: "Keep existing" (default) / "Use NVD" — only shown when descriptions differ | - -### Bulk Controls -Above the table: -- Summary: `Found: N | Up to date: N | Changes: N | Not in NVD: N | Errors: N` -- Bulk toggle: "Keep All Existing" / "Use All NVD Descriptions" - -Below the table: -- "Apply N Changes" button (count updates dynamically) -- "Cancel" button - -### Apply Logic -Build updates array: -- For each CVE with NVD data (no error): - - Always include `severity` and `published_date` if different from current - - Include `description` only if user chose "Use NVD" — otherwise send `null` - - Skip CVEs where nothing changed -- POST to `/api/cves/nvd-sync` -- On success: call `onSyncComplete()` to refresh CVE list, then show done phase - ---- - -## Step 4: Frontend — App.js Integration - -Minimal changes following `AuditLog`/`UserManagement` pattern: - -1. **Import:** Add `NvdSyncModal` and `RefreshCw` icon -2. **State:** Add `const [showNvdSync, setShowNvdSync] = useState(false);` -3. **Header button** (next to "Add CVE/Vendor", visible to editors/admins): -```jsx -{canWrite() && ( - -)} -``` -4. **Modal render** (alongside other modals): -```jsx -{showNvdSync && ( - setShowNvdSync(false)} onSyncComplete={() => fetchCVEs()} /> -)} -``` - ---- - -## Step 5: AuditLog Badge - -**File:** `frontend/src/components/AuditLog.js` - -Add to the `ACTION_BADGES` object: -```js -cve_nvd_sync: { bg: 'bg-green-100', text: 'text-green-800' }, -``` - ---- - -## Step 6: .env.example (already in stash) -``` -# NVD API Key (optional - increases rate limit from 5 to 50 requests per 30s) -# Request one at https://nvd.nist.gov/developers/request-an-api-key -NVD_API_KEY= -``` - ---- - -## File Summary - -| File | Action | Lines Changed (est.) | -|------|--------|---------------------| -| `backend/server.js` | Modify | +40 (NVD mount + 2 new endpoints) | -| `backend/routes/nvdLookup.js` | From stash | 0 (already complete) | -| `backend/.env.example` | From stash | +3 | -| `frontend/src/components/NvdSyncModal.js` | New | ~350-400 | -| `frontend/src/App.js` | Modify | +10 (import, state, button, modal) | -| `frontend/src/components/AuditLog.js` | Modify | +1 (badge entry) | - ---- - -## Verification Checklist -1. Pop stash, resolve conflict, verify `nvdLookup.js` and server.js are correct -2. Test NVD lookup via curl: `curl -b cookie.txt http://localhost:3001/api/nvd/lookup/CVE-2024-3094` -3. Test distinct-ids: `curl -b cookie.txt http://localhost:3001/api/cves/distinct-ids` -4. Open Add CVE modal, type CVE ID, tab out → verify auto-fill works -5. Click "Sync with NVD" button → modal opens with CVE count -6. Click "Fetch NVD Data" → progress bar, rate-limited fetching -7. Review comparison table → verify diffs shown correctly -8. Toggle description choices, click "Apply" → verify database updated -9. Confirm main CVE list refreshes with new data -10. Check audit log for `cve_nvd_sync` entry diff --git a/test_cases_auth.md b/test_cases_auth.md index 651a288..ad82ed4 100644 --- a/test_cases_auth.md +++ b/test_cases_auth.md @@ -1,7 +1,5 @@ # Authentication Feature - Test Cases -**Feature Branch:** feature/login -**Date:** 2026-01-28 **Tester:** _______________ ---