Merge pull request #610 from imlonghao/feat/bunny

feat: support bunny as dns and cdn provider
This commit is contained in:
Yoan.liu
2025-04-19 10:45:51 +08:00
committed by GitHub
26 changed files with 690 additions and 0 deletions

View File

@@ -11,6 +11,7 @@ import (
pAWSRoute53 "github.com/usual2970/certimate/internal/pkg/core/applicant/acme-dns-01/lego-providers/aws-route53"
pAzureDNS "github.com/usual2970/certimate/internal/pkg/core/applicant/acme-dns-01/lego-providers/azure-dns"
pBaiduCloud "github.com/usual2970/certimate/internal/pkg/core/applicant/acme-dns-01/lego-providers/baiducloud"
pBunny "github.com/usual2970/certimate/internal/pkg/core/applicant/acme-dns-01/lego-providers/bunny"
pCloudflare "github.com/usual2970/certimate/internal/pkg/core/applicant/acme-dns-01/lego-providers/cloudflare"
pClouDNS "github.com/usual2970/certimate/internal/pkg/core/applicant/acme-dns-01/lego-providers/cloudns"
pCMCCCloud "github.com/usual2970/certimate/internal/pkg/core/applicant/acme-dns-01/lego-providers/cmcccloud"
@@ -128,6 +129,21 @@ func createApplicant(options *applicantOptions) (challenge.Provider, error) {
return applicant, err
}
case domain.ApplyDNSProviderTypeBunny:
{
access := domain.AccessConfigForBunny{}
if err := maputil.Populate(options.ProviderAccessConfig, &access); err != nil {
return nil, fmt.Errorf("failed to populate provider access config: %w", err)
}
applicant, err := pBunny.NewChallengeProvider(&pBunny.ChallengeProviderConfig{
ApiKey: access.ApiKey,
DnsPropagationTimeout: options.DnsPropagationTimeout,
DnsTTL: options.DnsTTL,
})
return applicant, err
}
case domain.ApplyDNSProviderTypeCloudflare:
{
access := domain.AccessConfigForCloudflare{}

View File

@@ -31,6 +31,7 @@ import (
pBaishanCDN "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/baishan-cdn"
pBaotaPanelConsole "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/baotapanel-console"
pBaotaPanelSite "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/baotapanel-site"
pBunnyCDN "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/bunny-cdn"
pBytePlusCDN "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/byteplus-cdn"
pCacheFly "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/cachefly"
pCdnfly "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/cdnfly"
@@ -416,6 +417,21 @@ func createDeployer(options *deployerOptions) (deployer.Deployer, error) {
}
}
case domain.DeployProviderTypeBunnyCDN:
{
access := domain.AccessConfigForBunny{}
if err := maputil.Populate(options.ProviderAccessConfig, &access); err != nil {
return nil, fmt.Errorf("failed to populate provider access config: %w", err)
}
deployer, err := pBunnyCDN.NewDeployer(&pBunnyCDN.DeployerConfig{
ApiKey: access.ApiKey,
PullZoneId: maputil.GetString(options.ProviderDeployConfig, "pullZoneId"),
HostName: maputil.GetString(options.ProviderDeployConfig, "hostName"),
})
return deployer, err
}
case domain.DeployProviderTypeBytePlusCDN:
{
access := domain.AccessConfigForBytePlus{}

View File

@@ -64,6 +64,10 @@ type AccessConfigForBytePlus struct {
SecretKey string `json:"secretKey"`
}
type AccessConfigForBunny struct {
ApiKey string `json:"apiKey"`
}
type AccessConfigForCacheFly struct {
ApiToken string `json:"apiToken"`
}

View File

@@ -104,6 +104,7 @@ const (
ApplyDNSProviderTypeAzureDNS = ApplyDNSProviderType("azure-dns")
ApplyDNSProviderTypeBaiduCloud = ApplyDNSProviderType("baiducloud") // 兼容旧值,等同于 [ApplyDNSProviderTypeBaiduCloudDNS]
ApplyDNSProviderTypeBaiduCloudDNS = ApplyDNSProviderType("baiducloud-dns")
ApplyDNSProviderTypeBunny = ApplyDNSProviderType("bunny")
ApplyDNSProviderTypeCloudflare = ApplyDNSProviderType("cloudflare")
ApplyDNSProviderTypeClouDNS = ApplyDNSProviderType("cloudns")
ApplyDNSProviderTypeCMCCCloud = ApplyDNSProviderType("cmcccloud")
@@ -168,6 +169,7 @@ const (
DeployProviderTypeBaishanCDN = DeployProviderType("baishan-cdn")
DeployProviderTypeBaotaPanelConsole = DeployProviderType("baotapanel-console")
DeployProviderTypeBaotaPanelSite = DeployProviderType("baotapanel-site")
DeployProviderTypeBunnyCDN = DeployProviderType("bunny-cdn")
DeployProviderTypeBytePlusCDN = DeployProviderType("byteplus-cdn")
DeployProviderTypeCacheFly = DeployProviderType("cachefly")
DeployProviderTypeCdnfly = DeployProviderType("cdnfly")

View File

@@ -0,0 +1,36 @@
package bunny
import (
"time"
"github.com/go-acme/lego/v4/challenge"
"github.com/go-acme/lego/v4/providers/dns/bunny"
)
type ChallengeProviderConfig struct {
ApiKey string `json:"apiKey"`
DnsPropagationTimeout int32 `json:"dnsPropagationTimeout,omitempty"`
DnsTTL int32 `json:"dnsTTL,omitempty"`
}
func NewChallengeProvider(config *ChallengeProviderConfig) (challenge.Provider, error) {
if config == nil {
panic("config is nil")
}
providerConfig := bunny.NewDefaultConfig()
providerConfig.APIKey = config.ApiKey
if config.DnsPropagationTimeout != 0 {
providerConfig.PropagationTimeout = time.Duration(config.DnsPropagationTimeout) * time.Second
}
if config.DnsTTL != 0 {
providerConfig.TTL = int(config.DnsTTL)
}
provider, err := bunny.NewDNSProviderConfig(providerConfig)
if err != nil {
return nil, err
}
return provider, nil
}

View File

@@ -0,0 +1,70 @@
package bunnycdn
import (
"context"
"encoding/base64"
"log/slog"
xerrors "github.com/pkg/errors"
"github.com/usual2970/certimate/internal/pkg/core/deployer"
bunnysdk "github.com/usual2970/certimate/internal/pkg/vendors/bunny-sdk"
)
type DeployerConfig struct {
// Bunny API Key
ApiKey string `json:"apiKey"`
// Bunny Pull Zone ID
PullZoneId string `json:"pullZoneId"`
// Bunny CDN Hostname支持泛域名
HostName string `json:"hostName"`
}
type DeployerProvider struct {
config *DeployerConfig
logger *slog.Logger
sdkClient *bunnysdk.Client
}
var _ deployer.Deployer = (*DeployerProvider)(nil)
func NewDeployer(config *DeployerConfig) (*DeployerProvider, error) {
if config == nil {
panic("config is nil")
}
return &DeployerProvider{
config: config,
logger: slog.Default(),
sdkClient: bunnysdk.NewClient(config.ApiKey),
}, nil
}
func (d *DeployerProvider) WithLogger(logger *slog.Logger) deployer.Deployer {
if logger == nil {
d.logger = slog.Default()
} else {
d.logger = logger
}
return d
}
func (d *DeployerProvider) Deploy(ctx context.Context, certPem string, privkeyPem string) (*deployer.DeployResult, error) {
// Prepare
certPemBase64 := base64.StdEncoding.EncodeToString([]byte(certPem))
privkeyPemBase64 := base64.StdEncoding.EncodeToString([]byte(privkeyPem))
// 上传证书
createCertificateReq := &bunnysdk.AddCustomCertificateRequest{
Hostname: d.config.HostName,
PullZoneId: d.config.PullZoneId,
Certificate: certPemBase64,
CertificateKey: privkeyPemBase64,
}
createCertificateResp, err := d.sdkClient.AddCustomCertificate(createCertificateReq)
d.logger.Debug("sdk request 'bunny-cdn.AddCustomCertificate'", slog.Any("request", createCertificateReq), slog.Any("response", createCertificateResp))
if err != nil {
return nil, xerrors.Wrap(err, "failed to execute sdk request 'bunny-cdn.AddCustomCertificate'")
}
return &deployer.DeployResult{}, nil
}

View File

@@ -0,0 +1,75 @@
package bunnycdn_test
import (
"context"
"flag"
"fmt"
"os"
"strings"
"testing"
provider "github.com/usual2970/certimate/internal/pkg/core/deployer/providers/bunny-cdn"
)
var (
fInputCertPath string
fInputKeyPath string
fApiKey string
fPullZoneId string
fHostName string
)
func init() {
argsPrefix := "CERTIMATE_DEPLOYER_BUNNYCDN_"
flag.StringVar(&fInputCertPath, argsPrefix+"INPUTCERTPATH", "", "")
flag.StringVar(&fInputKeyPath, argsPrefix+"INPUTKEYPATH", "", "")
flag.StringVar(&fApiKey, argsPrefix+"APIKEY", "", "")
flag.StringVar(&fPullZoneId, argsPrefix+"PULLZONEID", "", "")
flag.StringVar(&fHostName, argsPrefix+"HOSTNAME", "", "")
}
/*
Shell command to run this test:
go test -v ./bunny_cdn_test.go -args \
--CERTIMATE_DEPLOYER_BUNNYCDN_INPUTCERTPATH="/path/to/your-input-cert.pem" \
--CERTIMATE_DEPLOYER_BUNNYCDN_INPUTKEYPATH="/path/to/your-input-key.pem" \
--CERTIMATE_DEPLOYER_BUNNYCDN_APITOKEN="your-api-token" \
--CERTIMATE_DEPLOYER_BUNNYCDN_PULLZONEID="your-pull-zone-id" \
--CERTIMATE_DEPLOYER_BUNNYCDN_HOSTNAME="example.com"
*/
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("APIKEY: %v", fApiKey),
fmt.Sprintf("PULLZONEID: %v", fPullZoneId),
fmt.Sprintf("HOSTNAME: %v", fHostName),
}, "\n"))
deployer, err := provider.NewDeployer(&provider.DeployerConfig{
ApiKey: fApiKey,
PullZoneId: fPullZoneId,
HostName: fHostName,
})
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)
})
}

11
internal/pkg/vendors/bunny-sdk/api.go vendored Normal file
View File

@@ -0,0 +1,11 @@
package bunnysdk
import (
"fmt"
"net/http"
)
func (c *Client) AddCustomCertificate(req *AddCustomCertificateRequest) ([]byte, error) {
resp, err := c.sendRequest(http.MethodPost, fmt.Sprintf("/pullzone/%s/addCertificate", req.PullZoneId), req)
return resp.Body(), err
}

View File

@@ -0,0 +1,66 @@
package bunnysdk
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 interface{}) (*resty.Response, error) {
req := c.client.R()
req.Method = method
req.URL = "https://api.bunny.net" + path
req = req.SetHeader("AccessKey", c.apiToken)
if strings.EqualFold(method, http.MethodGet) {
qs := make(map[string]string)
if params != nil {
temp := make(map[string]any)
jsonb, _ := json.Marshal(params)
json.Unmarshal(jsonb, &temp)
for k, v := range temp {
if v != nil {
qs[k] = fmt.Sprintf("%v", v)
}
}
}
req = req.SetQueryParams(qs)
} else {
req = req.
SetHeader("Content-Type", "application/json").
SetBody(params)
}
resp, err := req.Send()
if err != nil {
return resp, fmt.Errorf("bunny api error: failed to send request: %w", err)
} else if resp.IsError() {
return resp, fmt.Errorf("bunny api error: unexpected status code: %d, %s", resp.StatusCode(), resp.Body())
}
return resp, nil
}

View File

@@ -0,0 +1,8 @@
package bunnysdk
type AddCustomCertificateRequest struct {
Hostname string `json:"Hostname"`
PullZoneId string `json:"-"`
Certificate string `json:"Certificate"`
CertificateKey string `json:"CertificateKey"`
}