| # SecurityGPT Usage Examples | |
| Practical examples for using SecurityGPT in various development scenarios. | |
| ## Table of Contents | |
| 1. [Basic Usage](#basic-usage) | |
| 2. [Secure API Development](#secure-api-development) | |
| 3. [Frontend Development](#frontend-development) | |
| 4. [Database Operations](#database-operations) | |
| 5. [Security Reviews](#security-reviews) | |
| 6. [DevOps & Infrastructure](#devops--infrastructure) | |
| 7. [Advanced Patterns](#advanced-patterns) | |
| --- | |
| ## Basic Usage | |
| ### Example 1: Simple Code Generation | |
| ```python | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| model_name = "pki/securitygpt-14b" | |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_name, | |
| device_map="auto", | |
| trust_remote_code=True | |
| ) | |
| # Simple prompt | |
| prompt = "Write a Python function to validate email addresses using regex" | |
| messages = [ | |
| {"role": "system", "content": "You are a helpful coding assistant."}, | |
| {"role": "user", "content": prompt} | |
| ] | |
| text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| inputs = tokenizer([text], return_tensors="pt").to(model.device) | |
| outputs = model.generate(**inputs, max_new_tokens=512, temperature=0.7) | |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| print(response) | |
| ``` | |
| ### Example 2: Using Ollama CLI | |
| ```bash | |
| # Simple query | |
| ollama run securitygpt:14b "Create a FastAPI health check endpoint" | |
| # With context | |
| ollama run securitygpt:14b "Create a user authentication endpoint with JWT tokens and argon2 password hashing" | |
| # Code review | |
| ollama run securitygpt:14b "Review this code for security issues: $(cat auth.py)" | |
| ``` | |
| --- | |
| ## Secure API Development | |
| ### Example 3: FastAPI User Authentication | |
| **Prompt:** | |
| ``` | |
| Create a complete FastAPI authentication system with: | |
| - User signup endpoint with email validation | |
| - Login endpoint with JWT token generation | |
| - Password hashing using argon2 | |
| - Proper error handling | |
| - Input validation using Pydantic | |
| ``` | |
| **Expected Output Pattern:** | |
| ```python | |
| from fastapi import APIRouter, HTTPException, Depends | |
| from pydantic import BaseModel, EmailStr, Field | |
| from passlib.context import CryptContext | |
| from datetime import datetime, timedelta | |
| import jwt | |
| router = APIRouter(prefix="/api/v1/auth", tags=["authentication"]) | |
| # Password hashing with argon2 (NEVER bcrypt) | |
| pwd_context = CryptContext(schemes=["argon2"], deprecated="auto") | |
| class UserSignup(BaseModel): | |
| email: EmailStr | |
| password: str = Field(..., min_length=8) | |
| full_name: str = Field(..., min_length=2) | |
| class UserLogin(BaseModel): | |
| email: EmailStr | |
| password: str | |
| @router.post("/signup") | |
| async def signup(user: UserSignup): | |
| """Create new user with secure password hashing.""" | |
| # Validate password strength | |
| if len(user.password) < 8: | |
| raise HTTPException(400, "Password must be at least 8 characters") | |
| # Hash password with argon2 | |
| hashed_password = pwd_context.hash(user.password) | |
| # Store user in database | |
| # ... (database logic) | |
| return {"message": "User created successfully"} | |
| @router.post("/login") | |
| async def login(credentials: UserLogin): | |
| """Authenticate user and return JWT token.""" | |
| # Get user from database | |
| # user = get_user_by_email(credentials.email) | |
| # Verify password | |
| if not pwd_context.verify(credentials.password, user.hashed_password): | |
| raise HTTPException(401, "Invalid credentials") | |
| # Generate JWT token | |
| token_data = { | |
| "sub": user.email, | |
| "exp": datetime.utcnow() + timedelta(hours=24) | |
| } | |
| token = jwt.encode(token_data, SECRET_KEY, algorithm="HS256") | |
| return {"access_token": token, "token_type": "bearer"} | |
| ``` | |
| ### Example 4: API with Input Validation | |
| **Prompt:** | |
| ``` | |
| Create a FastAPI endpoint for creating blog posts with: | |
| - Title validation (max 200 chars) | |
| - Content validation | |
| - Tag validation (max 5 tags) | |
| - SQL injection prevention | |
| - Proper error responses | |
| ``` | |
| --- | |
| ## Frontend Development | |
| ### Example 5: Secure React Login Form | |
| **Prompt:** | |
| ``` | |
| Create a React login component with: | |
| - Email and password inputs | |
| - Client-side validation | |
| - XSS protection | |
| - CSRF token handling | |
| - Loading states | |
| - Error display | |
| - TypeScript types | |
| ``` | |
| **Expected Output Pattern:** | |
| ```typescript | |
| import React, { useState } from 'react'; | |
| import DOMPurify from 'dompurify'; | |
| interface LoginFormProps { | |
| onSubmit: (email: string, password: string) => Promise<void>; | |
| csrfToken: string; | |
| } | |
| interface FormErrors { | |
| email?: string; | |
| password?: string; | |
| general?: string; | |
| } | |
| export const LoginForm: React.FC<LoginFormProps> = ({ onSubmit, csrfToken }) => { | |
| const [email, setEmail] = useState(''); | |
| const [password, setPassword] = useState(''); | |
| const [errors, setErrors] = useState<FormErrors>({}); | |
| const [loading, setLoading] = useState(false); | |
| const validateEmail = (email: string): boolean => { | |
| const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; | |
| return regex.test(email); | |
| }; | |
| const handleSubmit = async (e: React.FormEvent) => { | |
| e.preventDefault(); | |
| // Clear previous errors | |
| setErrors({}); | |
| // Validate inputs | |
| const newErrors: FormErrors = {}; | |
| if (!validateEmail(email)) { | |
| newErrors.email = 'Invalid email address'; | |
| } | |
| if (password.length < 8) { | |
| newErrors.password = 'Password must be at least 8 characters'; | |
| } | |
| if (Object.keys(newErrors).length > 0) { | |
| setErrors(newErrors); | |
| return; | |
| } | |
| // Sanitize inputs (XSS protection) | |
| const cleanEmail = DOMPurify.sanitize(email); | |
| try { | |
| setLoading(true); | |
| await onSubmit(cleanEmail, password); | |
| } catch (error) { | |
| setErrors({ general: 'Login failed. Please try again.' }); | |
| } finally { | |
| setLoading(false); | |
| } | |
| }; | |
| return ( | |
| <form onSubmit={handleSubmit}> | |
| <input type="hidden" name="csrf_token" value={csrfToken} /> | |
| <div> | |
| <label htmlFor="email">Email</label> | |
| <input | |
| id="email" | |
| type="email" | |
| value={email} | |
| onChange={(e) => setEmail(e.target.value)} | |
| disabled={loading} | |
| required | |
| /> | |
| {errors.email && <span className="error">{errors.email}</span>} | |
| </div> | |
| <div> | |
| <label htmlFor="password">Password</label> | |
| <input | |
| id="password" | |
| type="password" | |
| value={password} | |
| onChange={(e) => setPassword(e.target.value)} | |
| disabled={loading} | |
| required | |
| /> | |
| {errors.password && <span className="error">{errors.password}</span>} | |
| </div> | |
| {errors.general && <div className="error">{errors.general}</div>} | |
| <button type="submit" disabled={loading}> | |
| {loading ? 'Logging in...' : 'Login'} | |
| </button> | |
| </form> | |
| ); | |
| }; | |
| ``` | |
| ### Example 6: API Client with Error Handling | |
| **Prompt:** | |
| ``` | |
| Create a TypeScript API client class with: | |
| - Axios integration | |
| - JWT token management | |
| - Request interceptors | |
| - Error handling | |
| - Retry logic | |
| - Type safety | |
| ``` | |
| --- | |
| ## Database Operations | |
| ### Example 7: Secure SQLAlchemy Model | |
| **Prompt:** | |
| ``` | |
| Create a SQLAlchemy User model with: | |
| - Secure password storage | |
| - Email uniqueness constraint | |
| - Timestamps (created_at, updated_at) | |
| - Soft delete support | |
| - Audit logging | |
| ``` | |
| **Expected Output:** | |
| ```python | |
| from sqlalchemy import Column, Integer, String, DateTime, Boolean | |
| from sqlalchemy.ext.declarative import declarative_base | |
| from datetime import datetime | |
| from passlib.context import CryptContext | |
| Base = declarative_base() | |
| pwd_context = CryptContext(schemes=["argon2"], deprecated="auto") | |
| class User(Base): | |
| __tablename__ = "users" | |
| id = Column(Integer, primary_key=True, index=True) | |
| email = Column(String(255), unique=True, index=True, nullable=False) | |
| hashed_password = Column(String(255), nullable=False) | |
| full_name = Column(String(255)) | |
| is_active = Column(Boolean, default=True) | |
| is_deleted = Column(Boolean, default=False) | |
| created_at = Column(DateTime, default=datetime.utcnow, nullable=False) | |
| updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) | |
| def set_password(self, password: str): | |
| """Hash and set user password using argon2.""" | |
| self.hashed_password = pwd_context.hash(password) | |
| def verify_password(self, password: str) -> bool: | |
| """Verify password against stored hash.""" | |
| return pwd_context.verify(password, self.hashed_password) | |
| def soft_delete(self): | |
| """Mark user as deleted without removing from database.""" | |
| self.is_deleted = True | |
| self.is_active = False | |
| ``` | |
| ### Example 8: Database Migration | |
| **Prompt:** | |
| ``` | |
| Create an Alembic migration script to add user authentication table with proper indexes | |
| ``` | |
| --- | |
| ## Security Reviews | |
| ### Example 9: Code Security Audit | |
| **Prompt:** | |
| ``` | |
| Review this authentication code for security vulnerabilities: | |
| def login(username, password): | |
| query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'" | |
| result = db.execute(query) | |
| if result: | |
| return create_token(username) | |
| return None | |
| ``` | |
| **Expected Output:** | |
| ``` | |
| SECURITY VULNERABILITIES FOUND: | |
| 1. SQL INJECTION (CRITICAL) | |
| - Line 2: Raw string concatenation in SQL query | |
| - Attack vector: username = "admin' OR '1'='1" | |
| - Fix: Use parameterized queries or ORM | |
| 2. PLAINTEXT PASSWORDS (CRITICAL) | |
| - Line 2: Password stored/compared in plaintext | |
| - Fix: Use argon2 password hashing | |
| 3. TIMING ATTACK (MEDIUM) | |
| - Different execution paths for valid/invalid users | |
| - Fix: Use constant-time comparison | |
| SECURE IMPLEMENTATION: | |
| from sqlalchemy.orm import Session | |
| from passlib.context import CryptContext | |
| pwd_context = CryptContext(schemes=["argon2"], deprecated="auto") | |
| def login(username: str, password: str, db: Session): | |
| """Secure login with parameterized query and password hashing.""" | |
| # Parameterized query (SQL injection prevention) | |
| user = db.query(User).filter(User.username == username).first() | |
| # Constant-time check to prevent timing attacks | |
| if user is None: | |
| # Perform dummy hash to maintain constant time | |
| pwd_context.hash("dummy") | |
| return None | |
| # Verify password with argon2 | |
| if not pwd_context.verify(password, user.hashed_password): | |
| return None | |
| return create_token(user.id) | |
| ``` | |
| --- | |
| ## DevOps & Infrastructure | |
| ### Example 10: Docker Compose with Security | |
| **Prompt:** | |
| ``` | |
| Create a secure docker-compose.yml for a FastAPI app with PostgreSQL including: | |
| - Non-root users | |
| - Environment variables from secrets | |
| - Network isolation | |
| - Health checks | |
| - Resource limits | |
| ``` | |
| ### Example 11: GitLab CI/CD Pipeline | |
| **Prompt:** | |
| ``` | |
| Create a GitLab CI pipeline for a Python FastAPI app with: | |
| - Linting (flake8) | |
| - Testing (pytest) | |
| - Security scanning | |
| - Docker build | |
| - Deployment to production | |
| ``` | |
| --- | |
| ## Advanced Patterns | |
| ### Example 12: Rate Limiting Middleware | |
| **Prompt:** | |
| ``` | |
| Create FastAPI rate limiting middleware using Redis with: | |
| - IP-based limiting | |
| - Token bucket algorithm | |
| - Configurable limits | |
| - Custom error responses | |
| ``` | |
| ### Example 13: API Key Management | |
| **Prompt:** | |
| ``` | |
| Create an API key management system with: | |
| - Key generation with secure random | |
| - Key hashing for storage | |
| - Rate limiting per key | |
| - Key expiration | |
| - Usage tracking | |
| ``` | |
| ### Example 14: Multi-factor Authentication | |
| **Prompt:** | |
| ``` | |
| Implement TOTP-based 2FA for FastAPI with: | |
| - QR code generation | |
| - Token verification | |
| - Backup codes | |
| - Account recovery | |
| ``` | |
| --- | |
| ## Integration Examples | |
| ### Example 15: Using with LangChain | |
| ```python | |
| from langchain.llms import HuggingFacePipeline | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline | |
| model_name = "pki/securitygpt-14b" | |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_name, | |
| device_map="auto", | |
| trust_remote_code=True | |
| ) | |
| pipe = pipeline( | |
| "text-generation", | |
| model=model, | |
| tokenizer=tokenizer, | |
| max_new_tokens=1024, | |
| temperature=0.7 | |
| ) | |
| llm = HuggingFacePipeline(pipeline=pipe) | |
| # Use with LangChain | |
| from langchain.chains import LLMChain | |
| from langchain.prompts import PromptTemplate | |
| template = """Create a secure {feature} for a {framework} application. | |
| Include proper error handling and security best practices. | |
| Feature: {feature} | |
| Framework: {framework} | |
| """ | |
| prompt = PromptTemplate(template=template, input_variables=["feature", "framework"]) | |
| chain = LLMChain(llm=llm, prompt=prompt) | |
| result = chain.run(feature="user authentication", framework="FastAPI") | |
| print(result) | |
| ``` | |
| ### Example 16: Batch Processing | |
| ```python | |
| # Process multiple code generation tasks | |
| prompts = [ | |
| "Create a FastAPI endpoint for user registration", | |
| "Create a React form component for login", | |
| "Create a PostgreSQL schema for user management" | |
| ] | |
| for prompt in prompts: | |
| messages = [ | |
| {"role": "system", "content": "You are a secure coding assistant."}, | |
| {"role": "user", "content": prompt} | |
| ] | |
| text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| inputs = tokenizer([text], return_tensors="pt").to(model.device) | |
| outputs = model.generate(**inputs, max_new_tokens=512) | |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| print(f"\n{'='*60}\nPrompt: {prompt}\n{'='*60}") | |
| print(response) | |
| ``` | |
| --- | |
| ## Tips for Best Results | |
| ### 1. Be Specific in Prompts | |
| ❌ Bad: "Create an API endpoint" | |
| ✅ Good: "Create a FastAPI POST endpoint at /api/v1/users for user registration with email validation and argon2 password hashing" | |
| ### 2. Specify Technology Stack | |
| Include framework versions and specific libraries when relevant: | |
| ``` | |
| Create a React 18 component using TypeScript and Tailwind CSS for... | |
| ``` | |
| ### 3. Request Security Features | |
| Explicitly ask for security features: | |
| ``` | |
| Create a login endpoint with argon2 password hashing, rate limiting, and CSRF protection | |
| ``` | |
| ### 4. Use System Prompts | |
| Customize the system prompt for your use case: | |
| ```python | |
| messages = [ | |
| {"role": "system", "content": "You are a senior security engineer reviewing code for vulnerabilities."}, | |
| {"role": "user", "content": "Review this authentication code..."} | |
| ] | |
| ``` | |
| ### 5. Adjust Temperature | |
| - **Low (0.1-0.3):** Deterministic, consistent code generation | |
| - **Medium (0.5-0.7):** Balanced creativity and consistency | |
| - **High (0.8-1.0):** More creative solutions, less predictable | |
| ### 6. Iterate and Refine | |
| Use follow-up prompts to refine output: | |
| ``` | |
| 1st prompt: "Create a user authentication endpoint" | |
| 2nd prompt: "Add rate limiting to prevent brute force attacks" | |
| 3rd prompt: "Add logging for security audit trail" | |
| ``` | |
| --- | |
| ## Common Patterns | |
| ### Pattern 1: Full-Stack Feature | |
| ``` | |
| Create a complete user profile feature including: | |
| - Backend: FastAPI endpoint with SQLAlchemy model | |
| - Frontend: React component with TypeScript | |
| - Database: PostgreSQL migration script | |
| - Tests: pytest for backend, Jest for frontend | |
| ``` | |
| ### Pattern 2: Security Hardening | |
| ``` | |
| Review and harden this [component] for production: | |
| - Add input validation | |
| - Implement rate limiting | |
| - Add security headers | |
| - Add audit logging | |
| - Fix any SQL injection or XSS vulnerabilities | |
| ``` | |
| ### Pattern 3: Migration/Upgrade | |
| ``` | |
| Migrate this Flask endpoint to FastAPI: | |
| - Use Pydantic for validation | |
| - Add async/await | |
| - Update to /api/v1 versioning | |
| - Add OpenAPI documentation | |
| [paste code] | |
| ``` | |
| --- | |
| ## Troubleshooting | |
| ### Issue: Model generating outdated patterns | |
| **Solution:** Explicitly specify modern versions in prompt | |
| ``` | |
| Create a FastAPI endpoint using FastAPI 0.110+ with Pydantic v2 | |
| ``` | |
| ### Issue: Output too verbose | |
| **Solution:** Lower temperature and add conciseness requirement | |
| ```python | |
| outputs = model.generate(..., temperature=0.3) | |
| # Add to prompt: "Provide concise implementation without extensive comments" | |
| ``` | |
| ### Issue: Missing security features | |
| **Solution:** Explicitly list required security features in prompt | |
| ``` | |
| Include: input validation, SQL injection prevention, XSS protection, rate limiting | |
| ``` | |
| --- | |
| ## Additional Resources | |
| - [Model Card](./MODEL_CARD.md) - Full model documentation | |
| - [Training Details](./TRAINING.md) - Training methodology | |
| - [Deployment Guide](./DEPLOYMENT.md) - Production deployment | |
| - [Hugging Face Model Hub](https://huggingface.co/pki/securitygpt-14b) | |
| --- | |
| **Need help?** Open an issue on the model repository or use the Hugging Face discussions tab. | |