add goSec, go-lint, update actions #2

Merged
lerentis merged 4 commits from add-gosec-scan into main 2025-10-09 15:47:41 +00:00
Owner

🔒 Add Security and Code Quality Tools to CI/CD Pipeline

Overview

This PR enhances the Canada Kaktus project by integrating comprehensive security scanning and code quality checks into all CI/CD workflows using Gosec and golangci-lint.

🎯 What's Added

🔍 Gosec Security Scanner

  • Purpose: Identifies security vulnerabilities in Go source code
  • Integration: Added to all workflow files (main, PR, and release)
  • Scope: Scans entire codebase with args: ./...

🧹 golangci-lint Code Quality

  • Purpose: Comprehensive Go linting with multiple built-in linters
  • Version: Using v2.1 for stability and reliability
  • Integration: Runs before tests in all workflows

📁 Files Modified

  • .gitea/workflows/main.yaml - Main branch CI/CD
  • .gitea/workflows/pr.yaml - Pull request validation
  • .gitea/workflows/release.yaml - Release pipeline

🔧 Implementation Details

Each workflow now includes these new steps in the Test job:

- name: golangci-lint
  uses: golangci/golangci-lint-action@v8
  with:
    version: v2.1

- name: Run Gosec Security Scanner
  uses: securego/gosec@master
  with:
    args: ./...

🛡️ Security Benefits

Gosec will detect:

  • SQL injection vulnerabilities
  • Command injection risks
  • Hardcoded credentials and secrets
  • Weak cryptographic implementations
  • File path traversal vulnerabilities
  • Unsafe use of reflection
  • Integer overflow conditions

📊 Code Quality Benefits

golangci-lint provides:

  • Multiple linting rules in one tool
  • Consistent code style enforcement
  • Dead code detection
  • Performance optimization suggestions
  • Best practice compliance
  • Customizable rule sets

🚀 Workflow Integration

The tools are strategically placed in the pipeline:

  1. Checkout code
  2. Setup Go environment
  3. Run golangci-lint (code quality)
  4. Run Gosec (security scan)
  5. Execute tests
  6. Build and deploy (if applicable)

This ensures that code quality and security issues are caught before tests run, providing fast feedback to developers.

Benefits

  • 🔒 Enhanced Security: Automatic vulnerability detection in every PR and deployment
  • 📈 Improved Code Quality: Consistent linting and style enforcement
  • Fast Feedback: Issues caught early in the development cycle
  • 🤖 Zero Configuration: Works out-of-the-box with sensible defaults
  • 🔄 Comprehensive Coverage: Runs on all code changes across all workflows

🧪 Testing Strategy

  • Tools run on every push to main branch
  • PR validation includes both security and quality checks
  • Release pipeline ensures production code meets all standards
  • Build fails if critical issues are detected

This addition significantly strengthens the project's security posture and code quality standards while maintaining development velocity through automated checks.


Ready for review! 🚀

# 🔒 Add Security and Code Quality Tools to CI/CD Pipeline ## Overview This PR enhances the Canada Kaktus project by integrating comprehensive security scanning and code quality checks into all CI/CD workflows using **Gosec** and **golangci-lint**. ## 🎯 **What's Added** ### 🔍 **Gosec Security Scanner** - **Purpose**: Identifies security vulnerabilities in Go source code - **Integration**: Added to all workflow files (main, PR, and release) - **Scope**: Scans entire codebase with `args: ./...` ### 🧹 **golangci-lint Code Quality** - **Purpose**: Comprehensive Go linting with multiple built-in linters - **Version**: Using v2.1 for stability and reliability - **Integration**: Runs before tests in all workflows ## 📁 **Files Modified** - `.gitea/workflows/main.yaml` - Main branch CI/CD - `.gitea/workflows/pr.yaml` - Pull request validation - `.gitea/workflows/release.yaml` - Release pipeline ## 🔧 **Implementation Details** Each workflow now includes these new steps in the `Test` job: ```yaml - name: golangci-lint uses: golangci/golangci-lint-action@v8 with: version: v2.1 - name: Run Gosec Security Scanner uses: securego/gosec@master with: args: ./... ``` ## 🛡️ **Security Benefits** **Gosec** will detect: - SQL injection vulnerabilities - Command injection risks - Hardcoded credentials and secrets - Weak cryptographic implementations - File path traversal vulnerabilities - Unsafe use of reflection - Integer overflow conditions ## 📊 **Code Quality Benefits** **golangci-lint** provides: - Multiple linting rules in one tool - Consistent code style enforcement - Dead code detection - Performance optimization suggestions - Best practice compliance - Customizable rule sets ## 🚀 **Workflow Integration** The tools are strategically placed in the pipeline: 1. **Checkout code** 2. **Setup Go environment** 3. **Run golangci-lint** (code quality) 4. **Run Gosec** (security scan) 5. **Execute tests** 6. **Build and deploy** (if applicable) This ensures that code quality and security issues are caught **before** tests run, providing fast feedback to developers. ## ✅ **Benefits** - **🔒 Enhanced Security**: Automatic vulnerability detection in every PR and deployment - **📈 Improved Code Quality**: Consistent linting and style enforcement - **⚡ Fast Feedback**: Issues caught early in the development cycle - **🤖 Zero Configuration**: Works out-of-the-box with sensible defaults - **🔄 Comprehensive Coverage**: Runs on all code changes across all workflows ## 🧪 **Testing Strategy** - Tools run on every push to main branch - PR validation includes both security and quality checks - Release pipeline ensures production code meets all standards - Build fails if critical issues are detected This addition significantly strengthens the project's security posture and code quality standards while maintaining development velocity through automated checks. --- **Ready for review!** 🚀
julian added 1 commit 2025-10-09 14:13:19 +00:00
add goSec, go-lint, update actions
Some checks failed
PR Build / Test (pull_request) Failing after 3m23s
PR Build / Build_Image (pull_request) Successful in 1m30s
1d39b1d214
julian requested review from lerentis 2025-10-09 14:13:19 +00:00
julian added the
Kind/Security
Kind/Testing
labels 2025-10-09 14:14:14 +00:00
julian added 1 commit 2025-10-09 14:33:00 +00:00
fix security - health endpoint will now properly handle timeouts
All checks were successful
PR Build / Test (pull_request) Successful in 4m11s
PR Build / Build_Image (pull_request) Successful in 1m17s
89f0d5e6e7
Author
Owner

🔒 Security Issue Resolution

Issue Identified

  • Tool: Gosec Security Scanner
  • Rule: G114 (CWE-676)
  • Severity: MEDIUM (High Confidence)
  • Location: /internal/health.go:39
  • Problem: Use of net/http serve function that has no support for setting timeouts

Original Code

func (hs *HealthServer) Start() {
    r := mux.NewRouter()
    r.Use(mux.CORSMethodMiddleware(r))
    r.HandleFunc("/health", hs.sendHealth).Methods(http.MethodGet)
    err := http.ListenAndServe("0.0.0.0:8080", r)  // ❌ Security issue
    if err != nil {
        log.WithFields(log.Fields{
            "Caller": "HealthServer.Start",
        }).Error(fmt.Sprintf("Error creating health endpoint: %s", err.Error()))
    }
}

Fixed Code

func (hs *HealthServer) Start() {
    r := mux.NewRouter()
    r.Use(mux.CORSMethodMiddleware(r))
    r.HandleFunc("/health", hs.sendHealth).Methods(http.MethodGet)
    
    server := &http.Server{                        // ✅ Secure implementation
        Addr:         "0.0.0.0:8080",
        Handler:      r,
        ReadTimeout:  15 * time.Second,
        WriteTimeout: 15 * time.Second,
        IdleTimeout:  60 * time.Second,
    }
    
    err := server.ListenAndServe()
    if err != nil {
        log.WithFields(log.Fields{
            "Caller": "HealthServer.Start",
        }).Error(fmt.Sprintf("Error creating health endpoint: %s", err.Error()))
    }
}

📁 Files Modified

internal/health.go

Import Changes

import (
    "fmt"
    "net/http"
    "sync"
+   "time"

    "github.com/gorilla/mux"
    log "github.com/sirupsen/logrus"
)

Function Changes

  • Modified: Start() method in HealthServer struct
  • Added: Proper HTTP server configuration with timeouts
  • Removed: Direct use of http.ListenAndServe

🛡️ Security Improvements

Timeout Configuration

Setting Value Purpose
ReadTimeout 15 seconds Maximum time to read the entire request including body
WriteTimeout 15 seconds Maximum time before timing out writes of the response
IdleTimeout 60 seconds Maximum time to wait for the next request when keep-alives are enabled

Vulnerabilities Addressed

  • Slowloris Attack Prevention: ReadTimeout prevents slow header attacks
  • Slow POST Attack Prevention: ReadTimeout prevents slow body attacks
  • Resource Exhaustion: WriteTimeout prevents slow response attacks
  • Connection Hanging: IdleTimeout prevents indefinite connection holding

Benefits

  • 🔒 Enhanced Security: Mitigates potential DoS attacks through slow connections
  • 📈 Resource Management: Prevents server resource exhaustion
  • Better Performance: Ensures timely connection cleanup
  • 🤖 Compliance: Resolves Gosec G114 security warning
  • 🛡️ Production Ready: Follows HTTP server security best practices

🧪 Impact Assessment

Backward Compatibility

  • API Unchanged: Health endpoint behavior remains the same
  • Response Format: No changes to response structure
  • Functionality: All existing functionality preserved

Operational Impact

  • Low Risk: Only affects connection handling, not business logic
  • Improved Reliability: Prevents hanging connections
  • Kubernetes Ready: Compatible with liveness/readiness probes

Testing Considerations

  • Health checks will timeout after 15 seconds (previously unlimited)
  • Kubernetes probes should complete well within this timeframe
  • No changes needed to existing monitoring or health check configurations

📊 Before vs After

Aspect Before After
Security Vulnerable to slow attacks Protected with timeouts
Resource Usage Potential memory leaks Proper cleanup
Gosec Compliance G114 warning Clean scan
Production Readiness Basic implementation Enterprise ready

This change enhances the security posture of the Canada Kaktus health endpoint while maintaining full compatibility with existing functionality.

# 🔒 Security Issue Resolution ### **Issue Identified** - **Tool**: Gosec Security Scanner - **Rule**: G114 (CWE-676) - **Severity**: MEDIUM (High Confidence) - **Location**: `/internal/health.go:39` - **Problem**: Use of `net/http` serve function that has no support for setting timeouts ### **Original Code** ```go func (hs *HealthServer) Start() { r := mux.NewRouter() r.Use(mux.CORSMethodMiddleware(r)) r.HandleFunc("/health", hs.sendHealth).Methods(http.MethodGet) err := http.ListenAndServe("0.0.0.0:8080", r) // ❌ Security issue if err != nil { log.WithFields(log.Fields{ "Caller": "HealthServer.Start", }).Error(fmt.Sprintf("Error creating health endpoint: %s", err.Error())) } } ``` ### **Fixed Code** ```go func (hs *HealthServer) Start() { r := mux.NewRouter() r.Use(mux.CORSMethodMiddleware(r)) r.HandleFunc("/health", hs.sendHealth).Methods(http.MethodGet) server := &http.Server{ // ✅ Secure implementation Addr: "0.0.0.0:8080", Handler: r, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, } err := server.ListenAndServe() if err != nil { log.WithFields(log.Fields{ "Caller": "HealthServer.Start", }).Error(fmt.Sprintf("Error creating health endpoint: %s", err.Error())) } } ``` ## 📁 **Files Modified** ### `internal/health.go` #### **Import Changes** ```diff import ( "fmt" "net/http" "sync" + "time" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" ) ``` #### **Function Changes** - **Modified**: `Start()` method in `HealthServer` struct - **Added**: Proper HTTP server configuration with timeouts - **Removed**: Direct use of `http.ListenAndServe` ## 🛡️ **Security Improvements** ### **Timeout Configuration** | Setting | Value | Purpose | |---------|-------|---------| | `ReadTimeout` | 15 seconds | Maximum time to read the entire request including body | | `WriteTimeout` | 15 seconds | Maximum time before timing out writes of the response | | `IdleTimeout` | 60 seconds | Maximum time to wait for the next request when keep-alives are enabled | ### **Vulnerabilities Addressed** - **Slowloris Attack Prevention**: ReadTimeout prevents slow header attacks - **Slow POST Attack Prevention**: ReadTimeout prevents slow body attacks - **Resource Exhaustion**: WriteTimeout prevents slow response attacks - **Connection Hanging**: IdleTimeout prevents indefinite connection holding ## ✅ **Benefits** - **🔒 Enhanced Security**: Mitigates potential DoS attacks through slow connections - **📈 Resource Management**: Prevents server resource exhaustion - **⚡ Better Performance**: Ensures timely connection cleanup - **🤖 Compliance**: Resolves Gosec G114 security warning - **🛡️ Production Ready**: Follows HTTP server security best practices ## 🧪 **Impact Assessment** ### **Backward Compatibility** - ✅ **API Unchanged**: Health endpoint behavior remains the same - ✅ **Response Format**: No changes to response structure - ✅ **Functionality**: All existing functionality preserved ### **Operational Impact** - ✅ **Low Risk**: Only affects connection handling, not business logic - ✅ **Improved Reliability**: Prevents hanging connections - ✅ **Kubernetes Ready**: Compatible with liveness/readiness probes ### **Testing Considerations** - Health checks will timeout after 15 seconds (previously unlimited) - Kubernetes probes should complete well within this timeframe - No changes needed to existing monitoring or health check configurations ## 📊 **Before vs After** | Aspect | Before | After | |--------|--------|-------| | Security | ❌ Vulnerable to slow attacks | ✅ Protected with timeouts | | Resource Usage | ❌ Potential memory leaks | ✅ Proper cleanup | | Gosec Compliance | ❌ G114 warning | ✅ Clean scan | | Production Readiness | ❌ Basic implementation | ✅ Enterprise ready | This change enhances the security posture of the Canada Kaktus health endpoint while maintaining full compatibility with existing functionality.
julian added 1 commit 2025-10-09 14:36:31 +00:00
fix security - health endpoint will now properly handle timeouts
Some checks failed
PR Build / Test (pull_request) Failing after 2m42s
PR Build / Build_Image (pull_request) Successful in 1m24s
00708eef30
julian added 1 commit 2025-10-09 14:44:52 +00:00
fix test - ensures the server is listening before the test
All checks were successful
PR Build / Test (pull_request) Successful in 2m40s
PR Build / Build_Image (pull_request) Successful in 1m4s
d3467b357f
lerentis merged commit 4aa8d104bb into main 2025-10-09 15:47:41 +00:00
lerentis deleted branch add-gosec-scan 2025-10-09 15:47:42 +00:00
Sign in to join this conversation.
No description provided.