refactor: workflow condition node
refactor: workflow condition node
This commit is contained in:
@@ -6,13 +6,13 @@ import (
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/usual2970/certimate/internal/domain"
|
||||
httputil "github.com/usual2970/certimate/internal/pkg/utils/http"
|
||||
)
|
||||
|
||||
type monitorNode struct {
|
||||
@@ -32,23 +32,23 @@ func NewMonitorNode(node *domain.WorkflowNode) *monitorNode {
|
||||
func (n *monitorNode) Process(ctx context.Context) error {
|
||||
n.logger.Info("ready to monitor certificate ...")
|
||||
|
||||
nodeConfig := n.node.GetConfigForMonitor()
|
||||
nodeCfg := n.node.GetConfigForMonitor()
|
||||
|
||||
targetAddr := fmt.Sprintf("%s:%d", nodeConfig.Host, nodeConfig.Port)
|
||||
if nodeConfig.Port == 0 {
|
||||
targetAddr = fmt.Sprintf("%s:443", nodeConfig.Host)
|
||||
targetAddr := fmt.Sprintf("%s:%d", nodeCfg.Host, nodeCfg.Port)
|
||||
if nodeCfg.Port == 0 {
|
||||
targetAddr = fmt.Sprintf("%s:443", nodeCfg.Host)
|
||||
}
|
||||
|
||||
targetDomain := nodeConfig.Domain
|
||||
targetDomain := nodeCfg.Domain
|
||||
if targetDomain == "" {
|
||||
targetDomain = nodeConfig.Host
|
||||
targetDomain = nodeCfg.Host
|
||||
}
|
||||
|
||||
n.logger.Info(fmt.Sprintf("retrieving certificate at %s (domain: %s)", targetAddr, targetDomain))
|
||||
|
||||
const MAX_ATTEMPTS = 3
|
||||
const RETRY_INTERVAL = 2 * time.Second
|
||||
var cert *x509.Certificate
|
||||
var certs []*x509.Certificate
|
||||
var err error
|
||||
for attempt := 0; attempt < MAX_ATTEMPTS; attempt++ {
|
||||
if attempt > 0 {
|
||||
@@ -61,7 +61,7 @@ func (n *monitorNode) Process(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
cert, err = n.tryRetrieveCert(ctx, targetAddr, targetDomain, nodeConfig.RequestPath)
|
||||
certs, err = n.tryRetrievePeerCertificates(ctx, targetAddr, targetDomain, nodeCfg.RequestPath)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
@@ -71,15 +71,13 @@ func (n *monitorNode) Process(ctx context.Context) error {
|
||||
n.logger.Warn("failed to monitor certificate")
|
||||
return err
|
||||
} else {
|
||||
if cert == nil {
|
||||
if len(certs) == 0 {
|
||||
n.logger.Warn("no ssl certificates retrieved in http response")
|
||||
|
||||
outputs := map[string]any{
|
||||
outputCertificateValidatedKey: strconv.FormatBool(false),
|
||||
outputCertificateDaysLeftKey: strconv.FormatInt(0, 10),
|
||||
}
|
||||
n.setOutputs(outputs)
|
||||
n.outputs[outputKeyForCertificateValidity] = strconv.FormatBool(false)
|
||||
n.outputs[outputKeyForCertificateDaysLeft] = strconv.FormatInt(0, 10)
|
||||
} else {
|
||||
cert := certs[0] // 只取证书链中的第一个证书,即服务器证书
|
||||
n.logger.Info(fmt.Sprintf("ssl certificate retrieved (serial='%s', subject='%s', issuer='%s', not_before='%s', not_after='%s', sans='%s')",
|
||||
cert.SerialNumber, cert.Subject.String(), cert.Issuer.String(),
|
||||
cert.NotBefore.Format(time.RFC3339), cert.NotAfter.Format(time.RFC3339),
|
||||
@@ -95,11 +93,8 @@ func (n *monitorNode) Process(ctx context.Context) error {
|
||||
|
||||
validated := isCertPeriodValid && isCertHostMatched
|
||||
daysLeft := int(math.Floor(cert.NotAfter.Sub(now).Hours() / 24))
|
||||
outputs := map[string]any{
|
||||
outputCertificateValidatedKey: strconv.FormatBool(validated),
|
||||
outputCertificateDaysLeftKey: strconv.FormatInt(int64(daysLeft), 10),
|
||||
}
|
||||
n.setOutputs(outputs)
|
||||
n.outputs[outputKeyForCertificateValidity] = strconv.FormatBool(validated)
|
||||
n.outputs[outputKeyForCertificateDaysLeft] = strconv.FormatInt(int64(daysLeft), 10)
|
||||
|
||||
if validated {
|
||||
n.logger.Info(fmt.Sprintf("the certificate is valid, and will expire in %d day(s)", daysLeft))
|
||||
@@ -113,52 +108,40 @@ func (n *monitorNode) Process(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *monitorNode) tryRetrieveCert(ctx context.Context, addr, domain, requestPath string) (_cert *x509.Certificate, _err error) {
|
||||
transport := &http.Transport{
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
}).DialContext,
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
},
|
||||
ForceAttemptHTTP2: false,
|
||||
DisableKeepAlives: true,
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
func (n *monitorNode) tryRetrievePeerCertificates(ctx context.Context, addr, domain, requestPath string) ([]*x509.Certificate, error) {
|
||||
transport := httputil.NewDefaultTransport()
|
||||
if transport.TLSClientConfig == nil {
|
||||
transport.TLSClientConfig = &tls.Config{}
|
||||
}
|
||||
transport.TLSClientConfig.InsecureSkipVerify = true
|
||||
|
||||
client := &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: 15 * time.Second,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: transport,
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("https://%s/%s", addr, strings.TrimLeft(requestPath, "/"))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil)
|
||||
if err != nil {
|
||||
_err = fmt.Errorf("failed to create http request: %w", err)
|
||||
n.logger.Warn(fmt.Sprintf("failed to create http request: %w", err))
|
||||
return nil, _err
|
||||
err = fmt.Errorf("failed to create http request: %w", err)
|
||||
n.logger.Warn(err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", "certimate")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
_err = fmt.Errorf("failed to send http request: %w", err)
|
||||
n.logger.Warn(fmt.Sprintf("failed to send http request: %w", err))
|
||||
return nil, _err
|
||||
err = fmt.Errorf("failed to send http request: %w", err)
|
||||
n.logger.Warn(err.Error())
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 {
|
||||
return nil, _err
|
||||
return make([]*x509.Certificate, 0), nil
|
||||
}
|
||||
|
||||
_cert = resp.TLS.PeerCertificates[0]
|
||||
return _cert, nil
|
||||
}
|
||||
|
||||
func (n *monitorNode) setOutputs(outputs map[string]any) {
|
||||
n.outputs = outputs
|
||||
return resp.TLS.PeerCertificates, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user