Skip to content

Commit

Permalink
Add cert attachment validation before sending the redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
edw-defang committed Apr 5, 2024
1 parent 074b54a commit db363cb
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions cmd/lambda/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ package main
import (
"context"
"crypto/ecdsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"

"defang.io/cloudacme/acme"
"defang.io/cloudacme/aws/acm"
Expand Down Expand Up @@ -72,6 +75,12 @@ func HandleALBEvent(ctx context.Context, evt events.ALBTargetGroupRequest) (*eve
return nil, fmt.Errorf("failed to remove http rule: %w", err)
}

validationCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
if err := validateCertAttached(validationCtx, host); err != nil {
return nil, fmt.Errorf("failed to validate certificate: %w", err)
}

return &events.ALBTargetGroupResponse{
StatusCode: 301,
Headers: map[string]string{
Expand All @@ -80,6 +89,29 @@ func HandleALBEvent(ctx context.Context, evt events.ALBTargetGroupRequest) (*eve
}, nil
}

func validateCertAttached(ctx context.Context, domain string) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s", domain), nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}

if _, err := http.DefaultClient.Do(req); err != nil {
var tlsErr *tls.CertificateVerificationError
if errors.As(err, &tlsErr) {
continue
}
return fmt.Errorf("failed https request to domain %v: %w", domain, err)
}
return nil
}
}
}

func removeHttpRule(ctx context.Context, albArn string, ruleCond alb.RuleCondition) error {
listener, err := alb.GetListener(ctx, albArn, awsalb.ProtocolEnumHttp, 80)
if err != nil {
Expand Down

0 comments on commit db363cb

Please sign in to comment.