HUB
Sign inSign up

mohdmusheer/codeshield-ai

By mohdmusheer

β€’Updated about 2 months ago

CodeShield AI is a state-of-the-art, enterprise-quality codebase security analyzer.

Image
Networking
Security
Machine learning & AI
0

2.8K

mohdmusheer/codeshield-ai repository overview

⁠CodeShield AI πŸ›‘οΈ

CI Pipeline Security Scan Apache 2.0 License Docker Support

CodeShield AI is an enterprise-quality codebase security analyzer and college project integrating a modern frontend, FastAPI backend, and Render PostgreSQL database. It automates remote repository cloning, dependency mapping, intelligent code chunking, and leverages Groq's Large Language Models (LLMs) alongside static scanners to detect, score, and automatically remediate vulnerabilities.


β πŸ› οΈ Architecture

               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
               β”‚         Frontend Dashboard / User Profile (/profile)        β”‚
               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚ (Public / Guest Scans)        β”‚ (Auth & Profile)
                              β–Ό                               β–Ό
               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
               β”‚   FastAPI Scanner Endpoints   β”‚ β”‚ FastAPI Auth & DB Router  β”‚
               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚                                β”‚ (SQLAlchemy ORM)
                              β–Ό                                β–Ό
               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
               β”‚ ScanStateManager (Disk Cache) β”‚ β”‚   Render PostgreSQL DB    β”‚
               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚       (users table)       β”‚
                              β”‚                  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β–Ό
               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
               β”‚    PipelineManager Worker     β”‚
               β””β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”˜
                 β”‚            β”‚             β”‚
                 β–Ό            β–Ό             β–Ό
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚  GitHub/GitLab β”‚ β”‚ Code Chunker β”‚ β”‚ Static Regex & β”‚
        β”‚ Cloner Service β”‚ β”‚ & LLM Merger β”‚ β”‚ Groq Scanner   β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β πŸš€ Key Features

  • Multi-Source Code Loading: Scan remote public GitHub/GitLab repositories, local directories, or ZIP archive uploads with drag-and-drop.
  • Optional Guest Access: Instant access to all scanner capabilities, vulnerability findings, diff generation, and report downloads without registration.
  • User Authentication & Profiles: Secure user registration, authentication, and a dedicated profile management page powered by Render PostgreSQL.
  • Argon2id Password Security: Passwords are cryptographically salted and hashed using Argon2id with OWASP-recommended parameters; plaintext passwords and hashes are never exposed.
  • Secure Cookie Sessions & CSRF Protection: HTTP-only, SameSite-protected session cookies with rate limiting and CSRF mitigation.
  • Smart Chunk Grouping: Groups compatible code segments by file into unified prompts (up to 15,000 characters) to optimize Groq LLM context windows, bypass HTTP 429 rate limits, and run scans in under 10 seconds.
  • Disk-Backed State Machine: Remembers scan progress across server restarts and connection interruptions.
  • Interactive Code Modals: Provides full syntax highlighting alongside side-by-side vulnerable vs. remediated code views.
  • Unified Diff Patches: Generates drop-in .diff patches and pre-formatted AI prompt logs (fix_prompt.json, .md, .txt) to fix codebase security flaws.
  • Multi-Format Reports: Downloader supports SARIF, CSV, JSON, Markdown, HTML, and Mock PDF formats.

β πŸ” Authentication, Guest Access & User Profiles

⁠1. Optional Guest Mode (Default)
  • Open the dashboard at http://localhost:8000/ and start scanning immediately.
  • Guests have full access to the repository cloner, static analysis, Groq AI vulnerability detector, risk scoring, and report exports.
  • No database records, accounts, or session tokens are required for guest workflows.
⁠2. User Registration (Signup)
  • Click Account in the top navigation header and choose Sign Up (or visit /#signup).
  • Fields: Full name, Email address, Password (min 8 characters), Confirm password.
  • Submissions are validated with Pydantic and checked for duplicate emails (case-insensitive).
  • Passwords are securely hashed with Argon2id and persisted to the Render PostgreSQL users table.
  • A secure HTTP-only session cookie is issued upon registration, automatically logging in the user.
⁠3. User Login & Logout
  • Click Account and enter your registered email and password (or visit /#login).
  • Features login brute-force protection (maximum 5 failed attempts per 15-minute window).
  • Returns generic authentication failure messages to prevent user enumeration.
  • Clicking Logout immediately clears the session cookie and invalidates the session.
⁠4. Dedicated User Profile Page (/profile)
  • Accessible at /profile or by clicking the user badge in the header.
  • Displays:
    • Full Name (view mode and editable inline)
    • Registered Email Address (linked to Render PostgreSQL)
    • Account Creation Date (formatted timestamp)
    • Account Status (Active)
    • Edit Profile and Save Changes buttons (persists updates to PostgreSQL)
    • Logout button
    • Back to Dashboard navigation link
  • Profile operations resolve strictly from the authenticated session, preventing horizontal privilege escalation or viewing other users' data.
  • If a guest visits /profile, a friendly notice explains guest mode and offers quick links to sign in or return to scanning.

β πŸ—„οΈ Database & PostgreSQL Integration (Render)

CodeShield AI integrates with Render PostgreSQL using SQLAlchemy 2.0 and psycopg2.

⁠Database Schema (users table)
ColumnTypeConstraintsDescription
idIntegerPrimary Key, AutoincrementUnique user identifier
full_nameString(100)Not NullUser display name
emailString(255)Unique, Indexed, Not NullNormalized login email
password_hashString(255)Not NullArgon2id cryptographic password hash
is_activeBooleanDefault True, Not NullAccount status flag
created_atDateTime (UTC)Not NullRegistration timestamp
updated_atDateTime (UTC)Not NullLast profile update timestamp
⁠Resilient & Graceful Fallback
  • On startup, init_db() verifies table existence and creates the users table automatically.
  • If DATABASE_URL is omitted, placeholder, or temporarily unreachable, the application logs an informational notice and continues running in guest-only mode without crashing. Existing scanner functionality is 100% independent of the database.
  • Database access is encapsulated in app/core/database.py with scoped session cleanup (get_db dependency).

β βš™οΈ Environment Configuration (.env)

Create a local .env file in the root directory (never commit .env to Git):

# PostgreSQL β€” Connection string from Render
DATABASE_URL=postgresql://csai_user:[email protected]/csai

# Existing Groq configuration β€” retain real values locally
GROQ_API_KEY=your_groq_api_key_here
GROQ_MODEL=llama-3.3-70b-versatile

# Authentication
SESSION_SECRET=a_very_long_and_cryptographically_random_secret_string

# Application
HOST=0.0.0.0
PORT=8000
DEBUG=false
LOG_LEVEL=INFO
COOKIE_SECURE=false
⁠Environment Variables Reference
VariableRequiredDefaultDescription
DATABASE_URLOptional""Render PostgreSQL connection URI. Automatically normalizes postgres:// to postgresql+psycopg2://.
SESSION_SECRETRequiredBuilt-in fallbackSecret key used to sign HMAC session tokens.
GROQ_API_KEYRequired""Groq Cloud API key for AI security reasoning.
GROQ_MODELOptionalllama-3.3-70b-versatileGroq LLM model name.
HOSTOptional0.0.0.0Server host binding.
PORTOptional8000Application HTTP port.
COOKIE_SECUREOptionalfalseSet to true when running on HTTPS in production.

Important

Never commit real secrets or `.env` files. Both `.env` and local database files are excluded in `.gitignore`. If an API key has ever been committed, rotate it immediately in the Groq Cloud Console.

β πŸ’» Local Installation (Development)

  1. Clone the Repository:

    git clone https://github.com/mohd-musheer/CodeShield-AI.git
    cd CodeShield-AI
    
  2. Create and Activate a Virtual Environment:

    # Windows PowerShell
    python -m venv .venv
    .\.venv\Scripts\Activate.ps1
    
    # Linux / macOS
    python3 -m venv .venv
    source .venv/bin/activate
    
  3. Install Dependencies:

    pip install -r requirements.txt
    
  4. Configure .env:

    cp .env.example .env
    # Edit .env with your Render PostgreSQL URL and Groq API Key
    
  5. Start the Application:

    python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
    

    Open http://localhost:8000 in your web browser.


⁠🐳 Docker Deployment

Docker Compose automatically reads environment variables from .env and mounts persistent volumes:

docker compose up --build -d

View logs and container status:

docker compose logs -f codeshield
docker compose ps

Stop services:

docker compose down
⁠2. Manual Docker Build & Run
# Build Docker image
docker build -t codeshield-ai:latest .

# Run container with environment file
docker run -d -p 8000:8000 --env-file .env codeshield-ai:latest

⁠☁️ Render Deployment Guide

  1. Deploying PostgreSQL on Render:

    • Create a new PostgreSQL service in your Render dashboard.
    • Note the Internal Database URL (for services within Render's private network) and External Database URL (for local development/testing).
  2. Deploying Web Service on Render:

    • Create a new Web Service pointing to your GitHub repository.
    • Select Docker as the Environment / Runtime.
    • Set the following Environment Variables in the Render dashboard:
      • DATABASE_URL: Your Render Internal Database URL.
      • GROQ_API_KEY: Your Groq Cloud API Key.
      • GROQ_MODEL: llama-3.3-70b-versatile.
      • SESSION_SECRET: A long random string (e.g. openssl rand -hex 32).
      • COOKIE_SECURE: true (Render provides automatic TLS/HTTPS).
      • PORT: 8000.

β πŸ“˜ API Documentation

CodeShield AI exposes standard REST endpoints for integration:

⁠Authentication & User Profile Endpoints
MethodEndpointAccessDescription
POST/auth/signupPublicRegisters a new account, hashes password, sets session cookie.
POST/auth/loginPublicAuthenticates credentials, checks rate limits, sets session cookie.
POST/auth/logoutSessionClears session and CSRF cookies.
GET/auth/meAuthenticatedRetrieves current authenticated user profile.
PATCH/auth/meAuthenticatedUpdates current user's profile details (full name).
GET/profilePublicServes the user profile management HTML page.
⁠Security Scanner & Repository Endpoints
MethodEndpointAccessDescription
GET/PublicServes the main CodeShield AI security dashboard.
GET/healthPublicServer status and API liveness metrics.
GET/scan/status/{scan_id}PublicRetrieves active progress metrics and current scan stage.
POST/repository/analyzePublicTriggers background codebase security scans.
POST/repository/uploadPublicUploads a ZIP codebase archive for parsing.
POST/repository/cancel/{scan_id}PublicAborts a running scan and cleans up disk cache.
GET/repository/reportPublicDownloads scan report in json, html, markdown, sarif, csv, pdf, patch_diff, or fix_prompt.

⁠⚑ Performance Benchmarks

Project SizeTotal ChunksMerged Groq CallsTotal Scan Duration
Small (1-50 Files)3-1012-4 seconds
Medium (50-200 Files)30-803-56-9 seconds
Large (200+ Files)200+12-1515-20 seconds

β πŸ—ΊοΈ Roadmap

  • Optional User Authentication & Profile Management with Render PostgreSQL.
  • Secure Argon2id password hashing and HTTP-only cookie sessions.
  • Support private repositories via SSH Keys and Git Credential Helper.
  • Add native Semgrep rules integration alongside Groq semantic scans.
  • Provide Slack and webhook notification alerts on completed scans.

β πŸ“œ License

Distributed under the Apache 2.0 License. See LICENSE⁠ for details.

Tag summary
Recent tags
Content type
Image
Digest
sha256:5bd5bd166…
Size
104.4 MB
Last updated
about 2 months ago
docker pull mohdmusheer/codeshield-ai:latest