This document outlines a comprehensive refactoring plan for the gearbox codebase based on a thorough code review. The codebase is functional but requires improvements in security, code quality, maintainability, and testing.
Codebase Size:
- 151 Go files, 54,381 lines of Go code
- 48 templ template files
- ~200 total source files
Overall Code Quality Score: 5.5/10
File: internal/framework/database/database.go:671
Issue: Direct table name interpolation using fmt.Sprintf
err := d.db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", table)).Scan(&count)Risk Level: Medium (table names are internally controlled, but sets bad precedent) Fix: Use whitelist validation for table names
Affected Files: 70+ instances across handler package Issue: Raw error messages exposed to clients
http.Error(w, "Failed to fetch logs: "+err.Error(), http.StatusInternalServerError)Risk Level: Medium (could leak internal paths, database structure) Fix: Create sanitized error responses, log full errors server-side
File: cmd/server/main.go:210
apiKey, _ := encryptor.DecryptString(dbServer.APIKeyEncrypted)Risk Level: High (silently uses empty/corrupted API key) Fix: Handle error explicitly, log and skip server if decryption fails
Multiple Files: Form handlers lack server-side validation Risk Level: Medium Fix: Add validation layer for all user inputs
File: internal/framework/handler/api.go - 1,596 lines
Issue: Single file handles too many responsibilities
Fix: Split into:
api_stats.go- Stats endpointsapi_logs.go- Log endpointsapi_certificates.go- Certificate endpointsapi_services.go- Service control endpointsapi_traffic.go- Traffic data endpoints
Issue: Excessive use of interface{} and map[string]interface{}
- 92 occurrences of bare
interface{} - 50+ instances of
map[string]interface{}for JSON responses Fix: Create typed response structs:
type StatsResponse struct {
Stats *models.Stats `json:"stats"`
UpdatedAt time.Time `json:"updated_at"`
Fresh bool `json:"fresh"`
}Issue: Mixed patterns for error handling
- 8 instances of
_ =(silently ignoring errors) - Inconsistent
sql.ErrNoRowshandling Fix: Standardize error handling patterns, never ignore errors without explicit comment
Issue: Mixed logging libraries (log.Logger vs slog)
Fix: Migrate entirely to slog with structured logging
Files:
traffic.templ- 2,669 linesintegrations.templ- 2,392 lineshaproxy_config.templ- 2,226 lines
Fix: Decompose into smaller, reusable components
Issue: Event handlers scattered throughout templates
onclick="switchServer(this.value)"
onchange="changeTimeRange(this.value)"Fix: Use event delegation with data attributes
Fix: Extract to separate stylesheets or Tailwind config
Issue: 48 *_templ.go files committed (22K+ lines)
Fix: Add to .gitignore, document build process
Issue: Migrations run on every startup without version control Fix: Implement migration versioning system
Fix: Standardize: "not found" vs "database error" responses
Fix: Add EXPLAIN PLAN comments for complex queries
- Only 5 test files in 150+ Go files (3.3% coverage)
config_redaction_test.gois the only substantial test- No tests for:
- API handlers (1,596 lines untested)
- Database operations (1,079 lines untested)
- Auth system
- Plugin system
-
Unit Tests
- Database layer (all CRUD operations)
- Auth system (password hashing, session management)
- Configuration redaction
- Permission checks
-
Integration Tests
- API endpoints (all routes)
- Plugin system
- WebSocket connections
-
Security Tests
- SQL injection attempts
- XSS prevention
- CSRF token validation
- Permission bypass attempts
Target: 70%+ code coverage
- No OpenAPI/Swagger spec for REST API
- Handler functions lack godoc comments
- Complex algorithms undocumented:
- Traffic delta calculation
- Alert evaluation logic
- Metrics retention policies
- No Architecture Decision Records (ADRs)
- Add godoc comments to all exported functions
- Create OpenAPI 3.0 specification
- Document business logic with examples
- Create ADR directory with key decisions
- Fix SQL injection risk in database.go
- Create error sanitization layer
- Fix ignored decryption error
- Add input validation framework
Deliverables:
internal/framework/errors/package for sanitized errorsinternal/framework/validation/package for input validation- Fixed database.go with table name whitelist
- Updated main.go with proper error handling
- Split
api.gointo separate files - Create typed response structs
- Standardize error handling
- Migrate to structured logging (slog)
Deliverables:
internal/framework/handler/api/directory with split filesinternal/framework/models/responses.gowith typed structs- Updated handlers with consistent error patterns
- Removed all
interface{}usage
- Decompose large templ files
- Extract inline JavaScript to modules
- Extract inline CSS
- Update
.gitignorefor generated files
Deliverables:
internal/templates/components/traffic/with decomposed componentsstatic/js/with extracted JavaScript modules- Updated
.gitignore
- Add database layer tests
- Add API integration tests
- Add auth system tests
- Add security tests
Deliverables:
- 70%+ code coverage
- CI integration for tests
- Test documentation
- Add migration version tracking
- Standardize error handling
- Add query optimization comments
Deliverables:
internal/framework/database/migrations/with versioned migrations- Consistent ErrNoRows handling
- EXPLAIN PLAN comments on complex queries
- Add godoc comments
- Create OpenAPI spec
- Document complex algorithms
- Create ADRs
Deliverables:
- Complete godoc coverage
docs/api/openapi.yamldocs/architecture/adr/directory
- Phase 1 (Critical): 4-6 hours
- Phase 2 (High Priority): 6-8 hours
- Phase 3 (Medium Priority): 6-8 hours
- Phase 4 (High Priority): 12-16 hours
- Phase 5 (Medium Priority): 4-6 hours
- Phase 6 (Low Priority): 4-6 hours
Total: 36-50 hours of development work
- Adding tests
- Adding documentation
- Extracting inline CSS/JS
- Logging migration
- Splitting handler files
- Adding type safety
- Error handling changes
- Database query changes
- Input validation (could break forms)
- Template decomposition (UI changes)
- Security: All critical security issues resolved
- Code Quality:
- No files > 500 lines
- No
interface{}usage without explicit justification - Consistent error handling patterns
- Testing: 70%+ code coverage
- Documentation: All exported functions documented
- Maintainability: New developers can understand code structure in < 1 hour
- Week 1: Phase 1 (Security) + Phase 4 start (Tests)
- Week 2: Phase 2 (Handlers) + Phase 4 continue
- Week 3: Phase 3 (Templates) + Phase 5 (Database)
- Week 4: Phase 4 complete + Phase 6 (Docs)
Before proceeding, please review this plan and confirm:
- Which phases should be prioritized?
- Any specific concerns about breaking changes?
- Preferred approach for template refactoring?
- Testing strategy (unit vs integration focus)?
Document Version: 1.0 Date: 2026-01-27 Author: Claude Code (Sonnet 4.5)