VerifactuMidAPI/internal/cert/validator.go

96 lines
2.3 KiB
Go

package cert
import (
"os"
"os/exec"
"strconv"
"strings"
)
type ValidationResult struct {
Valid bool `json:"valid"`
CertInfo *CertInfo `json:"cert_info,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Error string `json:"error,omitempty"`
}
type CertInfo struct {
Subject string `json:"subject"`
Issuer string `json:"issuer"`
NotBefore string `json:"not_before"`
NotAfter string `json:"not_after"`
Expired bool `json:"expired"`
ExpiringSoon bool `json:"expiring_soon"`
DaysUntilExpiry int `json:"days_until_expiry"`
}
const WarningDaysThreshold = 30
func ValidateP12(filePath, password string) *ValidationResult {
result := &ValidationResult{Valid: true}
if _, err := os.Stat(filePath); os.IsNotExist(err) {
result.Valid = false
result.Error = "file_not_found"
return result
}
scriptPath := "C:\\Users\\jmest\\GolandProjects\\VerifactuMidAPI\\validate_cert.ps1"
cmd := exec.Command("powershell", "-ExecutionPolicy", "Bypass", "-File", scriptPath, "-p12Path", filePath, "-pwd", password)
out, err := cmd.CombinedOutput()
output := strings.TrimSpace(string(out))
if err != nil || output == "" {
result.Valid = false
result.Error = "invalid_password_or_format"
return result
}
if strings.HasPrefix(output, "NOT_FOUND") {
result.Valid = false
result.Error = "file_not_found"
return result
}
if strings.HasPrefix(output, "INVALID") {
result.Valid = false
result.Error = "invalid_password_or_format"
return result
}
if strings.HasPrefix(output, "NOT_YET_VALID") {
result.Valid = false
result.Error = "certificate_not_yet_valid"
return result
}
if strings.HasPrefix(output, "EXPIRED") {
result.Valid = false
result.Error = "certificate_expired"
result.CertInfo = &CertInfo{Expired: true}
return result
}
if strings.HasPrefix(output, "OK:") {
daysStr := strings.TrimPrefix(output, "OK:")
days, _ := strconv.Atoi(daysStr)
result.CertInfo = &CertInfo{
Subject: "Certificate",
Issuer: "Certificate",
DaysUntilExpiry: days,
}
if days <= WarningDaysThreshold {
result.Warnings = append(result.Warnings, "certificate_expiring_soon")
result.CertInfo.ExpiringSoon = true
}
return result
}
result.Valid = false
result.Error = "invalid_password_or_format"
return result
}