File size: 16,455 Bytes
d347e23 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 |
# 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.
|