feat: add cdnfly deployer

This commit is contained in:
Fu Diwei
2025-02-18 15:14:24 +08:00
parent 46f02331fd
commit 03d2f4ca32
122 changed files with 955 additions and 243 deletions

View File

@@ -0,0 +1,180 @@
package cdnfly
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"time"
xerrors "github.com/pkg/errors"
"github.com/usual2970/certimate/internal/pkg/core/deployer"
"github.com/usual2970/certimate/internal/pkg/core/logger"
cfsdk "github.com/usual2970/certimate/internal/pkg/vendors/cdnfly-sdk"
)
type CdnflyDeployerConfig struct {
// Cdnfly 地址。
ApiUrl string `json:"apiUrl"`
// Cdnfly 用户端 API Key。
ApiKey string `json:"apiKey"`
// Cdnfly 用户端 API Secret。
ApiSecret string `json:"apiSecret"`
// 部署资源类型。
ResourceType ResourceType `json:"resourceType"`
// 网站 ID。
// 部署资源类型为 [RESOURCE_TYPE_SITE] 时必填。
SiteId string `json:"siteId,omitempty"`
// 证书 ID。
// 部署资源类型为 [RESOURCE_TYPE_CERTIFICATE] 时必填。
CertificateId string `json:"certificateId,omitempty"`
}
type CdnflyDeployer struct {
config *CdnflyDeployerConfig
logger logger.Logger
sdkClient *cfsdk.Client
}
var _ deployer.Deployer = (*CdnflyDeployer)(nil)
func New(config *CdnflyDeployerConfig) (*CdnflyDeployer, error) {
return NewWithLogger(config, logger.NewNilLogger())
}
func NewWithLogger(config *CdnflyDeployerConfig, logger logger.Logger) (*CdnflyDeployer, error) {
if config == nil {
panic("config is nil")
}
if logger == nil {
panic("logger is nil")
}
client, err := createSdkClient(config.ApiUrl, config.ApiKey, config.ApiSecret)
if err != nil {
return nil, xerrors.Wrap(err, "failed to create sdk client")
}
return &CdnflyDeployer{
logger: logger,
config: config,
sdkClient: client,
}, nil
}
func (d *CdnflyDeployer) Deploy(ctx context.Context, certPem string, privkeyPem string) (*deployer.DeployResult, error) {
// 根据部署资源类型决定部署方式
switch d.config.ResourceType {
case RESOURCE_TYPE_SITE:
if err := d.deployToSite(ctx, certPem, privkeyPem); err != nil {
return nil, err
}
case RESOURCE_TYPE_CERTIFICATE:
if err := d.deployToCertificate(ctx, certPem, privkeyPem); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unsupported resource type: %s", d.config.ResourceType)
}
return &deployer.DeployResult{}, nil
}
func (d *CdnflyDeployer) deployToSite(ctx context.Context, certPem string, privkeyPem string) error {
if d.config.SiteId == "" {
return errors.New("config `siteId` is required")
}
// 获取单个网站详情
// REF: https://doc.cdnfly.cn/wangzhanguanli-v1-sites.html#%E8%8E%B7%E5%8F%96%E5%8D%95%E4%B8%AA%E7%BD%91%E7%AB%99%E8%AF%A6%E6%83%85
getSiteReq := &cfsdk.GetSiteRequest{
Id: d.config.SiteId,
}
getSiteResp, err := d.sdkClient.GetSite(getSiteReq)
if err != nil {
return xerrors.Wrap(err, "failed to execute sdk request 'cdnfly.GetSite'")
} else {
d.logger.Logt("已获取网站详情", getSiteResp)
}
// 添加单个证书
// REF: https://doc.cdnfly.cn/wangzhanzhengshu-v1-certs.html#%E6%B7%BB%E5%8A%A0%E5%8D%95%E4%B8%AA%E6%88%96%E5%A4%9A%E4%B8%AA%E8%AF%81%E4%B9%A6-%E5%A4%9A%E4%B8%AA%E8%AF%81%E4%B9%A6%E6%97%B6%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F%E4%B8%BA%E6%95%B0%E7%BB%84
createCertificateReq := &cfsdk.CreateCertificateRequest{
Name: fmt.Sprintf("certimate-%d", time.Now().UnixMilli()),
Type: "custom",
Cert: certPem,
Key: privkeyPem,
}
createCertificateResp, err := d.sdkClient.CreateCertificate(createCertificateReq)
if err != nil {
return xerrors.Wrap(err, "failed to execute sdk request 'cdnfly.CreateCertificate'")
} else {
d.logger.Logt("已添加证书", createCertificateResp)
}
// 修改单个网站
// REF: https://doc.cdnfly.cn/wangzhanguanli-v1-sites.html#%E4%BF%AE%E6%94%B9%E5%8D%95%E4%B8%AA%E7%BD%91%E7%AB%99
updateSiteHttpsListenMap := make(map[string]any)
_ = json.Unmarshal([]byte(getSiteResp.Data.HttpsListen), &updateSiteHttpsListenMap)
updateSiteHttpsListenMap["cert"] = createCertificateResp.Data
updateSiteHttpsListenData, _ := json.Marshal(updateSiteHttpsListenMap)
updateSiteHttpsListen := string(updateSiteHttpsListenData)
updateSiteReq := &cfsdk.UpdateSiteRequest{
Id: d.config.SiteId,
HttpsListen: &updateSiteHttpsListen,
}
updateSiteResp, err := d.sdkClient.UpdateSite(updateSiteReq)
if err != nil {
return xerrors.Wrap(err, "failed to execute sdk request 'cdnfly.UpdateSite'")
} else {
d.logger.Logt("已修改网站", updateSiteResp)
}
return nil
}
func (d *CdnflyDeployer) deployToCertificate(ctx context.Context, certPem string, privkeyPem string) error {
if d.config.CertificateId == "" {
return errors.New("config `certificateId` is required")
}
// 修改单个证书
// REF: https://doc.cdnfly.cn/wangzhanzhengshu-v1-certs.html#%E4%BF%AE%E6%94%B9%E5%8D%95%E4%B8%AA%E8%AF%81%E4%B9%A6
updateCertificateType := "custom"
updateCertificateReq := &cfsdk.UpdateCertificateRequest{
Id: d.config.CertificateId,
Type: &updateCertificateType,
Cert: &certPem,
Key: &privkeyPem,
}
updateCertificateResp, err := d.sdkClient.UpdateCertificate(updateCertificateReq)
if err != nil {
return xerrors.Wrap(err, "failed to execute sdk request 'cdnfly.UpdateCertificate'")
} else {
d.logger.Logt("已修改证书", updateCertificateResp)
}
return nil
}
func createSdkClient(apiUrl, apiKey, apiSecret string) (*cfsdk.Client, error) {
if _, err := url.Parse(apiUrl); err != nil {
return nil, errors.New("invalid cachefly api url")
}
if apiKey == "" {
return nil, errors.New("invalid cachefly api key")
}
if apiSecret == "" {
return nil, errors.New("invalid cachefly api secret")
}
client := cfsdk.NewClient(apiUrl, apiKey, apiSecret)
return client, nil
}

View File

@@ -0,0 +1,81 @@
package cdnfly_test
import (
"context"
"flag"
"fmt"
"os"
"strings"
"testing"
provider "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/cdnfly"
)
var (
fInputCertPath string
fInputKeyPath string
fApiUrl string
fApiKey string
fApiSecret string
fCertificateId string
)
func init() {
argsPrefix := "CERTIMATE_DEPLOYER_CDNFLY_"
flag.StringVar(&fInputCertPath, argsPrefix+"INPUTCERTPATH", "", "")
flag.StringVar(&fInputKeyPath, argsPrefix+"INPUTKEYPATH", "", "")
flag.StringVar(&fApiUrl, argsPrefix+"APIURL", "", "")
flag.StringVar(&fApiKey, argsPrefix+"APIKEY", "", "")
flag.StringVar(&fApiSecret, argsPrefix+"APISECRET", "", "")
flag.StringVar(&fCertificateId, argsPrefix+"CERTIFICATEID", "", "")
}
/*
Shell command to run this test:
go test -v ./cdnfly_test.go -args \
--CERTIMATE_DEPLOYER_CDNFLY_INPUTCERTPATH="/path/to/your-input-cert.pem" \
--CERTIMATE_DEPLOYER_CDNFLY_INPUTKEYPATH="/path/to/your-input-key.pem" \
--CERTIMATE_DEPLOYER_CDNFLY_APIURL="http://127.0.0.1:88" \
--CERTIMATE_DEPLOYER_CDNFLY_APIKEY="your-api-key" \
--CERTIMATE_DEPLOYER_CDNFLY_APISECRET="your-api-secret" \
--CERTIMATE_DEPLOYER_CDNFLY_CERTIFICATEID="your-cert-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("APIURL: %v", fApiUrl),
fmt.Sprintf("APIKEY: %v", fApiKey),
fmt.Sprintf("APISECRET: %v", fApiSecret),
fmt.Sprintf("CERTIFICATEID: %v", fCertificateId),
}, "\n"))
deployer, err := provider.New(&provider.CdnflyDeployerConfig{
ApiUrl: fApiUrl,
ApiKey: fApiKey,
ApiSecret: fApiSecret,
ResourceType: provider.RESOURCE_TYPE_CERTIFICATE,
CertificateId: fCertificateId,
})
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)
})
}

View File

@@ -0,0 +1,10 @@
package cdnfly
type ResourceType string
const (
// 资源类型:替换指定网站的证书。
RESOURCE_TYPE_SITE = ResourceType("site")
// 资源类型:替换指定证书。
RESOURCE_TYPE_CERTIFICATE = ResourceType("certificate")
)