mirror of
https://github.com/usual2970/certimate.git
synced 2025-10-05 14:04:54 +00:00
fix conflict
This commit is contained in:
@@ -0,0 +1,187 @@
|
||||
package aliyuncasdeploy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
aliyunCas "github.com/alibabacloud-go/cas-20200407/v3/client"
|
||||
aliyunOpen "github.com/alibabacloud-go/darabonba-openapi/v2/client"
|
||||
"github.com/alibabacloud-go/tea/tea"
|
||||
xerrors "github.com/pkg/errors"
|
||||
|
||||
"github.com/usual2970/certimate/internal/pkg/core/deployer"
|
||||
"github.com/usual2970/certimate/internal/pkg/core/logger"
|
||||
"github.com/usual2970/certimate/internal/pkg/core/uploader"
|
||||
uploaderp "github.com/usual2970/certimate/internal/pkg/core/uploader/providers/aliyun-cas"
|
||||
)
|
||||
|
||||
type AliyunCASDeployDeployerConfig struct {
|
||||
// 阿里云 AccessKeyId。
|
||||
AccessKeyId string `json:"accessKeyId"`
|
||||
// 阿里云 AccessKeySecret。
|
||||
AccessKeySecret string `json:"accessKeySecret"`
|
||||
// 阿里云地域。
|
||||
Region string `json:"region"`
|
||||
// 阿里云云产品资源 ID 数组。
|
||||
ResourceIds []string `json:"resourceIds"`
|
||||
// 阿里云云联系人 ID 数组。
|
||||
// 零值时默认使用账号下第一个联系人。
|
||||
ContactIds []string `json:"contactIds"`
|
||||
}
|
||||
|
||||
type AliyunCASDeployDeployer struct {
|
||||
config *AliyunCASDeployDeployerConfig
|
||||
logger logger.Logger
|
||||
sdkClient *aliyunCas.Client
|
||||
sslUploader uploader.Uploader
|
||||
}
|
||||
|
||||
var _ deployer.Deployer = (*AliyunCASDeployDeployer)(nil)
|
||||
|
||||
func New(config *AliyunCASDeployDeployerConfig) (*AliyunCASDeployDeployer, error) {
|
||||
return NewWithLogger(config, logger.NewNilLogger())
|
||||
}
|
||||
|
||||
func NewWithLogger(config *AliyunCASDeployDeployerConfig, logger logger.Logger) (*AliyunCASDeployDeployer, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New("config is nil")
|
||||
}
|
||||
|
||||
if logger == nil {
|
||||
return nil, errors.New("logger is nil")
|
||||
}
|
||||
|
||||
client, err := createSdkClient(config.AccessKeyId, config.AccessKeySecret, config.Region)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to create sdk client")
|
||||
}
|
||||
|
||||
uploader, err := createSslUploader(config.AccessKeyId, config.AccessKeySecret, config.Region)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to create ssl uploader")
|
||||
}
|
||||
|
||||
return &AliyunCASDeployDeployer{
|
||||
logger: logger,
|
||||
config: config,
|
||||
sdkClient: client,
|
||||
sslUploader: uploader,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *AliyunCASDeployDeployer) Deploy(ctx context.Context, certPem string, privkeyPem string) (*deployer.DeployResult, error) {
|
||||
if len(d.config.ResourceIds) == 0 {
|
||||
return nil, errors.New("config `resourceIds` is required")
|
||||
}
|
||||
|
||||
// 上传证书到 CAS
|
||||
upres, err := d.sslUploader.Upload(ctx, certPem, privkeyPem)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to upload certificate file")
|
||||
}
|
||||
|
||||
d.logger.Logt("certificate file uploaded", upres)
|
||||
|
||||
contactIds := d.config.ContactIds
|
||||
if len(contactIds) == 0 {
|
||||
// 获取联系人列表
|
||||
// REF: https://help.aliyun.com/zh/ssl-certificate/developer-reference/api-cas-2020-04-07-listcontact
|
||||
listContactReq := &aliyunCas.ListContactRequest{}
|
||||
listContactReq.ShowSize = tea.Int32(1)
|
||||
listContactReq.CurrentPage = tea.Int32(1)
|
||||
listContactResp, err := d.sdkClient.ListContact(listContactReq)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to execute sdk request 'cas.ListContact'")
|
||||
}
|
||||
|
||||
if len(listContactResp.Body.ContactList) > 0 {
|
||||
contactIds = []string{fmt.Sprintf("%d", listContactResp.Body.ContactList[0].ContactId)}
|
||||
}
|
||||
}
|
||||
|
||||
// 创建部署任务
|
||||
// REF: https://help.aliyun.com/zh/ssl-certificate/developer-reference/api-cas-2020-04-07-createdeploymentjob
|
||||
createDeploymentJobReq := &aliyunCas.CreateDeploymentJobRequest{
|
||||
Name: tea.String(fmt.Sprintf("certimate-%d", time.Now().UnixMilli())),
|
||||
JobType: tea.String("user"),
|
||||
CertIds: tea.String(upres.CertId),
|
||||
ResourceIds: tea.String(strings.Join(d.config.ResourceIds, ",")),
|
||||
ContactIds: tea.String(strings.Join(contactIds, ",")),
|
||||
}
|
||||
createDeploymentJobResp, err := d.sdkClient.CreateDeploymentJob(createDeploymentJobReq)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to execute sdk request 'cas.CreateDeploymentJob'")
|
||||
}
|
||||
|
||||
d.logger.Logt("已创建部署任务", createDeploymentJobResp)
|
||||
|
||||
// 循环获取部署任务详情,等待任务状态变更
|
||||
// REF: https://help.aliyun.com/zh/ssl-certificate/developer-reference/api-cas-2020-04-07-describedeploymentjob
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
describeDeploymentJobReq := &aliyunCas.DescribeDeploymentJobRequest{
|
||||
JobId: createDeploymentJobResp.Body.JobId,
|
||||
}
|
||||
describeDeploymentJobResp, err := d.sdkClient.DescribeDeploymentJob(describeDeploymentJobReq)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to execute sdk request 'cas.DescribeDeploymentJob'")
|
||||
}
|
||||
|
||||
if describeDeploymentJobResp.Body.Status == nil || *describeDeploymentJobResp.Body.Status == "editing" {
|
||||
return nil, errors.New("部署任务状态异常")
|
||||
}
|
||||
|
||||
if *describeDeploymentJobResp.Body.Status == "success" || *describeDeploymentJobResp.Body.Status == "error" {
|
||||
d.logger.Logt("已获取部署任务详情", describeDeploymentJobResp)
|
||||
break
|
||||
}
|
||||
|
||||
d.logger.Logt("部署任务未完成 ...")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
|
||||
return &deployer.DeployResult{}, nil
|
||||
}
|
||||
|
||||
func createSdkClient(accessKeyId, accessKeySecret, region string) (*aliyunCas.Client, error) {
|
||||
if region == "" {
|
||||
region = "cn-hangzhou" // CAS 服务默认区域:华东一杭州
|
||||
}
|
||||
|
||||
// 接入点一览 https://help.aliyun.com/zh/ssl-certificate/developer-reference/endpoints
|
||||
var endpoint string
|
||||
switch region {
|
||||
case "cn-hangzhou":
|
||||
endpoint = "cas.aliyuncs.com"
|
||||
default:
|
||||
endpoint = fmt.Sprintf("cas.%s.aliyuncs.com", region)
|
||||
}
|
||||
|
||||
config := &aliyunOpen.Config{
|
||||
AccessKeyId: tea.String(accessKeyId),
|
||||
AccessKeySecret: tea.String(accessKeySecret),
|
||||
Endpoint: tea.String(endpoint),
|
||||
}
|
||||
|
||||
client, err := aliyunCas.NewClient(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func createSslUploader(accessKeyId, accessKeySecret, region string) (uploader.Uploader, error) {
|
||||
uploader, err := uploaderp.New(&uploaderp.AliyunCASUploaderConfig{
|
||||
AccessKeyId: accessKeyId,
|
||||
AccessKeySecret: accessKeySecret,
|
||||
Region: region,
|
||||
})
|
||||
return uploader, err
|
||||
}
|
138
internal/pkg/core/deployer/providers/aliyun-esa/aliyun_esa.go
Normal file
138
internal/pkg/core/deployer/providers/aliyun-esa/aliyun_esa.go
Normal file
@@ -0,0 +1,138 @@
|
||||
package aliyunesa
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
aliyunOpen "github.com/alibabacloud-go/darabonba-openapi/v2/client"
|
||||
aliyunEsa "github.com/alibabacloud-go/esa-20240910/v2/client"
|
||||
"github.com/alibabacloud-go/tea/tea"
|
||||
xerrors "github.com/pkg/errors"
|
||||
|
||||
"github.com/usual2970/certimate/internal/pkg/core/deployer"
|
||||
"github.com/usual2970/certimate/internal/pkg/core/logger"
|
||||
"github.com/usual2970/certimate/internal/pkg/core/uploader"
|
||||
uploaderp "github.com/usual2970/certimate/internal/pkg/core/uploader/providers/aliyun-cas"
|
||||
)
|
||||
|
||||
type AliyunESADeployerConfig struct {
|
||||
// 阿里云 AccessKeyId。
|
||||
AccessKeyId string `json:"accessKeyId"`
|
||||
// 阿里云 AccessKeySecret。
|
||||
AccessKeySecret string `json:"accessKeySecret"`
|
||||
// 阿里云地域。
|
||||
Region string `json:"region"`
|
||||
// 阿里云 ESA 站点 ID。
|
||||
SiteId int64 `json:"siteId"`
|
||||
}
|
||||
|
||||
type AliyunESADeployer struct {
|
||||
config *AliyunESADeployerConfig
|
||||
logger logger.Logger
|
||||
sdkClient *aliyunEsa.Client
|
||||
sslUploader uploader.Uploader
|
||||
}
|
||||
|
||||
var _ deployer.Deployer = (*AliyunESADeployer)(nil)
|
||||
|
||||
func New(config *AliyunESADeployerConfig) (*AliyunESADeployer, error) {
|
||||
return NewWithLogger(config, logger.NewNilLogger())
|
||||
}
|
||||
|
||||
func NewWithLogger(config *AliyunESADeployerConfig, logger logger.Logger) (*AliyunESADeployer, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New("config is nil")
|
||||
}
|
||||
|
||||
if logger == nil {
|
||||
return nil, errors.New("logger is nil")
|
||||
}
|
||||
|
||||
client, err := createSdkClient(config.AccessKeyId, config.AccessKeySecret, config.Region)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to create sdk client")
|
||||
}
|
||||
|
||||
uploader, err := createSslUploader(config.AccessKeyId, config.AccessKeySecret, config.Region)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to create ssl uploader")
|
||||
}
|
||||
|
||||
return &AliyunESADeployer{
|
||||
logger: logger,
|
||||
config: config,
|
||||
sdkClient: client,
|
||||
sslUploader: uploader,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *AliyunESADeployer) Deploy(ctx context.Context, certPem string, privkeyPem string) (*deployer.DeployResult, error) {
|
||||
if d.config.SiteId == 0 {
|
||||
return nil, errors.New("config `siteId` is required")
|
||||
}
|
||||
|
||||
// 上传证书到 CAS
|
||||
upres, err := d.sslUploader.Upload(ctx, certPem, privkeyPem)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to upload certificate file")
|
||||
}
|
||||
|
||||
d.logger.Logt("certificate file uploaded", upres)
|
||||
|
||||
// 配置站点证书
|
||||
// REF: https://help.aliyun.com/zh/edge-security-acceleration/esa/api-esa-2024-09-10-setcertificate
|
||||
certId, _ := strconv.ParseInt(upres.CertId, 10, 64)
|
||||
setCertificateReq := &aliyunEsa.SetCertificateRequest{
|
||||
SiteId: tea.Int64(d.config.SiteId),
|
||||
Type: tea.String("cas"),
|
||||
CasId: tea.Int64(certId),
|
||||
}
|
||||
setCertificateResp, err := d.sdkClient.SetCertificate(setCertificateReq)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to execute sdk request 'esa.SetCertificate'")
|
||||
}
|
||||
|
||||
d.logger.Logt("已配置站点证书", setCertificateResp)
|
||||
|
||||
return &deployer.DeployResult{}, nil
|
||||
}
|
||||
|
||||
func createSdkClient(accessKeyId, accessKeySecret, region string) (*aliyunEsa.Client, error) {
|
||||
// 接入点一览 https://help.aliyun.com/zh/edge-security-acceleration/esa/api-esa-2024-09-10-endpoint
|
||||
config := &aliyunOpen.Config{
|
||||
AccessKeyId: tea.String(accessKeyId),
|
||||
AccessKeySecret: tea.String(accessKeySecret),
|
||||
Endpoint: tea.String(fmt.Sprintf("esa.%s.aliyuncs.com", region)),
|
||||
}
|
||||
|
||||
client, err := aliyunEsa.NewClient(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func createSslUploader(accessKeyId, accessKeySecret, region string) (uploader.Uploader, error) {
|
||||
casRegion := region
|
||||
if casRegion != "" {
|
||||
// 阿里云 CAS 服务接入点是独立于 ESA 服务的
|
||||
// 国内版固定接入点:华东一杭州
|
||||
// 国际版固定接入点:亚太东南一新加坡
|
||||
if casRegion != "" && !strings.HasPrefix(casRegion, "cn-") {
|
||||
casRegion = "ap-southeast-1"
|
||||
} else {
|
||||
casRegion = "cn-hangzhou"
|
||||
}
|
||||
}
|
||||
|
||||
uploader, err := uploaderp.New(&uploaderp.AliyunCASUploaderConfig{
|
||||
AccessKeyId: accessKeyId,
|
||||
AccessKeySecret: accessKeySecret,
|
||||
Region: casRegion,
|
||||
})
|
||||
return uploader, err
|
||||
}
|
@@ -0,0 +1,80 @@
|
||||
package aliyunesa_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
provider "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/aliyun-esa"
|
||||
)
|
||||
|
||||
var (
|
||||
fInputCertPath string
|
||||
fInputKeyPath string
|
||||
fAccessKeyId string
|
||||
fAccessKeySecret string
|
||||
fRegion string
|
||||
fSiteId int64
|
||||
)
|
||||
|
||||
func init() {
|
||||
argsPrefix := "CERTIMATE_DEPLOYER_ALIYUNESA_"
|
||||
|
||||
flag.StringVar(&fInputCertPath, argsPrefix+"INPUTCERTPATH", "", "")
|
||||
flag.StringVar(&fInputKeyPath, argsPrefix+"INPUTKEYPATH", "", "")
|
||||
flag.StringVar(&fAccessKeyId, argsPrefix+"ACCESSKEYID", "", "")
|
||||
flag.StringVar(&fAccessKeySecret, argsPrefix+"ACCESSKEYSECRET", "", "")
|
||||
flag.StringVar(&fRegion, argsPrefix+"REGION", "", "")
|
||||
flag.Int64Var(&fSiteId, argsPrefix+"SITEID", "", "")
|
||||
}
|
||||
|
||||
/*
|
||||
Shell command to run this test:
|
||||
|
||||
go test -v ./aliyun_esa_test.go -args \
|
||||
--CERTIMATE_DEPLOYER_ALIYUNESA_INPUTCERTPATH="/path/to/your-input-cert.pem" \
|
||||
--CERTIMATE_DEPLOYER_ALIYUNESA_INPUTKEYPATH="/path/to/your-input-key.pem" \
|
||||
--CERTIMATE_DEPLOYER_ALIYUNESA_ACCESSKEYID="your-access-key-id" \
|
||||
--CERTIMATE_DEPLOYER_ALIYUNESA_ACCESSKEYSECRET="your-access-key-secret" \
|
||||
--CERTIMATE_DEPLOYER_ALIYUNOSS_REGION="cn-hangzhou" \
|
||||
--CERTIMATE_DEPLOYER_ALIYUNESA_SITEID="your-esa-site-id"
|
||||
*/
|
||||
func TestDeploy(t *testing.T) {
|
||||
flag.Parse()
|
||||
|
||||
t.Run("Deploy", func(t *testing.T) {
|
||||
t.Log(strings.Join([]string{
|
||||
"args:",
|
||||
fmt.Sprintf("INPUTCERTPATH: %v", fInputCertPath),
|
||||
fmt.Sprintf("INPUTKEYPATH: %v", fInputKeyPath),
|
||||
fmt.Sprintf("ACCESSKEYID: %v", fAccessKeyId),
|
||||
fmt.Sprintf("ACCESSKEYSECRET: %v", fAccessKeySecret),
|
||||
fmt.Sprintf("REGION: %v", fRegion),
|
||||
fmt.Sprintf("SITEID: %v", fSiteId),
|
||||
}, "\n"))
|
||||
|
||||
deployer, err := provider.New(&provider.AliyunESADeployerConfig{
|
||||
AccessKeyId: fAccessKeyId,
|
||||
AccessKeySecret: fAccessKeySecret,
|
||||
Region: fRegion,
|
||||
SiteId: fSiteId,
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("err: %+v", err)
|
||||
return
|
||||
}
|
||||
|
||||
fInputCertData, _ := os.ReadFile(fInputCertPath)
|
||||
fInputKeyData, _ := os.ReadFile(fInputKeyPath)
|
||||
res, err := deployer.Deploy(context.Background(), string(fInputCertData), string(fInputKeyData))
|
||||
if err != nil {
|
||||
t.Errorf("err: %+v", err)
|
||||
return
|
||||
}
|
||||
|
||||
t.Logf("ok: %v", res)
|
||||
})
|
||||
}
|
@@ -114,6 +114,7 @@ func (d *AliyunWAFDeployer) Deploy(ctx context.Context, certPem string, privkeyP
|
||||
}
|
||||
|
||||
func createSdkClient(accessKeyId, accessKeySecret, region string) (*aliyunWaf.Client, error) {
|
||||
// 接入点一览:https://help.aliyun.com/zh/waf/web-application-firewall-3-0/developer-reference/api-waf-openapi-2021-10-01-endpoint
|
||||
config := &aliyunOpen.Config{
|
||||
AccessKeyId: tea.String(accessKeyId),
|
||||
AccessKeySecret: tea.String(accessKeySecret),
|
||||
|
@@ -0,0 +1,81 @@
|
||||
package baotapanelsite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
xerrors "github.com/pkg/errors"
|
||||
|
||||
"github.com/usual2970/certimate/internal/pkg/core/deployer"
|
||||
"github.com/usual2970/certimate/internal/pkg/core/logger"
|
||||
btsdk "github.com/usual2970/certimate/internal/pkg/vendors/btpanel-sdk"
|
||||
)
|
||||
|
||||
type BaotaPanelSiteDeployerConfig struct {
|
||||
// 宝塔面板地址。
|
||||
ApiUrl string `json:"apiUrl"`
|
||||
// 宝塔面板接口密钥。
|
||||
ApiKey string `json:"apiKey"`
|
||||
// 站点名称
|
||||
SiteName string `json:"siteName"`
|
||||
}
|
||||
|
||||
type BaotaPanelSiteDeployer struct {
|
||||
config *BaotaPanelSiteDeployerConfig
|
||||
logger logger.Logger
|
||||
sdkClient *btsdk.BaoTaPanelClient
|
||||
}
|
||||
|
||||
var _ deployer.Deployer = (*BaotaPanelSiteDeployer)(nil)
|
||||
|
||||
func New(config *BaotaPanelSiteDeployerConfig) (*BaotaPanelSiteDeployer, error) {
|
||||
return NewWithLogger(config, logger.NewNilLogger())
|
||||
}
|
||||
|
||||
func NewWithLogger(config *BaotaPanelSiteDeployerConfig, logger logger.Logger) (*BaotaPanelSiteDeployer, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New("config is nil")
|
||||
}
|
||||
|
||||
if logger == nil {
|
||||
return nil, errors.New("logger is nil")
|
||||
}
|
||||
|
||||
client, err := createSdkClient(config.ApiUrl, config.ApiKey)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to create sdk client")
|
||||
}
|
||||
|
||||
return &BaotaPanelSiteDeployer{
|
||||
logger: logger,
|
||||
config: config,
|
||||
sdkClient: client,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *BaotaPanelSiteDeployer) Deploy(ctx context.Context, certPem string, privkeyPem string) (*deployer.DeployResult, error) {
|
||||
if d.config.SiteName == "" {
|
||||
return nil, errors.New("config `siteName` is required")
|
||||
}
|
||||
|
||||
// 设置站点 SSL 证书
|
||||
setSiteSSLReq := &btsdk.SetSiteSSLRequest{
|
||||
SiteName: d.config.SiteName,
|
||||
Type: "1",
|
||||
Key: privkeyPem,
|
||||
Csr: certPem,
|
||||
}
|
||||
setSiteSSLResp, err := d.sdkClient.SetSiteSSL(setSiteSSLReq)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to execute sdk request 'bt.SetSiteSSL'")
|
||||
}
|
||||
|
||||
d.logger.Logt("已设置站点 SSL 证书", setSiteSSLResp)
|
||||
|
||||
return &deployer.DeployResult{}, nil
|
||||
}
|
||||
|
||||
func createSdkClient(apiUrl, apiKey string) (*btsdk.BaoTaPanelClient, error) {
|
||||
client := btsdk.NewBaoTaPanelClient(apiUrl, apiKey)
|
||||
return client, nil
|
||||
}
|
@@ -0,0 +1,75 @@
|
||||
package baotapanelsite_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
provider "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/baotapanel-site"
|
||||
)
|
||||
|
||||
var (
|
||||
fInputCertPath string
|
||||
fInputKeyPath string
|
||||
fApiUrl string
|
||||
fApiKey string
|
||||
fSiteName string
|
||||
)
|
||||
|
||||
func init() {
|
||||
argsPrefix := "CERTIMATE_DEPLOYER_BAOTAPANELSITE_"
|
||||
|
||||
flag.StringVar(&fInputCertPath, argsPrefix+"INPUTCERTPATH", "", "")
|
||||
flag.StringVar(&fInputKeyPath, argsPrefix+"INPUTKEYPATH", "", "")
|
||||
flag.StringVar(&fApiUrl, argsPrefix+"APIURL", "", "")
|
||||
flag.StringVar(&fApiKey, argsPrefix+"APIKEY", "", "")
|
||||
flag.StringVar(&fSiteName, argsPrefix+"SITENAME", "", "")
|
||||
}
|
||||
|
||||
/*
|
||||
Shell command to run this test:
|
||||
|
||||
go test -v ./baotapanel_site_test.go -args \
|
||||
--CERTIMATE_DEPLOYER_BAOTAPANELSITE_INPUTCERTPATH="/path/to/your-input-cert.pem" \
|
||||
--CERTIMATE_DEPLOYER_BAOTAPANELSITE_INPUTKEYPATH="/path/to/your-input-key.pem" \
|
||||
--CERTIMATE_DEPLOYER_BAOTAPANELSITE_APIURL="your-baota-panel-url" \
|
||||
--CERTIMATE_DEPLOYER_BAOTAPANELSITE_APIKEY="your-baota-panel-key" \
|
||||
--CERTIMATE_DEPLOYER_BAOTAPANELSITE_SITENAME="your-baota-site-name"
|
||||
*/
|
||||
func TestDeploy(t *testing.T) {
|
||||
flag.Parse()
|
||||
|
||||
t.Run("Deploy", func(t *testing.T) {
|
||||
t.Log(strings.Join([]string{
|
||||
"args:",
|
||||
fmt.Sprintf("INPUTCERTPATH: %v", fInputCertPath),
|
||||
fmt.Sprintf("INPUTKEYPATH: %v", fInputKeyPath),
|
||||
fmt.Sprintf("APIURL: %v", fApiUrl),
|
||||
fmt.Sprintf("APIKEY: %v", fApiKey),
|
||||
fmt.Sprintf("SITENAME: %v", fSiteName),
|
||||
}, "\n"))
|
||||
|
||||
deployer, err := provider.New(&provider.BaotaPanelSiteDeployerConfig{
|
||||
ApiUrl: fApiUrl,
|
||||
ApiKey: fApiKey,
|
||||
SiteName: fSiteName,
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("err: %+v", err)
|
||||
return
|
||||
}
|
||||
|
||||
fInputCertData, _ := os.ReadFile(fInputCertPath)
|
||||
fInputKeyData, _ := os.ReadFile(fInputKeyPath)
|
||||
res, err := deployer.Deploy(context.Background(), string(fInputCertData), string(fInputKeyData))
|
||||
if err != nil {
|
||||
t.Errorf("err: %+v", err)
|
||||
return
|
||||
}
|
||||
|
||||
t.Logf("ok: %v", res)
|
||||
})
|
||||
}
|
@@ -4,7 +4,7 @@ type DeployResourceType string
|
||||
|
||||
const (
|
||||
// 资源类型:通过 SSL 服务部署到云资源实例。
|
||||
DEPLOY_RESOURCE_USE_SSLDEPLOY = DeployResourceType("ssl-deploy")
|
||||
DEPLOY_RESOURCE_VIA_SSLDEPLOY = DeployResourceType("ssl-deploy")
|
||||
// 资源类型:部署到指定负载均衡器。
|
||||
DEPLOY_RESOURCE_LOADBALANCER = DeployResourceType("loadbalancer")
|
||||
// 资源类型:部署到指定监听器。
|
||||
|
@@ -96,8 +96,8 @@ func (d *TencentCloudCLBDeployer) Deploy(ctx context.Context, certPem string, pr
|
||||
|
||||
// 根据部署资源类型决定部署方式
|
||||
switch d.config.ResourceType {
|
||||
case DEPLOY_RESOURCE_USE_SSLDEPLOY:
|
||||
if err := d.deployToInstanceUseSsl(ctx, upres.CertId); err != nil {
|
||||
case DEPLOY_RESOURCE_VIA_SSLDEPLOY:
|
||||
if err := d.deployViaSslService(ctx, upres.CertId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ func (d *TencentCloudCLBDeployer) Deploy(ctx context.Context, certPem string, pr
|
||||
return &deployer.DeployResult{}, nil
|
||||
}
|
||||
|
||||
func (d *TencentCloudCLBDeployer) deployToInstanceUseSsl(ctx context.Context, cloudCertId string) error {
|
||||
func (d *TencentCloudCLBDeployer) deployViaSslService(ctx context.Context, cloudCertId string) error {
|
||||
if d.config.LoadbalancerId == "" {
|
||||
return errors.New("config `loadbalancerId` is required")
|
||||
}
|
||||
|
@@ -68,7 +68,7 @@ func TestDeploy(t *testing.T) {
|
||||
SecretId: fSecretId,
|
||||
SecretKey: fSecretKey,
|
||||
Region: fRegion,
|
||||
ResourceType: provider.DEPLOY_RESOURCE_USE_SSLDEPLOY,
|
||||
ResourceType: provider.DEPLOY_RESOURCE_VIA_SSLDEPLOY,
|
||||
LoadbalancerId: fLoadbalancerId,
|
||||
ListenerId: fListenerId,
|
||||
Domain: fDomain,
|
||||
|
@@ -0,0 +1,156 @@
|
||||
package tencentcloudssldeploy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
xerrors "github.com/pkg/errors"
|
||||
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
|
||||
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
|
||||
tcSsl "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ssl/v20191205"
|
||||
|
||||
"github.com/usual2970/certimate/internal/pkg/core/deployer"
|
||||
"github.com/usual2970/certimate/internal/pkg/core/logger"
|
||||
"github.com/usual2970/certimate/internal/pkg/core/uploader"
|
||||
uploaderp "github.com/usual2970/certimate/internal/pkg/core/uploader/providers/tencentcloud-ssl"
|
||||
)
|
||||
|
||||
type TencentCloudSSLDeployDeployerConfig struct {
|
||||
// 腾讯云 SecretId。
|
||||
SecretId string `json:"secretId"`
|
||||
// 腾讯云 SecretKey。
|
||||
SecretKey string `json:"secretKey"`
|
||||
// 腾讯云地域。
|
||||
Region string `json:"region"`
|
||||
// 腾讯云云资源类型。
|
||||
ResourceType string `json:"resourceType"`
|
||||
// 腾讯云云资源 ID 数组。
|
||||
ResourceIds []string `json:"resourceIds"`
|
||||
}
|
||||
|
||||
type TencentCloudSSLDeployDeployer struct {
|
||||
config *TencentCloudSSLDeployDeployerConfig
|
||||
logger logger.Logger
|
||||
sdkClient *tcSsl.Client
|
||||
sslUploader uploader.Uploader
|
||||
}
|
||||
|
||||
var _ deployer.Deployer = (*TencentCloudSSLDeployDeployer)(nil)
|
||||
|
||||
func New(config *TencentCloudSSLDeployDeployerConfig) (*TencentCloudSSLDeployDeployer, error) {
|
||||
return NewWithLogger(config, logger.NewNilLogger())
|
||||
}
|
||||
|
||||
func NewWithLogger(config *TencentCloudSSLDeployDeployerConfig, logger logger.Logger) (*TencentCloudSSLDeployDeployer, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New("config is nil")
|
||||
}
|
||||
|
||||
if logger == nil {
|
||||
return nil, errors.New("logger is nil")
|
||||
}
|
||||
|
||||
client, err := createSdkClient(config.SecretId, config.SecretKey, config.Region)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to create sdk client")
|
||||
}
|
||||
|
||||
uploader, err := uploaderp.New(&uploaderp.TencentCloudSSLUploaderConfig{
|
||||
SecretId: config.SecretId,
|
||||
SecretKey: config.SecretKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to create ssl uploader")
|
||||
}
|
||||
|
||||
return &TencentCloudSSLDeployDeployer{
|
||||
logger: logger,
|
||||
config: config,
|
||||
sdkClient: client,
|
||||
sslUploader: uploader,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *TencentCloudSSLDeployDeployer) Deploy(ctx context.Context, certPem string, privkeyPem string) (*deployer.DeployResult, error) {
|
||||
if d.config.ResourceType == "" {
|
||||
return nil, errors.New("config `resourceType` is required")
|
||||
}
|
||||
if len(d.config.ResourceIds) == 0 {
|
||||
return nil, errors.New("config `resourceIds` is required")
|
||||
}
|
||||
|
||||
// 上传证书到 SSL
|
||||
upres, err := d.sslUploader.Upload(ctx, certPem, privkeyPem)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to upload certificate file")
|
||||
}
|
||||
|
||||
d.logger.Logt("certificate file uploaded", upres)
|
||||
|
||||
// 证书部署到云资源实例列表
|
||||
// REF: https://cloud.tencent.com/document/product/400/91667
|
||||
deployCertificateInstanceReq := tcSsl.NewDeployCertificateInstanceRequest()
|
||||
deployCertificateInstanceReq.CertificateId = common.StringPtr(upres.CertId)
|
||||
deployCertificateInstanceReq.ResourceType = common.StringPtr(d.config.ResourceType)
|
||||
deployCertificateInstanceReq.InstanceIdList = common.StringPtrs(d.config.ResourceIds)
|
||||
deployCertificateInstanceReq.Status = common.Int64Ptr(1)
|
||||
deployCertificateInstanceResp, err := d.sdkClient.DeployCertificateInstance(deployCertificateInstanceReq)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to execute sdk request 'ssl.DeployCertificateInstance'")
|
||||
} else if deployCertificateInstanceResp.Response == nil || deployCertificateInstanceResp.Response.DeployRecordId == nil {
|
||||
return nil, errors.New("failed to create deploy record")
|
||||
}
|
||||
|
||||
d.logger.Logt("已部署证书到云资源实例", deployCertificateInstanceResp.Response)
|
||||
|
||||
// 循环获取部署任务详情,等待任务状态变更
|
||||
// REF: https://cloud.tencent.com.cn/document/api/400/91658
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
describeHostDeployRecordDetailReq := tcSsl.NewDescribeHostDeployRecordDetailRequest()
|
||||
describeHostDeployRecordDetailReq.DeployRecordId = common.StringPtr(fmt.Sprintf("%d", *deployCertificateInstanceResp.Response.DeployRecordId))
|
||||
describeHostDeployRecordDetailReq.Limit = common.Uint64Ptr(100)
|
||||
describeHostDeployRecordDetailResp, err := d.sdkClient.DescribeHostDeployRecordDetail(describeHostDeployRecordDetailReq)
|
||||
if err != nil {
|
||||
return nil, xerrors.Wrap(err, "failed to execute sdk request 'ssl.DescribeHostDeployRecordDetail'")
|
||||
}
|
||||
|
||||
if describeHostDeployRecordDetailResp.Response.TotalCount == nil {
|
||||
return nil, errors.New("部署任务状态异常")
|
||||
} else {
|
||||
acc := int64(0)
|
||||
if describeHostDeployRecordDetailResp.Response.SuccessTotalCount != nil {
|
||||
acc += *describeHostDeployRecordDetailResp.Response.SuccessTotalCount
|
||||
}
|
||||
if describeHostDeployRecordDetailResp.Response.FailedTotalCount != nil {
|
||||
acc += *describeHostDeployRecordDetailResp.Response.FailedTotalCount
|
||||
}
|
||||
|
||||
if acc == *describeHostDeployRecordDetailResp.Response.TotalCount {
|
||||
d.logger.Logt("已获取部署任务详情", describeHostDeployRecordDetailResp)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
d.logger.Logt("部署任务未完成 ...")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
|
||||
return &deployer.DeployResult{}, nil
|
||||
}
|
||||
|
||||
func createSdkClient(secretId, secretKey, region string) (*tcSsl.Client, error) {
|
||||
credential := common.NewCredential(secretId, secretKey)
|
||||
|
||||
client, err := tcSsl.NewClient(credential, region, profile.NewClientProfile())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
26
internal/pkg/vendors/btpanel-sdk/api.go
vendored
Normal file
26
internal/pkg/vendors/btpanel-sdk/api.go
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
package btpanelsdk
|
||||
|
||||
type BaseResponse interface {
|
||||
GetStatus() *bool
|
||||
GetMsg() *string
|
||||
}
|
||||
|
||||
type SetSiteSSLRequest struct {
|
||||
Type string `json:"type"`
|
||||
SiteName string `json:"siteName"`
|
||||
Key string `json:"key"`
|
||||
Csr string `json:"csr"`
|
||||
}
|
||||
|
||||
type SetSiteSSLResponse struct {
|
||||
Status *bool `json:"status,omitempty"`
|
||||
Msg *string `json:"msg,omitempty"`
|
||||
}
|
||||
|
||||
func (r *SetSiteSSLResponse) GetStatus() *bool {
|
||||
return r.Status
|
||||
}
|
||||
|
||||
func (r *SetSiteSSLResponse) GetMsg() *string {
|
||||
return r.Msg
|
||||
}
|
107
internal/pkg/vendors/btpanel-sdk/client.go
vendored
Normal file
107
internal/pkg/vendors/btpanel-sdk/client.go
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
package btpanelsdk
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
|
||||
"github.com/usual2970/certimate/internal/pkg/utils/maps"
|
||||
)
|
||||
|
||||
type BaoTaPanelClient struct {
|
||||
apiHost string
|
||||
apiKey string
|
||||
client *resty.Client
|
||||
}
|
||||
|
||||
func NewBaoTaPanelClient(apiHost, apiKey string) *BaoTaPanelClient {
|
||||
client := resty.New()
|
||||
|
||||
return &BaoTaPanelClient{
|
||||
apiHost: apiHost,
|
||||
apiKey: apiKey,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *BaoTaPanelClient) WithTimeout(timeout time.Duration) *BaoTaPanelClient {
|
||||
c.client.SetTimeout(timeout)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *BaoTaPanelClient) SetSiteSSL(req *SetSiteSSLRequest) (*SetSiteSSLResponse, error) {
|
||||
params := make(map[string]any)
|
||||
jsonData, _ := json.Marshal(req)
|
||||
json.Unmarshal(jsonData, ¶ms)
|
||||
|
||||
result := SetSiteSSLResponse{}
|
||||
err := c.sendRequestWithResult("/site?action=SetSSL", params, &result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (c *BaoTaPanelClient) generateSignature(timestamp string) string {
|
||||
keyMd5 := md5.Sum([]byte(c.apiKey))
|
||||
keyMd5Hex := strings.ToLower(hex.EncodeToString(keyMd5[:]))
|
||||
|
||||
signMd5 := md5.Sum([]byte(timestamp + keyMd5Hex))
|
||||
signMd5Hex := strings.ToLower(hex.EncodeToString(signMd5[:]))
|
||||
return signMd5Hex
|
||||
}
|
||||
|
||||
func (c *BaoTaPanelClient) sendRequest(path string, params map[string]any) (*resty.Response, error) {
|
||||
if params == nil {
|
||||
params = make(map[string]any)
|
||||
}
|
||||
|
||||
timestamp := time.Now().Unix()
|
||||
params["request_time"] = timestamp
|
||||
params["request_token"] = c.generateSignature(fmt.Sprintf("%d", timestamp))
|
||||
|
||||
url := strings.TrimRight(c.apiHost, "/") + path
|
||||
req := c.client.R().
|
||||
SetHeader("Content-Type", "application/json").
|
||||
SetBody(params)
|
||||
resp, err := req.Post(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("baota: failed to send request: %w", err)
|
||||
}
|
||||
|
||||
if resp.IsError() {
|
||||
return nil, fmt.Errorf("baota: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (c *BaoTaPanelClient) sendRequestWithResult(path string, params map[string]any, result BaseResponse) error {
|
||||
resp, err := c.sendRequest(path, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
jsonResp := make(map[string]any)
|
||||
if err := json.Unmarshal(resp.Body(), &jsonResp); err != nil {
|
||||
return fmt.Errorf("baota: failed to parse response: %w", err)
|
||||
}
|
||||
if err := maps.Decode(jsonResp, &result); err != nil {
|
||||
return fmt.Errorf("baota: failed to parse response: %w", err)
|
||||
}
|
||||
|
||||
if result.GetStatus() != nil && !*result.GetStatus() {
|
||||
if result.GetMsg() == nil {
|
||||
return fmt.Errorf("baota api error: unknown error")
|
||||
} else {
|
||||
return fmt.Errorf("baota api error: %s", result.GetMsg())
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
12
internal/pkg/vendors/gname-sdk/client.go
vendored
12
internal/pkg/vendors/gname-sdk/client.go
vendored
@@ -130,11 +130,11 @@ func (c *GnameClient) sendRequest(path string, params map[string]any) (*resty.Re
|
||||
SetFormData(data)
|
||||
resp, err := req.Post(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send request: %w", err)
|
||||
return nil, fmt.Errorf("gname: failed to send request: %w", err)
|
||||
}
|
||||
|
||||
if resp.IsError() {
|
||||
return nil, fmt.Errorf("unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
|
||||
return nil, fmt.Errorf("gname: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
@@ -148,14 +148,14 @@ func (c *GnameClient) sendRequestWithResult(path string, params map[string]any,
|
||||
|
||||
jsonResp := make(map[string]any)
|
||||
if err := json.Unmarshal(resp.Body(), &jsonResp); err != nil {
|
||||
return fmt.Errorf("failed to parse response: %w", err)
|
||||
return fmt.Errorf("gname: failed to parse response: %w", err)
|
||||
}
|
||||
if err := maps.Populate(jsonResp, &result); err != nil {
|
||||
return fmt.Errorf("failed to parse response: %w", err)
|
||||
if err := maps.Decode(jsonResp, &result); err != nil {
|
||||
return fmt.Errorf("gname: failed to parse response: %w", err)
|
||||
}
|
||||
|
||||
if result.GetCode() != 1 {
|
||||
return fmt.Errorf("API error: %s", result.GetMsg())
|
||||
return fmt.Errorf("gname api error: %s", result.GetMsg())
|
||||
}
|
||||
|
||||
return nil
|
||||
|
Reference in New Issue
Block a user