You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@trafficcontrol.apache.org by GitBox <gi...@apache.org> on 2021/01/26 17:12:03 UTC

[GitHub] [trafficcontrol] mattjackson220 opened a new pull request #5466: ACME integration and external account binding

mattjackson220 opened a new pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466


   <!--
   ************ STOP!! ************
   If this Pull Request is intended to fix a security vulnerability, DO NOT submit it! Instead, contact
   the Apache Software Foundation Security Team at security@trafficcontrol.apache.org and follow the
   guidelines at https://www.apache.org/security/ regarding vulnerability disclosure.
   -->
   ## What does this PR (Pull Request) do?
   <!-- Explain the changes you made here. If this fixes an Issue, identify it by
   replacing the text in the checkbox item with the Issue number e.g.
   
   - [x] This PR fixes #9001 OR is not related to any Issue
   
   ^ This will automatically close Issue number 9001 when the Pull Request is
   merged (The '#' is important).
   
   Be sure you check the box properly, see the "The following criteria are ALL
   met by this PR" section for details.
   -->
   
   - [x] This PR is not related to any Issue <!-- You can check for an issue here: https://github.com/apache/trafficcontrol/issues -->
   
   This PR adds the ability to renew certificates using ACME protocol and to register new ACME accounts using external account binding.
   
   
   ## Which Traffic Control components are affected by this PR?
   <!-- Please delete all components from this list that are NOT affected by this
   Pull Request. Also, feel free to add the name of a tool or script that is
   affected but not on the list.
   
   Additionally, if this Pull Request does NOT affect documentation, please
   explain why documentation is not required. -->
   
   - Documentation
   - Traffic Ops
   - Traffic Portal
   
   ## What is the best way to verify this PR?
   <!-- Please include here ALL the steps necessary to test your Pull Request. If
   it includes tests (and most should), outline here the steps needed to run the
   tests. If not, lay out the manual testing procedure and please explain why
   tests are unnecessary for this Pull Request. -->
   
   Set up an account with an ACME provider and get the HMAC and Kid from them
   Fill in the ACME info in cdn.conf and run a renewal either through the API or TP
   Verify that the account information has been saved in the acme_accounts table
   Verify that both the API and TP work to kick off a renewal
   Verify that the saved account info is used for a second renewal
   Verify that API and unit tests pass
   Verify that docs build and look good
   
   ## If this is a bug fix, what versions of Traffic Control are affected?
   <!-- If this PR fixes a bug, please list here all of the affected versions - to
   the best of your knowledge. It's also pretty helpful to include a commit hash
   of where 'master' is at the time this PR is opened (if it affects master),
   because what 'master' means will change over time. For example, if this PR
   fixes a bug that's present in master (at commit hash '1df853c8'), in v4.0.0,
   and in the current 4.0.1 Release candidate (e.g. RC1), then this list would
   look like:
   
   - master (1df853c8)
   - 4.0.0
   - 4.0.1 (RC1)
   
   If you don't know what other versions might have this bug, AND don't know how
   to find the commit hash of 'master', then feel free to leave this section
   blank (or, preferably, delete it entirely).
    -->
   
   
   ## The following criteria are ALL met by this PR
   <!-- Check the boxes to signify that the associated statement is true. To
   "check a box", replace the space inside of the square brackets with an 'x'.
   e.g.
   
   - [ x] <- Wrong
   - [x ] <- Wrong
   - [] <- Wrong
   - [*] <- Wrong
   - [x] <- Correct!
   
   -->
   
   - [x] This PR includes tests OR I have explained why tests are unnecessary
   - [x] This PR includes documentation OR I have explained why documentation is unnecessary
   - [x] This PR includes an update to CHANGELOG.md OR such an update is not necessary
   - [x] This PR includes any and all required license headers
   - [x] This PR **DOES NOT FIX A SERIOUS SECURITY VULNERABILITY** (see [the Apache Software Foundation's security guidelines](https://www.apache.org/security/) for details)
   
   
   ## Additional Information
   <!-- If you would like to include any additional information on the PR for
   potential reviewers please put it here.
   
   Some examples of this would be:
   
   - Before and after screenshots/gifs of the Traffic Portal if it is affected
   - Links to other dependent Pull Requests
   - References to relevant context (e.g. new/updates to dependent libraries,
   mailing list records, blueprints)
   
   Feel free to leave this section blank (or, preferably, delete it entirely).
   -->
   
   <!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at
   
       http://www.apache.org/licenses/LICENSE-2.0
   
   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.
   -->
   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] zrhoffman merged pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
zrhoffman merged pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] mattjackson220 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
mattjackson220 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566934175



##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}
+	if err := riaksvc.PutDeliveryServiceSSLKeysObj(newCertObj, tx, cfg.RiakAuthOptions, cfg.RiakPort); err != nil {
+		log.Errorf("Error posting acme certificate to riak: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New(dsName + ": putting riak keys: " + err.Error())
+	}
+
+	tx2, err := db.Begin()
+	if err != nil {
+		log.Errorf("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+		return errors.New("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+	}
+
+	if err := updateSSLKeyVersion(dsName, *certVersion+1, tx2); err != nil {
+		log.Errorf("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+		return errors.New("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+	}
+	tx2.Commit()
+
+	api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: Added SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+
+	return nil
+}
+
+func getAcmeAccountConfig(cfg *config.Config, acmeProvider string) *config.ConfigAcmeAccount {
+	for _, acmeCfg := range cfg.AcmeAccounts {
+		if acmeCfg.AcmeProvider == acmeProvider {
+			return &acmeCfg
+		}
+	}
+	return nil
+}
+
+func getDSIdAndVersionFromName(db *sqlx.DB, xmlId string) (*int, *int64, error) {
+	var dsID int
+	var certVersion int64
+
+	if err := db.QueryRow(`SELECT id, ssl_key_version FROM deliveryservice WHERE xml_id = $1`, xmlId).Scan(&dsID, &certVersion); err != nil {
+		return nil, nil, err
+	}
+
+	return &dsID, &certVersion, nil
+}
+
+func GetAcmeClient(acmeAccount *config.ConfigAcmeAccount, userTx *sql.Tx, db *sqlx.DB) (*lego.Client, error) {
+	if acmeAccount.UserEmail == "" {
+		log.Errorf("An email address must be provided to use ACME with %v", acmeAccount.AcmeProvider)
+		return nil, errors.New("An email address must be provided to use ACME with " + acmeAccount.AcmeProvider)
+	}
+	storedAcmeInfo, err := getStoredAcmeAccountInfo(userTx, acmeAccount.UserEmail, acmeAccount.AcmeProvider)
+	if err != nil {
+		log.Errorf("Error finding stored ACME information: %s", err.Error())
+		return nil, err
+	}
+
+	myUser := MyUser{}
+	foundPreviousAccount := false
+	userPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+	if err != nil {
+		log.Errorf("Error generating private key: %s", err.Error())
+		return nil, err
+	}
+
+	if storedAcmeInfo == nil || acmeAccount.UserEmail == "" {
+		myUser = MyUser{
+			key:   userPrivateKey,
+			Email: acmeAccount.UserEmail,
+		}
+	} else {
+		foundPreviousAccount = true
+		myUser = MyUser{
+			key:   &storedAcmeInfo.PrivateKey,
+			Email: storedAcmeInfo.Email,
+			Registration: &registration.Resource{
+				URI: storedAcmeInfo.URI,
+			},
+		}
+	}
+
+	config := lego.NewConfig(&myUser)
+	config.CADirURL = acmeAccount.AcmeUrl
+	config.Certificate.KeyType = certcrypto.RSA2048
+
+	client, err := lego.NewClient(config)
+	if err != nil {
+		log.Errorf("Error creating acme client: %s", err.Error())
+		return nil, err
+	}
+
+	if acmeAccount.AcmeProvider == tc.LetsEncryptAuthType {
+		client.Challenge.Remove(challenge.HTTP01)
+		client.Challenge.Remove(challenge.TLSALPN01)
+		trafficRouterDns := NewDNSProviderTrafficRouter()
+		trafficRouterDns.db = db
+		if err != nil {
+			log.Errorf("Error creating Traffic Router DNS provider: %s", err.Error())
+			return nil, err
+		}
+		client.Challenge.SetDNS01Provider(trafficRouterDns)
+	}
+
+	if foundPreviousAccount {
+		log.Debugf("Found existing account with %s", acmeAccount.AcmeProvider)
+		reg, err := client.Registration.QueryRegistration()
+		if err != nil {
+			log.Errorf("Error querying %s for existing account: %s", acmeAccount.AcmeProvider, err.Error())
+			return nil, err
+		}
+		myUser.Registration = reg

Review comment:
       i dont think it can be nil without an error




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] mattjackson220 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
mattjackson220 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566933120



##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {

Review comment:
       i dont think cert will ever be nil without an error but i threw it in 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] mattjackson220 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
mattjackson220 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566931635



##########
File path: traffic_ops/traffic_ops_golang/config/config.go
##########
@@ -48,8 +48,9 @@ type Config struct {
 	SMTP                   *ConfigSMTP `json:"smtp"`
 	ConfigPortal           `json:"portal"`
 	ConfigLetsEncrypt      `json:"lets_encrypt"`
-	DB                     ConfigDatabase `json:"db"`
-	Secrets                []string       `json:"secrets"`
+	AcmeAccounts           []ConfigAcmeAccount `json:"acme_accounts"`

Review comment:
       i ran go fmt again and got the same. they look alright to me? let me know if youre still seeing it and ill dig deeper




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] mattjackson220 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
mattjackson220 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566933379



##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}
+	if err := riaksvc.PutDeliveryServiceSSLKeysObj(newCertObj, tx, cfg.RiakAuthOptions, cfg.RiakPort); err != nil {
+		log.Errorf("Error posting acme certificate to riak: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New(dsName + ": putting riak keys: " + err.Error())
+	}
+
+	tx2, err := db.Begin()
+	if err != nil {
+		log.Errorf("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+		return errors.New("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+	}
+
+	if err := updateSSLKeyVersion(dsName, *certVersion+1, tx2); err != nil {
+		log.Errorf("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+		return errors.New("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+	}
+	tx2.Commit()
+
+	api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: Added SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+
+	return nil
+}
+
+func getAcmeAccountConfig(cfg *config.Config, acmeProvider string) *config.ConfigAcmeAccount {
+	for _, acmeCfg := range cfg.AcmeAccounts {
+		if acmeCfg.AcmeProvider == acmeProvider {
+			return &acmeCfg
+		}
+	}
+	return nil
+}
+
+func getDSIdAndVersionFromName(db *sqlx.DB, xmlId string) (*int, *int64, error) {
+	var dsID int
+	var certVersion int64
+
+	if err := db.QueryRow(`SELECT id, ssl_key_version FROM deliveryservice WHERE xml_id = $1`, xmlId).Scan(&dsID, &certVersion); err != nil {
+		return nil, nil, err
+	}
+
+	return &dsID, &certVersion, nil
+}
+
+func GetAcmeClient(acmeAccount *config.ConfigAcmeAccount, userTx *sql.Tx, db *sqlx.DB) (*lego.Client, error) {
+	if acmeAccount.UserEmail == "" {

Review comment:
       i do the nil check before calling this function




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] mattjackson220 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
mattjackson220 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566932187



##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)

Review comment:
       yea good call! really the only user error that could happen would be requesting it for a DS that doesnt exist or doesnt have certs. i updated it so those cases should return the right status




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] mattjackson220 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
mattjackson220 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566934779



##########
File path: docs/source/admin/traffic_ops.rst
##########
@@ -306,6 +306,16 @@ cdn.conf
 """"""""
 This file deals with the configuration parameters of running Traffic Ops itself. It is a JSON-format set of options and their respective values. For the `Legacy Perl Script`_ to work with this file, it must be in its default location at :file:`/opt/traffic_ops/app/conf/cdn.conf`, but `traffic_ops_golang`_ will use whatever file is specified by its :option:`--cfg` option. The keys of the file are described below.
 
+:acme_accounts: This is an optional array of objects to define External Account Binding information to an existing :abbr:`ACME (Automatic Certificate Management Environment)` account.  The `acme_provider` and `user_email` combination must be unique.

Review comment:
       it does not. idk why i was so adamant at capitalizing it haha. and good call on referencing the actual section!




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] zrhoffman merged pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
zrhoffman merged pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] srijeet0406 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
srijeet0406 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566486271



##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"

Review comment:
       These might need to be rearranged.

##########
File path: traffic_ops/traffic_ops_golang/config/config.go
##########
@@ -48,8 +48,9 @@ type Config struct {
 	SMTP                   *ConfigSMTP `json:"smtp"`
 	ConfigPortal           `json:"portal"`
 	ConfigLetsEncrypt      `json:"lets_encrypt"`
-	DB                     ConfigDatabase `json:"db"`
-	Secrets                []string       `json:"secrets"`
+	AcmeAccounts           []ConfigAcmeAccount `json:"acme_accounts"`

Review comment:
       The formatting seems a little bit wonky here, the `json` tags dont seem to be aligned.

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}
+	if err := riaksvc.PutDeliveryServiceSSLKeysObj(newCertObj, tx, cfg.RiakAuthOptions, cfg.RiakPort); err != nil {
+		log.Errorf("Error posting acme certificate to riak: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New(dsName + ": putting riak keys: " + err.Error())
+	}
+
+	tx2, err := db.Begin()
+	if err != nil {
+		log.Errorf("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+		return errors.New("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+	}
+
+	if err := updateSSLKeyVersion(dsName, *certVersion+1, tx2); err != nil {
+		log.Errorf("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+		return errors.New("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+	}
+	tx2.Commit()
+
+	api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: Added SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+
+	return nil
+}
+
+func getAcmeAccountConfig(cfg *config.Config, acmeProvider string) *config.ConfigAcmeAccount {
+	for _, acmeCfg := range cfg.AcmeAccounts {
+		if acmeCfg.AcmeProvider == acmeProvider {
+			return &acmeCfg
+		}
+	}
+	return nil
+}
+
+func getDSIdAndVersionFromName(db *sqlx.DB, xmlId string) (*int, *int64, error) {
+	var dsID int
+	var certVersion int64
+
+	if err := db.QueryRow(`SELECT id, ssl_key_version FROM deliveryservice WHERE xml_id = $1`, xmlId).Scan(&dsID, &certVersion); err != nil {
+		return nil, nil, err
+	}
+
+	return &dsID, &certVersion, nil
+}
+
+func GetAcmeClient(acmeAccount *config.ConfigAcmeAccount, userTx *sql.Tx, db *sqlx.DB) (*lego.Client, error) {
+	if acmeAccount.UserEmail == "" {

Review comment:
       Do we need a `nil` check for `acmeAccount` here?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}
+	if err := riaksvc.PutDeliveryServiceSSLKeysObj(newCertObj, tx, cfg.RiakAuthOptions, cfg.RiakPort); err != nil {
+		log.Errorf("Error posting acme certificate to riak: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New(dsName + ": putting riak keys: " + err.Error())
+	}
+
+	tx2, err := db.Begin()
+	if err != nil {
+		log.Errorf("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+		return errors.New("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+	}
+
+	if err := updateSSLKeyVersion(dsName, *certVersion+1, tx2); err != nil {
+		log.Errorf("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+		return errors.New("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+	}
+	tx2.Commit()
+
+	api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: Added SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+
+	return nil
+}
+
+func getAcmeAccountConfig(cfg *config.Config, acmeProvider string) *config.ConfigAcmeAccount {
+	for _, acmeCfg := range cfg.AcmeAccounts {
+		if acmeCfg.AcmeProvider == acmeProvider {
+			return &acmeCfg
+		}
+	}
+	return nil
+}
+
+func getDSIdAndVersionFromName(db *sqlx.DB, xmlId string) (*int, *int64, error) {
+	var dsID int
+	var certVersion int64
+
+	if err := db.QueryRow(`SELECT id, ssl_key_version FROM deliveryservice WHERE xml_id = $1`, xmlId).Scan(&dsID, &certVersion); err != nil {
+		return nil, nil, err
+	}
+
+	return &dsID, &certVersion, nil
+}
+
+func GetAcmeClient(acmeAccount *config.ConfigAcmeAccount, userTx *sql.Tx, db *sqlx.DB) (*lego.Client, error) {
+	if acmeAccount.UserEmail == "" {
+		log.Errorf("An email address must be provided to use ACME with %v", acmeAccount.AcmeProvider)
+		return nil, errors.New("An email address must be provided to use ACME with " + acmeAccount.AcmeProvider)
+	}
+	storedAcmeInfo, err := getStoredAcmeAccountInfo(userTx, acmeAccount.UserEmail, acmeAccount.AcmeProvider)
+	if err != nil {
+		log.Errorf("Error finding stored ACME information: %s", err.Error())
+		return nil, err
+	}
+
+	myUser := MyUser{}
+	foundPreviousAccount := false
+	userPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+	if err != nil {
+		log.Errorf("Error generating private key: %s", err.Error())
+		return nil, err
+	}
+
+	if storedAcmeInfo == nil || acmeAccount.UserEmail == "" {
+		myUser = MyUser{
+			key:   userPrivateKey,
+			Email: acmeAccount.UserEmail,
+		}
+	} else {
+		foundPreviousAccount = true
+		myUser = MyUser{
+			key:   &storedAcmeInfo.PrivateKey,
+			Email: storedAcmeInfo.Email,
+			Registration: &registration.Resource{
+				URI: storedAcmeInfo.URI,
+			},
+		}
+	}
+
+	config := lego.NewConfig(&myUser)
+	config.CADirURL = acmeAccount.AcmeUrl
+	config.Certificate.KeyType = certcrypto.RSA2048
+
+	client, err := lego.NewClient(config)
+	if err != nil {
+		log.Errorf("Error creating acme client: %s", err.Error())
+		return nil, err
+	}
+
+	if acmeAccount.AcmeProvider == tc.LetsEncryptAuthType {
+		client.Challenge.Remove(challenge.HTTP01)
+		client.Challenge.Remove(challenge.TLSALPN01)
+		trafficRouterDns := NewDNSProviderTrafficRouter()
+		trafficRouterDns.db = db
+		if err != nil {
+			log.Errorf("Error creating Traffic Router DNS provider: %s", err.Error())
+			return nil, err
+		}
+		client.Challenge.SetDNS01Provider(trafficRouterDns)
+	}
+
+	if foundPreviousAccount {
+		log.Debugf("Found existing account with %s", acmeAccount.AcmeProvider)
+		reg, err := client.Registration.QueryRegistration()
+		if err != nil {
+			log.Errorf("Error querying %s for existing account: %s", acmeAccount.AcmeProvider, err.Error())
+			return nil, err
+		}
+		myUser.Registration = reg

Review comment:
       Not sure if reg can be `nil` without an error?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {

Review comment:
       Could we add a `nil` check for `cert` here?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/letsencryptcert.go
##########
@@ -228,88 +226,22 @@ func GetLetsEncryptCertificates(cfg *config.Config, req tc.DeliveryServiceLetsEn
 	}
 	tx.Commit()
 

Review comment:
       Could we add a nil check for `cfg` before dereferencing it?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}

Review comment:
       nit: For better readability, could we split this struct initialization into multiple lines?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}
+	if err := riaksvc.PutDeliveryServiceSSLKeysObj(newCertObj, tx, cfg.RiakAuthOptions, cfg.RiakPort); err != nil {
+		log.Errorf("Error posting acme certificate to riak: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New(dsName + ": putting riak keys: " + err.Error())
+	}
+
+	tx2, err := db.Begin()
+	if err != nil {
+		log.Errorf("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+		return errors.New("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+	}
+
+	if err := updateSSLKeyVersion(dsName, *certVersion+1, tx2); err != nil {
+		log.Errorf("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+		return errors.New("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+	}
+	tx2.Commit()
+
+	api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: Added SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+
+	return nil
+}
+
+func getAcmeAccountConfig(cfg *config.Config, acmeProvider string) *config.ConfigAcmeAccount {
+	for _, acmeCfg := range cfg.AcmeAccounts {
+		if acmeCfg.AcmeProvider == acmeProvider {
+			return &acmeCfg
+		}
+	}
+	return nil
+}
+
+func getDSIdAndVersionFromName(db *sqlx.DB, xmlId string) (*int, *int64, error) {
+	var dsID int
+	var certVersion int64
+
+	if err := db.QueryRow(`SELECT id, ssl_key_version FROM deliveryservice WHERE xml_id = $1`, xmlId).Scan(&dsID, &certVersion); err != nil {
+		return nil, nil, err
+	}
+
+	return &dsID, &certVersion, nil
+}
+
+func GetAcmeClient(acmeAccount *config.ConfigAcmeAccount, userTx *sql.Tx, db *sqlx.DB) (*lego.Client, error) {

Review comment:
       Could you pls add a godoc comment to this function?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)

Review comment:
       Could you add a quick nil check for `cfg` before dereferencing it here?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)

Review comment:
       Rookie ACME question: Could this error not result due to a user error/ bad request? If so, we should send back the appropriate error code.

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/letsencryptcert.go
##########
@@ -358,7 +290,7 @@ func GetLetsEncryptCertificates(cfg *config.Config, req tc.DeliveryServiceLetsEn
 	// remove extra line if LE returns it
 	trimmedCert := bytes.ReplaceAll(certificates.Certificate, []byte("\n\n"), []byte("\n"))
 
-	dsSSLKeys.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(trimmedCert)), Key: string(EncodePEMToLegacyPerlRiakFormat(keyPem)), CSR: ""}
+	dsSSLKeys.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(trimmedCert)), Key: string(EncodePEMToLegacyPerlRiakFormat(keyPem)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("Lets Encrypt Generated")))}

Review comment:
       same comment about splitting this into multiple lines for better readability.

##########
File path: docs/source/api/v3/deliveryservices_xmlid_xmlid_sslkeys_renew.rst
##########
@@ -0,0 +1,54 @@
+..
+..
+.. Licensed under the Apache License, Version 2.0 (the "License");
+.. you may not use this file except in compliance with the License.
+.. You may obtain a copy of the License at
+..
+..     http://www.apache.org/licenses/LICENSE-2.0
+..
+.. Unless required by applicable law or agreed to in writing, software
+.. distributed under the License is distributed on an "AS IS" BASIS,
+.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+.. See the License for the specific language governing permissions and
+.. limitations under the License.
+..
+
+.. _to-api-deliveryservices-xmlid-xmlid-sslkeys-renew:
+
+**************************************************
+``deliveryservices/xmlId/{{XMLID}}/sslkeys/renew``
+**************************************************
+
+``POST``
+========
+Uses :abbr:`ACME (Automatic Certificate Management Environment)` protocol to renew SSL keys for a :term:`Delivery Service`.
+
+:Auth. Required: Yes

Review comment:
       Indentation seems a bit off here.

##########
File path: docs/source/admin/traffic_ops.rst
##########
@@ -306,6 +306,16 @@ cdn.conf
 """"""""
 This file deals with the configuration parameters of running Traffic Ops itself. It is a JSON-format set of options and their respective values. For the `Legacy Perl Script`_ to work with this file, it must be in its default location at :file:`/opt/traffic_ops/app/conf/cdn.conf`, but `traffic_ops_golang`_ will use whatever file is specified by its :option:`--cfg` option. The keys of the file are described below.
 
+:acme_accounts: This is an optional array of objects to define External Account Binding information to an existing :abbr:`ACME (Automatic Certificate Management Environment)` account.  The `acme_provider` and `user_email` combination must be unique.

Review comment:
       nit: Does `External Account Binding` need to be capitalized?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())

Review comment:
       nit: could we add a space after the `:` and before the `err.Error()` part?

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}
+	if err := riaksvc.PutDeliveryServiceSSLKeysObj(newCertObj, tx, cfg.RiakAuthOptions, cfg.RiakPort); err != nil {
+		log.Errorf("Error posting acme certificate to riak: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New(dsName + ": putting riak keys: " + err.Error())
+	}
+
+	tx2, err := db.Begin()
+	if err != nil {
+		log.Errorf("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+		return errors.New("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+	}
+
+	if err := updateSSLKeyVersion(dsName, *certVersion+1, tx2); err != nil {
+		log.Errorf("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+		return errors.New("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+	}
+	tx2.Commit()
+
+	api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: Added SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+
+	return nil
+}
+
+func getAcmeAccountConfig(cfg *config.Config, acmeProvider string) *config.ConfigAcmeAccount {
+	for _, acmeCfg := range cfg.AcmeAccounts {
+		if acmeCfg.AcmeProvider == acmeProvider {
+			return &acmeCfg
+		}
+	}
+	return nil
+}
+
+func getDSIdAndVersionFromName(db *sqlx.DB, xmlId string) (*int, *int64, error) {
+	var dsID int
+	var certVersion int64
+
+	if err := db.QueryRow(`SELECT id, ssl_key_version FROM deliveryservice WHERE xml_id = $1`, xmlId).Scan(&dsID, &certVersion); err != nil {
+		return nil, nil, err
+	}
+
+	return &dsID, &certVersion, nil
+}
+
+func GetAcmeClient(acmeAccount *config.ConfigAcmeAccount, userTx *sql.Tx, db *sqlx.DB) (*lego.Client, error) {
+	if acmeAccount.UserEmail == "" {
+		log.Errorf("An email address must be provided to use ACME with %v", acmeAccount.AcmeProvider)
+		return nil, errors.New("An email address must be provided to use ACME with " + acmeAccount.AcmeProvider)
+	}
+	storedAcmeInfo, err := getStoredAcmeAccountInfo(userTx, acmeAccount.UserEmail, acmeAccount.AcmeProvider)
+	if err != nil {
+		log.Errorf("Error finding stored ACME information: %s", err.Error())
+		return nil, err
+	}
+
+	myUser := MyUser{}
+	foundPreviousAccount := false
+	userPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+	if err != nil {
+		log.Errorf("Error generating private key: %s", err.Error())
+		return nil, err
+	}
+
+	if storedAcmeInfo == nil || acmeAccount.UserEmail == "" {
+		myUser = MyUser{
+			key:   userPrivateKey,
+			Email: acmeAccount.UserEmail,
+		}
+	} else {
+		foundPreviousAccount = true
+		myUser = MyUser{
+			key:   &storedAcmeInfo.PrivateKey,
+			Email: storedAcmeInfo.Email,
+			Registration: &registration.Resource{
+				URI: storedAcmeInfo.URI,
+			},
+		}
+	}
+
+	config := lego.NewConfig(&myUser)
+	config.CADirURL = acmeAccount.AcmeUrl
+	config.Certificate.KeyType = certcrypto.RSA2048
+
+	client, err := lego.NewClient(config)
+	if err != nil {
+		log.Errorf("Error creating acme client: %s", err.Error())
+		return nil, err
+	}
+
+	if acmeAccount.AcmeProvider == tc.LetsEncryptAuthType {
+		client.Challenge.Remove(challenge.HTTP01)
+		client.Challenge.Remove(challenge.TLSALPN01)
+		trafficRouterDns := NewDNSProviderTrafficRouter()
+		trafficRouterDns.db = db
+		if err != nil {
+			log.Errorf("Error creating Traffic Router DNS provider: %s", err.Error())
+			return nil, err
+		}
+		client.Challenge.SetDNS01Provider(trafficRouterDns)
+	}
+
+	if foundPreviousAccount {
+		log.Debugf("Found existing account with %s", acmeAccount.AcmeProvider)
+		reg, err := client.Registration.QueryRegistration()
+		if err != nil {
+			log.Errorf("Error querying %s for existing account: %s", acmeAccount.AcmeProvider, err.Error())
+			return nil, err
+		}
+		myUser.Registration = reg
+		if reg.Body.Status != "valid" {

Review comment:
       Could we add a constant for "valid" ?

##########
File path: docs/source/admin/traffic_ops.rst
##########
@@ -306,6 +306,16 @@ cdn.conf
 """"""""
 This file deals with the configuration parameters of running Traffic Ops itself. It is a JSON-format set of options and their respective values. For the `Legacy Perl Script`_ to work with this file, it must be in its default location at :file:`/opt/traffic_ops/app/conf/cdn.conf`, but `traffic_ops_golang`_ will use whatever file is specified by its :option:`--cfg` option. The keys of the file are described below.
 
+:acme_accounts: This is an optional array of objects to define External Account Binding information to an existing :abbr:`ACME (Automatic Certificate Management Environment)` account.  The `acme_provider` and `user_email` combination must be unique.

Review comment:
       Should we put a reference to the actual definition of external account binding here? `external_account_binding`

##########
File path: docs/source/admin/traffic_ops.rst
##########
@@ -306,6 +306,16 @@ cdn.conf
 """"""""
 This file deals with the configuration parameters of running Traffic Ops itself. It is a JSON-format set of options and their respective values. For the `Legacy Perl Script`_ to work with this file, it must be in its default location at :file:`/opt/traffic_ops/app/conf/cdn.conf`, but `traffic_ops_golang`_ will use whatever file is specified by its :option:`--cfg` option. The keys of the file are described below.
 
+:acme_accounts: This is an optional array of objects to define External Account Binding information to an existing :abbr:`ACME (Automatic Certificate Management Environment)` account.  The `acme_provider` and `user_email` combination must be unique.
+
+    .. versionadded:: 5.1
+
+	:acme_provider: The certificate provider. This field needs to correlate to the AuthType field for each certificate so the renewal functionality knows which provider to use.

Review comment:
       Looks like the indentation is off here.

##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}
+	if err := riaksvc.PutDeliveryServiceSSLKeysObj(newCertObj, tx, cfg.RiakAuthOptions, cfg.RiakPort); err != nil {
+		log.Errorf("Error posting acme certificate to riak: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New(dsName + ": putting riak keys: " + err.Error())
+	}
+
+	tx2, err := db.Begin()
+	if err != nil {
+		log.Errorf("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+		return errors.New("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+	}
+
+	if err := updateSSLKeyVersion(dsName, *certVersion+1, tx2); err != nil {
+		log.Errorf("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+		return errors.New("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+	}
+	tx2.Commit()
+
+	api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: Added SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+
+	return nil
+}
+
+func getAcmeAccountConfig(cfg *config.Config, acmeProvider string) *config.ConfigAcmeAccount {
+	for _, acmeCfg := range cfg.AcmeAccounts {
+		if acmeCfg.AcmeProvider == acmeProvider {
+			return &acmeCfg
+		}
+	}
+	return nil
+}
+
+func getDSIdAndVersionFromName(db *sqlx.DB, xmlId string) (*int, *int64, error) {
+	var dsID int
+	var certVersion int64
+
+	if err := db.QueryRow(`SELECT id, ssl_key_version FROM deliveryservice WHERE xml_id = $1`, xmlId).Scan(&dsID, &certVersion); err != nil {
+		return nil, nil, err
+	}
+
+	return &dsID, &certVersion, nil
+}
+
+func GetAcmeClient(acmeAccount *config.ConfigAcmeAccount, userTx *sql.Tx, db *sqlx.DB) (*lego.Client, error) {
+	if acmeAccount.UserEmail == "" {
+		log.Errorf("An email address must be provided to use ACME with %v", acmeAccount.AcmeProvider)
+		return nil, errors.New("An email address must be provided to use ACME with " + acmeAccount.AcmeProvider)
+	}
+	storedAcmeInfo, err := getStoredAcmeAccountInfo(userTx, acmeAccount.UserEmail, acmeAccount.AcmeProvider)
+	if err != nil {
+		log.Errorf("Error finding stored ACME information: %s", err.Error())
+		return nil, err
+	}
+
+	myUser := MyUser{}
+	foundPreviousAccount := false
+	userPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+	if err != nil {
+		log.Errorf("Error generating private key: %s", err.Error())
+		return nil, err
+	}
+
+	if storedAcmeInfo == nil || acmeAccount.UserEmail == "" {
+		myUser = MyUser{
+			key:   userPrivateKey,
+			Email: acmeAccount.UserEmail,
+		}
+	} else {
+		foundPreviousAccount = true
+		myUser = MyUser{
+			key:   &storedAcmeInfo.PrivateKey,
+			Email: storedAcmeInfo.Email,
+			Registration: &registration.Resource{
+				URI: storedAcmeInfo.URI,
+			},
+		}
+	}
+
+	config := lego.NewConfig(&myUser)
+	config.CADirURL = acmeAccount.AcmeUrl
+	config.Certificate.KeyType = certcrypto.RSA2048
+
+	client, err := lego.NewClient(config)
+	if err != nil {
+		log.Errorf("Error creating acme client: %s", err.Error())
+		return nil, err
+	}
+
+	if acmeAccount.AcmeProvider == tc.LetsEncryptAuthType {
+		client.Challenge.Remove(challenge.HTTP01)
+		client.Challenge.Remove(challenge.TLSALPN01)
+		trafficRouterDns := NewDNSProviderTrafficRouter()
+		trafficRouterDns.db = db
+		if err != nil {
+			log.Errorf("Error creating Traffic Router DNS provider: %s", err.Error())
+			return nil, err
+		}
+		client.Challenge.SetDNS01Provider(trafficRouterDns)
+	}
+
+	if foundPreviousAccount {
+		log.Debugf("Found existing account with %s", acmeAccount.AcmeProvider)
+		reg, err := client.Registration.QueryRegistration()
+		if err != nil {
+			log.Errorf("Error querying %s for existing account: %s", acmeAccount.AcmeProvider, err.Error())
+			return nil, err
+		}
+		myUser.Registration = reg
+		if reg.Body.Status != "valid" {
+			log.Debugf("Account found with %s is not valid.", acmeAccount.AcmeProvider)
+			foundPreviousAccount = false
+		}
+	}
+	if !foundPreviousAccount {
+		if acmeAccount.Kid != "" && acmeAccount.HmacEncoded != "" {
+			reg, err := client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
+				TermsOfServiceAgreed: true,
+				Kid:                  acmeAccount.Kid,
+				HmacEncoded:          acmeAccount.HmacEncoded,
+			})
+			if err != nil {
+				log.Errorf("Error registering acme client with external account binding: %s", err.Error())
+				return nil, err
+			}
+			myUser.Registration = reg
+			log.Debugf("Creating a new account with %s", acmeAccount.AcmeProvider)
+		} else {
+			reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
+			if err != nil {
+				log.Errorf("Error registering acme client: %s", err.Error())
+				return nil, err
+			}
+			myUser.Registration = reg
+			log.Debugf("Creating a new account with %s", acmeAccount.AcmeProvider)
+		}
+
+		// save account info
+		userKeyDer := x509.MarshalPKCS1PrivateKey(userPrivateKey)

Review comment:
       Do you think we should separate the key generation/ renewal part into its own function? 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] mattjackson220 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
mattjackson220 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566932875



##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)

Review comment:
       i dont think cfg could be nil without an error when doing api.NewInfo, but i threw in a nil check anyway




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [trafficcontrol] mattjackson220 commented on a change in pull request #5466: ACME integration and external account binding

Posted by GitBox <gi...@apache.org>.
mattjackson220 commented on a change in pull request #5466:
URL: https://github.com/apache/trafficcontrol/pull/5466#discussion_r566934350



##########
File path: traffic_ops/traffic_ops_golang/deliveryservice/acme.go
##########
@@ -0,0 +1,363 @@
+package deliveryservice
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"bytes"
+	"context"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"database/sql"
+	"encoding/pem"
+	"errors"
+	"github.com/go-acme/lego/certcrypto"
+	"github.com/go-acme/lego/challenge"
+	"github.com/go-acme/lego/lego"
+	"github.com/go-acme/lego/registration"
+	"net/http"
+	"strconv"
+
+	"github.com/apache/trafficcontrol/lib/go-log"
+	"github.com/apache/trafficcontrol/lib/go-tc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/riaksvc"
+	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+	"github.com/go-acme/lego/certificate"
+	"github.com/jmoiron/sqlx"
+)
+
+func RenewAcmeCertificate(w http.ResponseWriter, r *http.Request) {
+	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil)
+	if userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+	defer inf.Close()
+	if inf.Config.RiakEnabled == false {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, userErr, errors.New("deliveryservice.DeleteSSLKeys: Riak is not configured"))
+		return
+	}
+	xmlID := inf.Params["xmlid"]
+
+	if userErr, sysErr, errCode := tenant.Check(inf.User, xmlID, inf.Tx.Tx); userErr != nil || sysErr != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+		return
+	}
+
+	ctx, _ := context.WithTimeout(r.Context(), LetsEncryptTimeout)
+
+	err := renewAcmeCerts(inf.Config, xmlID, ctx, inf.User)
+	if err != nil {
+		api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err)
+	}
+
+	api.WriteRespAlert(w, r, tc.SuccessLevel, "Certificate for "+xmlID+" successfully renewed.")
+
+}
+
+func renewAcmeCerts(cfg *config.Config, dsName string, ctx context.Context, currentUser *auth.CurrentUser) error {
+	db, err := api.GetDB(ctx)
+	if err != nil {
+		log.Errorf(dsName+": Error getting db: %s", err.Error())
+		return err
+	}
+
+	tx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting tx: %s", err.Error())
+		return err
+	}
+
+	userTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting userTx: %s", err.Error())
+		return err
+	}
+	defer userTx.Commit()
+
+	logTx, err := db.Begin()
+	if err != nil {
+		log.Errorf(dsName+": Error getting logTx: %s", err.Error())
+		return err
+	}
+	defer logTx.Commit()
+
+	dsID, certVersion, err := getDSIdAndVersionFromName(db, dsName)
+	if err != nil {
+		return errors.New("querying DS info: " + err.Error())
+	}
+	if dsID == nil || *dsID == 0 {
+		return errors.New("DS id for " + dsName + " was nil or 0")
+	}
+	if certVersion == nil || *certVersion == 0 {
+		return errors.New("certificate for " + dsName + " could not be renewed because version was nil or 0")
+	}
+
+	keyObj, ok, err := riaksvc.GetDeliveryServiceSSLKeysObjV15(dsName, strconv.Itoa(int(*certVersion)), tx, cfg.RiakAuthOptions, cfg.RiakPort)
+	if err != nil {
+		return errors.New("getting ssl keys for xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)) + " :" + err.Error())
+	}
+	if !ok {
+		return errors.New("no object found for the specified key with xmlId: " + dsName + " and version: " + strconv.Itoa(int(*certVersion)))
+	}
+
+	err = base64DecodeCertificate(&keyObj.Certificate)
+	if err != nil {
+		return errors.New("decoding cert for XMLID " + dsName + " : " + err.Error())
+	}
+
+	acmeAccount := getAcmeAccountConfig(cfg, keyObj.AuthType)
+	if acmeAccount == nil {
+		return errors.New("No acme account information in cdn.conf for " + keyObj.AuthType)
+	}
+
+	client, err := GetAcmeClient(acmeAccount, userTx, db)
+	if err != nil {
+		log.Errorf(dsName+": Error getting acme client: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New("getting acme client: " + err.Error())
+	}
+
+	renewRequest := certificate.Resource{
+		Certificate: []byte(keyObj.Certificate.Crt),
+	}
+
+	cert, err := client.Certificate.Renew(renewRequest, true, false)
+	if err != nil {
+		log.Errorf("Error obtaining acme certificate: %s", err.Error())
+		return err
+	}
+
+	newCertObj := tc.DeliveryServiceSSLKeys{
+		AuthType:        keyObj.AuthType,
+		CDN:             keyObj.CDN,
+		DeliveryService: keyObj.DeliveryService,
+		Key:             keyObj.DeliveryService,
+		Hostname:        keyObj.Hostname,
+		Version:         keyObj.Version + 1,
+	}
+
+	newCertObj.Certificate = tc.DeliveryServiceSSLKeysCertificate{Crt: string(EncodePEMToLegacyPerlRiakFormat(cert.Certificate)), Key: string(EncodePEMToLegacyPerlRiakFormat(cert.PrivateKey)), CSR: string(EncodePEMToLegacyPerlRiakFormat([]byte("ACME Generated")))}
+	if err := riaksvc.PutDeliveryServiceSSLKeysObj(newCertObj, tx, cfg.RiakAuthOptions, cfg.RiakPort); err != nil {
+		log.Errorf("Error posting acme certificate to riak: %s", err.Error())
+		api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: FAILED to add SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+		return errors.New(dsName + ": putting riak keys: " + err.Error())
+	}
+
+	tx2, err := db.Begin()
+	if err != nil {
+		log.Errorf("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+		return errors.New("starting sql transaction for delivery service " + dsName + ": " + err.Error())
+	}
+
+	if err := updateSSLKeyVersion(dsName, *certVersion+1, tx2); err != nil {
+		log.Errorf("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+		return errors.New("updating SSL key version for delivery service '" + dsName + "': " + err.Error())
+	}
+	tx2.Commit()
+
+	api.CreateChangeLogRawTx(api.ApiChange, "DS: "+dsName+", ID: "+strconv.Itoa(*dsID)+", ACTION: Added SSL keys with "+acmeAccount.AcmeProvider, currentUser, logTx)
+
+	return nil
+}
+
+func getAcmeAccountConfig(cfg *config.Config, acmeProvider string) *config.ConfigAcmeAccount {
+	for _, acmeCfg := range cfg.AcmeAccounts {
+		if acmeCfg.AcmeProvider == acmeProvider {
+			return &acmeCfg
+		}
+	}
+	return nil
+}
+
+func getDSIdAndVersionFromName(db *sqlx.DB, xmlId string) (*int, *int64, error) {
+	var dsID int
+	var certVersion int64
+
+	if err := db.QueryRow(`SELECT id, ssl_key_version FROM deliveryservice WHERE xml_id = $1`, xmlId).Scan(&dsID, &certVersion); err != nil {
+		return nil, nil, err
+	}
+
+	return &dsID, &certVersion, nil
+}
+
+func GetAcmeClient(acmeAccount *config.ConfigAcmeAccount, userTx *sql.Tx, db *sqlx.DB) (*lego.Client, error) {
+	if acmeAccount.UserEmail == "" {
+		log.Errorf("An email address must be provided to use ACME with %v", acmeAccount.AcmeProvider)
+		return nil, errors.New("An email address must be provided to use ACME with " + acmeAccount.AcmeProvider)
+	}
+	storedAcmeInfo, err := getStoredAcmeAccountInfo(userTx, acmeAccount.UserEmail, acmeAccount.AcmeProvider)
+	if err != nil {
+		log.Errorf("Error finding stored ACME information: %s", err.Error())
+		return nil, err
+	}
+
+	myUser := MyUser{}
+	foundPreviousAccount := false
+	userPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+	if err != nil {
+		log.Errorf("Error generating private key: %s", err.Error())
+		return nil, err
+	}
+
+	if storedAcmeInfo == nil || acmeAccount.UserEmail == "" {
+		myUser = MyUser{
+			key:   userPrivateKey,
+			Email: acmeAccount.UserEmail,
+		}
+	} else {
+		foundPreviousAccount = true
+		myUser = MyUser{
+			key:   &storedAcmeInfo.PrivateKey,
+			Email: storedAcmeInfo.Email,
+			Registration: &registration.Resource{
+				URI: storedAcmeInfo.URI,
+			},
+		}
+	}
+
+	config := lego.NewConfig(&myUser)
+	config.CADirURL = acmeAccount.AcmeUrl
+	config.Certificate.KeyType = certcrypto.RSA2048
+
+	client, err := lego.NewClient(config)
+	if err != nil {
+		log.Errorf("Error creating acme client: %s", err.Error())
+		return nil, err
+	}
+
+	if acmeAccount.AcmeProvider == tc.LetsEncryptAuthType {
+		client.Challenge.Remove(challenge.HTTP01)
+		client.Challenge.Remove(challenge.TLSALPN01)
+		trafficRouterDns := NewDNSProviderTrafficRouter()
+		trafficRouterDns.db = db
+		if err != nil {
+			log.Errorf("Error creating Traffic Router DNS provider: %s", err.Error())
+			return nil, err
+		}
+		client.Challenge.SetDNS01Provider(trafficRouterDns)
+	}
+
+	if foundPreviousAccount {
+		log.Debugf("Found existing account with %s", acmeAccount.AcmeProvider)
+		reg, err := client.Registration.QueryRegistration()
+		if err != nil {
+			log.Errorf("Error querying %s for existing account: %s", acmeAccount.AcmeProvider, err.Error())
+			return nil, err
+		}
+		myUser.Registration = reg
+		if reg.Body.Status != "valid" {
+			log.Debugf("Account found with %s is not valid.", acmeAccount.AcmeProvider)
+			foundPreviousAccount = false
+		}
+	}
+	if !foundPreviousAccount {
+		if acmeAccount.Kid != "" && acmeAccount.HmacEncoded != "" {
+			reg, err := client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
+				TermsOfServiceAgreed: true,
+				Kid:                  acmeAccount.Kid,
+				HmacEncoded:          acmeAccount.HmacEncoded,
+			})
+			if err != nil {
+				log.Errorf("Error registering acme client with external account binding: %s", err.Error())
+				return nil, err
+			}
+			myUser.Registration = reg
+			log.Debugf("Creating a new account with %s", acmeAccount.AcmeProvider)
+		} else {
+			reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
+			if err != nil {
+				log.Errorf("Error registering acme client: %s", err.Error())
+				return nil, err
+			}
+			myUser.Registration = reg
+			log.Debugf("Creating a new account with %s", acmeAccount.AcmeProvider)
+		}
+
+		// save account info
+		userKeyDer := x509.MarshalPKCS1PrivateKey(userPrivateKey)

Review comment:
       yea thats a good idea. moved it and called it from the LE code too




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org