feat: add cachefly deployer

This commit is contained in:
Fu Diwei
2025-02-18 11:45:41 +08:00
parent 7c3f2399c2
commit 46f02331fd
52 changed files with 433 additions and 192 deletions

View File

@@ -61,7 +61,7 @@ func (d *BaotaPanelSiteDeployer) Deploy(ctx context.Context, certPem string, pri
// 设置站点 SSL 证书
siteSetSSLReq := &btsdk.SiteSetSSLRequest{
SiteName: d.config.SiteName,
Type: "1",
Type: "0",
PrivateKey: privkeyPem,
Certificate: certPem,
}

View File

@@ -0,0 +1,71 @@
package cachefly
import (
"context"
"errors"
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/cachefly-sdk"
)
type CacheFlyDeployerConfig struct {
// CacheFly API Token。
ApiToken string `json:"apiToken"`
}
type CacheFlyDeployer struct {
config *CacheFlyDeployerConfig
logger logger.Logger
sdkClient *cfsdk.Client
}
var _ deployer.Deployer = (*CacheFlyDeployer)(nil)
func New(config *CacheFlyDeployerConfig) (*CacheFlyDeployer, error) {
return NewWithLogger(config, logger.NewNilLogger())
}
func NewWithLogger(config *CacheFlyDeployerConfig, logger logger.Logger) (*CacheFlyDeployer, 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.ApiToken)
if err != nil {
return nil, xerrors.Wrap(err, "failed to create sdk client")
}
return &CacheFlyDeployer{
logger: logger,
config: config,
sdkClient: client,
}, nil
}
func (d *CacheFlyDeployer) Deploy(ctx context.Context, certPem string, privkeyPem string) (*deployer.DeployResult, error) {
// 上传证书
createCertificateReq := &cfsdk.CreateCertificateRequest{
Certificate: certPem,
CertificateKey: privkeyPem,
}
createCertificateResp, err := d.sdkClient.CreateCertificate(createCertificateReq)
if err != nil {
return nil, xerrors.Wrap(err, "failed to execute sdk request 'cachefly.CreateCertificate'")
} else {
d.logger.Logt("已上传证书", createCertificateResp)
}
return &deployer.DeployResult{}, nil
}
func createSdkClient(apiToken string) (*cfsdk.Client, error) {
client := cfsdk.NewClient(apiToken)
return client, nil
}

View File

@@ -0,0 +1,65 @@
package cachefly_test
import (
"context"
"flag"
"fmt"
"os"
"strings"
"testing"
provider "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/cachefly"
)
var (
fInputCertPath string
fInputKeyPath string
fApiToken string
)
func init() {
argsPrefix := "CERTIMATE_DEPLOYER_CACHEFLY_"
flag.StringVar(&fInputCertPath, argsPrefix+"INPUTCERTPATH", "", "")
flag.StringVar(&fInputKeyPath, argsPrefix+"INPUTKEYPATH", "", "")
flag.StringVar(&fApiToken, argsPrefix+"APITOKEN", "", "")
}
/*
Shell command to run this test:
go test -v ./cachefly_test.go -args \
--CERTIMATE_DEPLOYER_CACHEFLY_INPUTCERTPATH="/path/to/your-input-cert.pem" \
--CERTIMATE_DEPLOYER_CACHEFLY_INPUTKEYPATH="/path/to/your-input-key.pem" \
--CERTIMATE_DEPLOYER_CACHEFLY_APITOKEN="your-baota-panel-key"
*/
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("APITOKEN: %v", fApiToken),
}, "\n"))
deployer, err := provider.New(&provider.CacheFlyDeployerConfig{
ApiToken: fApiToken,
})
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

@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-resty/resty/v2"
@@ -32,7 +33,9 @@ func (c *Client) sendRequest(method string, path string, params map[string]any)
url := "https://cdn.api.baishan.com" + path
req := c.client.R()
if method == http.MethodGet {
req.Method = method
req.URL = url
if strings.EqualFold(method, http.MethodGet) {
data := make(map[string]string)
for k, v := range params {
data[k] = fmt.Sprintf("%v", v)
@@ -40,27 +43,18 @@ func (c *Client) sendRequest(method string, path string, params map[string]any)
req = req.
SetQueryParams(data).
SetQueryParam("token", c.apiToken)
} else if method == http.MethodPost {
} else {
req = req.
SetHeader("Content-Type", "application/json").
SetQueryParam("token", c.apiToken).
SetBody(params)
}
var resp *resty.Response
var err error
if method == http.MethodGet {
resp, err = req.Get(url)
} else if method == http.MethodPost {
resp, err = req.Post(url)
} else {
return nil, fmt.Errorf("baishan: unsupported method: %s", method)
}
resp, err := req.Send()
if err != nil {
return nil, fmt.Errorf("baishan: failed to send request: %w", err)
return nil, fmt.Errorf("baishan api error: failed to send request: %w", err)
} else if resp.IsError() {
return nil, fmt.Errorf("baishan: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
return nil, fmt.Errorf("baishan api error: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
}
return resp, nil
@@ -73,11 +67,9 @@ func (c *Client) sendRequestWithResult(method string, path string, params map[st
}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return fmt.Errorf("baishan: failed to parse response: %w", err)
}
if result.GetCode() != 0 {
return fmt.Errorf("baishan api error: %d, %s", result.GetCode(), result.GetMessage())
return fmt.Errorf("baishan api error: failed to parse response: %w", err)
} else if result.GetCode() != 0 {
return fmt.Errorf("baishan api error: %d - %s", result.GetCode(), result.GetMessage())
}
return nil

View File

@@ -36,12 +36,10 @@ type GetDomainConfigRequest struct {
type GetDomainConfigResponse struct {
baseResponse
Data []*GetDomainConfigResponseData `json:"data"`
}
type GetDomainConfigResponseData struct {
Domain string `json:"domain"`
Config *DomainConfig `json:"config"`
Data []*struct {
Domain string `json:"domain"`
Config *DomainConfig `json:"config"`
} `json:"data"`
}
type SetDomainConfigRequest struct {
@@ -51,11 +49,9 @@ type SetDomainConfigRequest struct {
type SetDomainConfigResponse struct {
baseResponse
Data *SetDomainConfigResponseData `json:"data"`
}
type SetDomainConfigResponseData struct {
Config *DomainConfig `json:"config"`
Data *struct {
Config *DomainConfig `json:"config"`
} `json:"data"`
}
type DomainCertificate struct {

View File

@@ -56,11 +56,9 @@ func (c *Client) sendRequest(path string, params map[string]any) (*resty.Respons
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 nil, fmt.Errorf("baota api error: failed to send request: %w", err)
} else if resp.IsError() {
return nil, fmt.Errorf("baota api error: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
}
return resp, nil
@@ -73,10 +71,8 @@ func (c *Client) sendRequestWithResult(path string, params map[string]any, resul
}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return fmt.Errorf("baota: failed to parse response: %w", err)
}
if result.GetStatus() != nil && !*result.GetStatus() {
return fmt.Errorf("baota api error: failed to parse response: %w", err)
} else if result.GetStatus() != nil && !*result.GetStatus() {
if result.GetMsg() == nil {
return fmt.Errorf("baota api error: unknown error")
} else {

View File

@@ -0,0 +1,19 @@
package cacheflysdk
import (
"encoding/json"
"net/http"
)
func (c *Client) CreateCertificate(req *CreateCertificateRequest) (*CreateCertificateResponse, error) {
params := make(map[string]any)
jsonData, _ := json.Marshal(req)
json.Unmarshal(jsonData, &params)
result := CreateCertificateResponse{}
err := c.sendRequestWithResult(http.MethodPost, "/certificates", params, &result)
if err != nil {
return nil, err
}
return &result, nil
}

View File

@@ -0,0 +1,72 @@
package cacheflysdk
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-resty/resty/v2"
)
type Client struct {
apiToken string
client *resty.Client
}
func NewClient(apiToken string) *Client {
client := resty.New()
return &Client{
apiToken: apiToken,
client: client,
}
}
func (c *Client) WithTimeout(timeout time.Duration) *Client {
c.client.SetTimeout(timeout)
return c
}
func (c *Client) sendRequest(method string, path string, params map[string]any) (*resty.Response, error) {
url := "https://api.cachefly.com/api/2.5" + path
req := c.client.R()
req.Method = method
req.URL = url
req = req.SetHeader("x-cf-authorization", "Bearer "+c.apiToken)
if strings.EqualFold(method, http.MethodGet) {
data := make(map[string]string)
for k, v := range params {
data[k] = fmt.Sprintf("%v", v)
}
req = req.SetQueryParams(data)
} else {
req = req.
SetHeader("Content-Type", "application/json").
SetBody(params)
}
resp, err := req.Send()
if err != nil {
return nil, fmt.Errorf("cachefly api error: failed to send request: %w", err)
} else if resp.IsError() {
return nil, fmt.Errorf("cachefly api error: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
}
return resp, nil
}
func (c *Client) sendRequestWithResult(method string, path string, params map[string]any, result BaseResponse) error {
resp, err := c.sendRequest(method, path, params)
if err != nil {
return err
}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return fmt.Errorf("cachefly api error: failed to parse response: %w", err)
}
return nil
}

View File

@@ -0,0 +1,35 @@
package cacheflysdk
type BaseResponse interface {
GetMessage() *string
}
type baseResponse struct {
Message *string `json:"message,omitempty"`
}
func (r *baseResponse) GetMessage() *string {
return r.Message
}
type CreateCertificateRequest struct {
Certificate string `json:"certificate"`
CertificateKey string `json:"certificateKey"`
Password *string `json:"password"`
}
type CreateCertificateResponse struct {
baseResponse
Id string `json:"_id"`
SubjectCommonName string `json:"subjectCommonName"`
SubjectNames []string `json:"subjectNames"`
Expired bool `json:"expired"`
Expiring bool `json:"expiring"`
InUse bool `json:"inUse"`
Managed bool `json:"managed"`
Services []string `json:"services"`
Domains []string `json:"domains"`
NotBefore string `json:"notBefore"`
NotAfter string `json:"notAfter"`
CreatedAt string `json:"createdAt"`
}

View File

@@ -76,9 +76,9 @@ func (c *Client) sendRequest(path string, params map[string]any) (*resty.Respons
SetFormData(data)
resp, err := req.Post(url)
if err != nil {
return nil, fmt.Errorf("gname: failed to send request: %w", err)
return nil, fmt.Errorf("gname api error: failed to send request: %w", err)
} else if resp.IsError() {
return nil, fmt.Errorf("gname: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
return nil, fmt.Errorf("gname api error: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
}
return resp, nil
@@ -91,11 +91,9 @@ func (c *Client) sendRequestWithResult(path string, params map[string]any, resul
}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return fmt.Errorf("gname: failed to parse response: %w", err)
}
if result.GetCode() != 1 {
return fmt.Errorf("gname api error: %s", result.GetMsg())
return fmt.Errorf("gname api error: failed to parse response: %w", err)
} else if result.GetCode() != 1 {
return fmt.Errorf("gname api error: %d - %s", result.GetCode(), result.GetMsg())
}
return nil

View File

@@ -42,11 +42,9 @@ func (c *Client) sendRequest(path string, params map[string]any) (*resty.Respons
SetBody(params)
resp, err := req.Post(url)
if err != nil {
return nil, fmt.Errorf("safeline: failed to send request: %w", err)
}
if resp.IsError() {
return nil, fmt.Errorf("safeline: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
return nil, fmt.Errorf("safeline api error: failed to send request: %w", err)
} else if resp.IsError() {
return nil, fmt.Errorf("safeline api error: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
}
return resp, nil
@@ -59,14 +57,12 @@ func (c *Client) sendRequestWithResult(path string, params map[string]any, resul
}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return fmt.Errorf("safeline: failed to parse response: %w", err)
}
if result.GetErrCode() != nil && *result.GetErrCode() != "" {
return fmt.Errorf("safeline api error: failed to parse response: %w", err)
} else if result.GetErrCode() != nil && *result.GetErrCode() != "" {
if result.GetErrMsg() == nil {
return fmt.Errorf("safeline api error: %s", *result.GetErrCode())
} else {
return fmt.Errorf("safeline api error: %s, %s", *result.GetErrCode(), *result.GetErrMsg())
return fmt.Errorf("safeline api error: %s - %s", *result.GetErrCode(), *result.GetErrMsg())
}
}