Skip to content
This repository has been archived by the owner on Oct 4, 2023. It is now read-only.

fix: add missing certificates statuses and handle cert validation trigger #7

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,18 @@ func (a App) Run(t time.Time, dryRun bool) error {

subl.Debug().Msgf("got zone ID from Cloudflare: %s", id)

subl.Info().Msg("checking current certificate packs status")
status, err := cloudflare.GetCertificatePacksStatus(id, a.CloudflareCredz)
subl.Info().Msg("checking current certificate pack status")
status, certPackId, err := cloudflare.GetCertificatePacksStatus(id, a.CloudflareCredz)
if err != nil {
if err == cloudflare.ErrEmptyResponse {
subl.Fatal().Err(err).Msg("cloudflare returned nothing, the token is probably not working")
}
subl.Error().Err(err).Msg("cannot check current certificate packs status")
subl.Error().Err(err).Str("cert pack ID", certPackId).Msg("cannot check current certificate pack status")
continue
}

if status == cloudflare.ActiveCertificate {
subl.Info().Msg("certificate packs are active for this domain, trying to cleanup provider's TXT records")
subl.Info().Str("cert pack ID", certPackId).Msg("certificate pack is active for this domain, trying to cleanup provider's TXT records")
if dryRun {
a.Logger.Info().Msg("running in dry-mode, stopping actions now")
continue
Expand All @@ -70,8 +70,21 @@ func (a App) Run(t time.Time, dryRun bool) error {
}
continue
}
subl.Info().Msg("certificate packs are pending for this domain")

if status == cloudflare.ValidationTimedOut {
subl.Warn().Str("cert pack ID", certPackId).Msg("certificate pack is in a 'validation_timed_out' state for this domain, meaning that the certs have not been validated in the allowed time period. Trying to retrigger the validation")
if dryRun {
a.Logger.Info().Msg("running in dry-mode, stopping actions now")
continue
}

if err := cloudflare.TriggerCertificatesValidation(id, certPackId, a.CloudflareCredz); err != nil {
subl.Error().Err(err).Str("cert pack ID", certPackId).Msg("error while triggering the certificate pack validation")
}
subl.Info().Str("cert pack ID", certPackId).Msg("retriggered the certificate pack validation")
}

subl.Info().Str("cert pack ID", certPackId).Msg("certificate pack is pending for this domain")
subl.Info().Msg("getting new TXT records on Cloudflare API")
vals, err := cloudflare.GetTXTValues(id, a.CloudflareCredz)
if err != nil {
Expand Down Expand Up @@ -102,7 +115,11 @@ func (a App) Run(t time.Time, dryRun bool) error {
}

if ok {
subl.Info().Msg("TXT records are already set but the certificate packs is still not renewed, so no need to pursue")
subl.Info().Msg("TXT records are already set but the certificate packs is still not renewed, so I'm triggering the renewal")
if err := cloudflare.TriggerCertificatesValidation(id, certPackId, a.CloudflareCredz); err != nil {
subl.Error().Err(err).Str("cert pack ID", certPackId).Msg("error while triggering the certificate validation")
}
subl.Info().Str("cert pack ID", certPackId).Msg("retriggered the certificate pack validation")
continue
}

Expand Down
91 changes: 75 additions & 16 deletions cloudflare/cloudflare.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import (
)

const (
PendingCertificate = "pending_validation"
ActiveCertificate = "active"
PendingCertificate = "pending_validation"
ActiveCertificate = "active"
ValidationTimedOut = "validation_timed_out"
InitializingCertificates = "initializing"
)

var (
Expand All @@ -37,7 +39,7 @@ func GetZoneID(name string, credz Credentials) (string, error) {
}

url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones?name=%s", name)
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
Expand Down Expand Up @@ -84,7 +86,7 @@ func GetTXTValues(id string, credz Credentials) ([]ValidationRecords, error) {
}

url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/ssl/certificate_packs?status=all", id)
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return []ValidationRecords{}, err
}
Expand Down Expand Up @@ -122,17 +124,19 @@ func GetTXTValues(id string, credz Credentials) ([]ValidationRecords, error) {
return holder.Result[0].ValidationRecords, nil
}

func GetCertificatePacksStatus(id string, credz Credentials) (string, error) {
// GetCertificatePacksStatus returns the status, the cert pack ID and an error
func GetCertificatePacksStatus(id string, credz Credentials) (string, string, error) {
type APISchema struct {
Result []struct {
Status string `json:"status,omitempty"`
ID string `json:"id,omitempty"`
} `json:"result"`
}

url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/ssl/certificate_packs?status=all", id)
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
return "", "", err
}

req.Header = http.Header{
Expand All @@ -143,35 +147,90 @@ func GetCertificatePacksStatus(id string, credz Credentials) (string, error) {
client := &http.Client{}
r, err := client.Do(req)
if err != nil {
return "", err
return "", "", err
}
defer r.Body.Close()

data, err := io.ReadAll(r.Body)
if err != nil {
return "", err
return "", "", err
}

var holder APISchema
if err := json.Unmarshal(data, &holder); err != nil {
return "", err
return "", "", err
}

if holder.Result == nil {
return "", ErrEmptyResponse
return "", "", ErrEmptyResponse
}

if len(holder.Result) < 1 {
return "", ErrNoResult
}

switch holder.Result[0].Status {
case "active":
return ActiveCertificate, nil
case "pending_validation":
return PendingCertificate, nil
case ActiveCertificate:
return ActiveCertificate, holder.Result[0].ID, nil
case PendingCertificate:
return PendingCertificate, holder.Result[0].ID, nil
case ValidationTimedOut:
return ValidationTimedOut, holder.Result[0].ID, nil
case InitializingCertificates:
return InitializingCertificates, holder.Result[0].ID, nil
default:
return "", fmt.Errorf("error while getting the certificate packs status: status '%s' is unknown",
return "", "", fmt.Errorf("error while getting the certificate packs status: status '%s' is unknown",
holder.Result[0].Status)
}
}

// https://developers.cloudflare.com/ssl/edge-certificates/advanced-certificate-manager/manage-certificates/#restart-validation
// https://developers.cloudflare.com/api/operations/certificate-packs-restart-validation-for-advanced-certificate-manager-certificate-pack
func TriggerCertificatesValidation(id, certPackId string, credz Credentials) error {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

type APISchema struct {
Errors []interface{} `json:"errors"`
Result struct {
ID string `json:"id"`
Status string `json:"status"`
} `json:"result"`
Success bool `json:"success"`
}

url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/ssl/certificate_packs/%s", id, certPackId)
req, err := http.NewRequest(http.MethodPatch, url, nil)
if err != nil {
return err
}

req.Header = http.Header{
"Authorization": {"Bearer " + credz.Token},
"Content-Type": {"application/json"},
}

client := &http.Client{}
r, err := client.Do(req)
if err != nil {
return err
}
defer r.Body.Close()

data, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}

var holder APISchema
if err := json.Unmarshal(data, &holder); err != nil {
return err
}

if !holder.Success {
return fmt.Errorf("error while triggering the certificates renewal: %s", holder.Errors...)
}

if holder.Result.Status != InitializingCertificates {
return fmt.Errorf("unexpected status, expected: %s, got: %s", InitializingCertificates, holder.Result.Status)
}

return nil
}