diff --git a/certinspector/inspector.go b/certinspector/inspector.go index b549f822142f2f2e407dcb1969ed37d9a498198e..376deb2e7aaf4c1ef2ce1aed8ce9b575be03c0ec 100644 --- a/certinspector/inspector.go +++ b/certinspector/inspector.go @@ -20,7 +20,6 @@ var ( InfoLogger *log.Logger WarningLogger *log.Logger ErrorLogger *log.Logger - verboseBool bool ) func init() { @@ -37,10 +36,10 @@ type CertificateData struct { ExpiryDate string `json:"expiry_date"` } -// inspect certificate and return CertificateData +// Inspect certificate and return CertificateData. func InspectCertificate(certDir string, verboseBool bool) (CertificateData, error) { if verboseBool { - DebugLogger.Printf("running inspector/InspectCertificate for: %s", certDir) + DebugLogger.Printf("executing InspectCertificate function for: %s", certDir) } fullchainPath := filepath.Join(certDir, "fullchain.pem") data, err := os.ReadFile(fullchainPath) @@ -76,10 +75,10 @@ func InspectCertificate(certDir string, verboseBool bool) (CertificateData, erro }, nil } -// call writeJSON functio. Used by the API. +// Process certificate and call writeJSON function. Write to file. func ProcessCertificatesWrite(baseDir, provider string, outputDir string, verboseBool bool) error { if verboseBool { - DebugLogger.Printf("Running inspector/ProcessCertificatesWrite function for provider: %s", provider) + DebugLogger.Printf("executing ProcessCertificatesWrite function for provider: %s", provider) } liveDir := filepath.Join(baseDir, provider, "live") dirs, err := os.ReadDir(liveDir) @@ -118,26 +117,10 @@ func ProcessCertificatesWrite(baseDir, provider string, outputDir string, verbos return writeJSON(outputFile, results, verboseBool) } -// write JSON to file. Used by the API. -func writeJSON(filename string, data interface{}, verboseBool bool) error { - if verboseBool { - DebugLogger.Printf("Running inspector/writeJSON function for file: %s", filename) - } - file, err := os.Create(filename) - if err != nil { - return fmt.Errorf("failed to create JSON file: %w", err) - } - defer file.Close() - - encoder := json.NewEncoder(file) - encoder.SetIndent("", " ") - return encoder.Encode(data) -} - -// process certificates and return JSON data +// process certificates and return JSON data. Used by the API. It doesn't write to file. func ProcessCertificates(baseDir, provider string, verboseBool bool) ([]byte, error) { if verboseBool { - DebugLogger.Printf("Running inspector/ProcessCertificates for provider: %s", provider) + DebugLogger.Printf("executing ProcessCertificates for provider: %s", provider) } liveDir := filepath.Join(baseDir, provider, "live") dirs, err := os.ReadDir(liveDir) @@ -179,3 +162,19 @@ func ProcessCertificates(baseDir, provider string, verboseBool bool) ([]byte, er return jsonData, nil } + +// write JSON to file. Used by the ProcessCertificatesWrite function. +func writeJSON(filename string, data interface{}, verboseBool bool) error { + if verboseBool { + DebugLogger.Printf("executing writeJSON function, target file: %s", filename) + } + file, err := os.Create(filename) + if err != nil { + return fmt.Errorf("failed to create JSON file: %w", err) + } + defer file.Close() + + encoder := json.NewEncoder(file) + encoder.SetIndent("", " ") + return encoder.Encode(data) +} diff --git a/main.go b/main.go index 74b689764d4dab366179416419866b63a2cb7dab..ccbe0ae3caa92061afa66fdecda8ba88972853d7 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "github.com/docopt/docopt-go" @@ -48,7 +49,7 @@ func renderJSON(w http.ResponseWriter, req *http.Request) { } if verboseBool { - DebugLogger.Printf("Serving JSON for provider: %s", provider) + DebugLogger.Printf("JSON generation initiated for provider: %s", provider) } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) @@ -79,32 +80,41 @@ func renderPage(w http.ResponseWriter, req *http.Request) { } // trigger puppet +// triggerPuppet triggers the Puppet process by sending SIGUSR1. func triggerPuppet(w http.ResponseWriter, req *http.Request) { - // content-type currently not working + const authHeaderPrefix = "Bearer " cmd := exec.Command("/usr/bin/pkill", "-f", "/opt/puppetlabs/puppet/bin/puppet", "--signal", "SIGUSR1") - authToken := "BOFH" - _, ok := req.Header["Authorization"] - if ok { - authToken = strings.Split(req.Header.Get("Authorization"), "Bearer ")[1] - } - okMsg := fmt.Sprintln("{\n \"status\": \"OK\",\n \"response\": 200\n}") - unauthorizedMsg := fmt.Sprintln("{\n \"status\": \"Unauthorized\",\n \"response\": 401\n}") - unavailableMsg := fmt.Sprintln("{\n \"status\": \"KO\",\n \"response\": 503\n}") w.Header().Set("Content-Type", "application/json; charset=utf-8") + + authHeader := req.Header.Get("Authorization") + if !strings.HasPrefix(authHeader, authHeaderPrefix) { + http.Error(w, `{"status": "Unauthorized", "response": 401, "puppet": "NOT triggered"}`, http.StatusUnauthorized) + return + } + + authToken := strings.TrimPrefix(authHeader, authHeaderPrefix) if authToken != bearerToken { - http.Error(w, unauthorizedMsg, http.StatusUnauthorized) - } else { - err := cmd.Run() - if err != nil { - WarningLogger.Println(err) - http.Error(w, unavailableMsg, http.StatusServiceUnavailable) - } else { - if verboseBool { - DebugLogger.Printf("HTTP Status %v", http.StatusOK) - } - http.Error(w, okMsg, http.StatusOK) - } + http.Error(w, `{"status": "Unauthorized", "response": 401}`, http.StatusUnauthorized) + return + } + + err := cmd.Run() + if err != nil { + WarningLogger.Printf("Failed to trigger Puppet: %v", err) + http.Error(w, `{"status": "KO", "response": 503, "error": "`+err.Error()+`"}`, http.StatusServiceUnavailable) + return + } + + if verboseBool { + DebugLogger.Printf("HTTP Status %v - Puppet triggered successfully", http.StatusOK) + } + + response := `{"status": "OK", "response": 200, "puppet": "triggered"}` + w.WriteHeader(http.StatusOK) + _, err = w.Write([]byte(response)) + if err != nil { + WarningLogger.Printf("Failed to write response: %v", err) } } @@ -112,7 +122,7 @@ func triggerPuppet(w http.ResponseWriter, req *http.Request) { func redirect(w http.ResponseWriter, req *http.Request) { redirectURL := filepath.Join(req.URL.Path, "/by_name.html") if verboseBool { - DebugLogger.Printf("running redirect to: %v", redirectURL) + DebugLogger.Printf("redirecting to: %v", redirectURL) } http.Redirect(w, req, redirectURL, http.StatusMovedPermanently) } @@ -120,11 +130,11 @@ func redirect(w http.ResponseWriter, req *http.Request) { // Custom HTTP handler with 404 fallback func customHandler(w http.ResponseWriter, req *http.Request) { path := req.URL.Path - - if path == "/" || path == "/index.html" || path == "/index.htm" { - //if verboseBool { - // DebugLogger.Printf("Serving file: %s", path) - //} + rootPath := []string{"/", "/index.html", "/index.htm"} + if slices.Contains(rootPath, path) { + // if verboseBool { + // DebugLogger.Printf("Serving file: %s", path) + // } http.ServeFile(w, req, filepath.Join(webDir, "index.html")) return } @@ -172,8 +182,7 @@ func customHandler(w http.ResponseWriter, req *http.Request) { return } - // If no route matches, return 404 - http.NotFound(w, req) + http.NotFound(w, req) // If no route matches, return 404 } func main() {