refactor: clean code

This commit is contained in:
Fu Diwei 2025-01-05 03:34:46 +08:00
parent 7cf96d7d7e
commit 8af5235e4d
9 changed files with 214 additions and 218 deletions

View File

@ -0,0 +1,35 @@
package applicant
const defaultSSLProvider = "letsencrypt"
const (
sslProviderLetsencrypt = "letsencrypt"
sslProviderZeroSSL = "zerossl"
sslProviderGts = "gts"
)
const (
zerosslUrl = "https://acme.zerossl.com/v2/DV90"
letsencryptUrl = "https://acme-v02.api.letsencrypt.org/directory"
gtsUrl = "https://dv.acme-v02.api.pki.goog/directory"
)
var sslProviderUrls = map[string]string{
sslProviderLetsencrypt: letsencryptUrl,
sslProviderZeroSSL: zerosslUrl,
sslProviderGts: gtsUrl,
}
type acmeSSLProviderConfig struct {
Config acmeSSLProviderConfigContent `json:"config"`
Provider string `json:"provider"`
}
type acmeSSLProviderConfigContent struct {
Zerossl acmeSSLProviderEab `json:"zerossl"`
Gts acmeSSLProviderEab `json:"gts"`
}
type acmeSSLProviderEab struct {
EabHmacKey string `json:"eabHmacKey"`
EabKid string `json:"eabKid"`
}

View File

@ -0,0 +1,126 @@
package applicant
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt"
"github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/registration"
"github.com/usual2970/certimate/internal/domain"
"github.com/usual2970/certimate/internal/pkg/utils/x509"
"github.com/usual2970/certimate/internal/repository"
)
type acmeUser struct {
CA string
Email string
Registration *registration.Resource
privkey string
}
func newAcmeUser(ca, email string) (*acmeUser, error) {
repo := repository.NewAcmeAccountRepository()
applyUser := &acmeUser{
CA: ca,
Email: email,
}
acmeAccount, err := repo.GetByCAAndEmail(ca, email)
if err != nil {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
keyStr, err := x509.ConvertECPrivateKeyToPEM(key)
if err != nil {
return nil, err
}
applyUser.privkey = keyStr
return applyUser, nil
}
applyUser.Registration = acmeAccount.Resource
applyUser.privkey = acmeAccount.Key
return applyUser, nil
}
func (u *acmeUser) GetEmail() string {
return u.Email
}
func (u acmeUser) GetRegistration() *registration.Resource {
return u.Registration
}
func (u *acmeUser) GetPrivateKey() crypto.PrivateKey {
rs, _ := x509.ParseECPrivateKeyFromPEM(u.privkey)
return rs
}
func (u *acmeUser) hasRegistration() bool {
return u.Registration != nil
}
func (u *acmeUser) getPrivateKeyPEM() string {
return u.privkey
}
type AcmeAccountRepository interface {
GetByCAAndEmail(ca, email string) (*domain.AcmeAccount, error)
Save(ca, email, key string, resource *registration.Resource) error
}
func registerAcmeUser(client *lego.Client, sslProvider *acmeSSLProviderConfig, user *acmeUser) (*registration.Resource, error) {
// TODO: fix 潜在的并发问题
var reg *registration.Resource
var err error
switch sslProvider.Provider {
case sslProviderZeroSSL:
reg, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
TermsOfServiceAgreed: true,
Kid: sslProvider.Config.Zerossl.EabKid,
HmacEncoded: sslProvider.Config.Zerossl.EabHmacKey,
})
case sslProviderGts:
reg, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
TermsOfServiceAgreed: true,
Kid: sslProvider.Config.Gts.EabKid,
HmacEncoded: sslProvider.Config.Gts.EabHmacKey,
})
case sslProviderLetsencrypt:
reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
default:
err = errors.New("unknown ssl provider")
}
if err != nil {
return nil, err
}
repo := repository.NewAcmeAccountRepository()
resp, err := repo.GetByCAAndEmail(sslProvider.Provider, user.GetEmail())
if err == nil {
user.privkey = resp.Key
return resp.Resource, nil
}
if err := repo.Save(sslProvider.Provider, user.GetEmail(), user.getPrivateKeyPEM(), reg); err != nil {
return nil, fmt.Errorf("failed to save registration: %w", err)
}
return reg, nil
}

View File

@ -2,11 +2,6 @@ package applicant
import ( import (
"context" "context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt" "fmt"
"os" "os"
"strconv" "strconv"
@ -17,126 +12,36 @@ import (
"github.com/go-acme/lego/v4/challenge" "github.com/go-acme/lego/v4/challenge"
"github.com/go-acme/lego/v4/challenge/dns01" "github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/lego" "github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/registration"
"github.com/usual2970/certimate/internal/app" "github.com/usual2970/certimate/internal/app"
"github.com/usual2970/certimate/internal/domain" "github.com/usual2970/certimate/internal/domain"
"github.com/usual2970/certimate/internal/pkg/utils/x509"
"github.com/usual2970/certimate/internal/repository" "github.com/usual2970/certimate/internal/repository"
) )
const defaultSSLProvider = "letsencrypt"
const (
sslProviderLetsencrypt = "letsencrypt"
sslProviderZeroSSL = "zerossl"
sslProviderGts = "gts"
)
const (
zerosslUrl = "https://acme.zerossl.com/v2/DV90"
letsencryptUrl = "https://acme-v02.api.letsencrypt.org/directory"
gtsUrl = "https://dv.acme-v02.api.pki.goog/directory"
)
var sslProviderUrls = map[string]string{
sslProviderLetsencrypt: letsencryptUrl,
sslProviderZeroSSL: zerosslUrl,
sslProviderGts: gtsUrl,
}
type Certificate struct {
CertUrl string `json:"certUrl"`
CertStableUrl string `json:"certStableUrl"`
PrivateKey string `json:"privateKey"`
Certificate string `json:"certificate"`
IssuerCertificate string `json:"issuerCertificate"`
CSR string `json:"csr"`
}
type applyConfig struct { type applyConfig struct {
Domains string `json:"domains"` Domains string
ContactEmail string `json:"contactEmail"` ContactEmail string
AccessConfig string `json:"accessConfig"` AccessConfig string
KeyAlgorithm string `json:"keyAlgorithm"` KeyAlgorithm string
Nameservers string `json:"nameservers"` Nameservers string
PropagationTimeout int32 `json:"propagationTimeout"` PropagationTimeout int32
DisableFollowCNAME bool `json:"disableFollowCNAME"` DisableFollowCNAME bool
} }
type applyUser struct { type ApplyResult struct {
CA string PrivateKey string
Email string Certificate string
Registration *registration.Resource IssuerCertificate string
ACMECertUrl string
privkey string ACMECertStableUrl string
CSR string
} }
func newApplyUser(ca, email string) (*applyUser, error) { type applicant interface {
repo := getAcmeAccountRepository() Apply() (*ApplyResult, error)
applyUser := &applyUser{
CA: ca,
Email: email,
}
acmeAccount, err := repo.GetByCAAndEmail(ca, email)
if err != nil {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
keyStr, err := x509.ConvertECPrivateKeyToPEM(key)
if err != nil {
return nil, err
}
applyUser.privkey = keyStr
return applyUser, nil
}
applyUser.Registration = acmeAccount.Resource
applyUser.privkey = acmeAccount.Key
return applyUser, nil
} }
func (u *applyUser) GetEmail() string { func NewWithApplyNode(node *domain.WorkflowNode) (applicant, error) {
return u.Email
}
func (u applyUser) GetRegistration() *registration.Resource {
return u.Registration
}
func (u *applyUser) GetPrivateKey() crypto.PrivateKey {
rs, _ := x509.ParseECPrivateKeyFromPEM(u.privkey)
return rs
}
func (u *applyUser) hasRegistration() bool {
return u.Registration != nil
}
func (u *applyUser) getPrivateKeyString() string {
return u.privkey
}
type Applicant interface {
Apply() (*Certificate, error)
}
// TODO: 暂时使用代理模式以兼容之前版本代码,后续重新实现此处逻辑
type proxyApplicant struct {
applyConfig *applyConfig
applicant challenge.Provider
}
func (d *proxyApplicant) Apply() (*Certificate, error) {
return apply(d.applyConfig, d.applicant)
}
func GetWithApplyNode(node *domain.WorkflowNode) (Applicant, error) {
// 获取授权配置 // 获取授权配置
accessRepo := repository.NewAccessRepository() accessRepo := repository.NewAccessRepository()
@ -161,31 +66,16 @@ func GetWithApplyNode(node *domain.WorkflowNode) (Applicant, error) {
} }
return &proxyApplicant{ return &proxyApplicant{
applyConfig: applyConfig,
applicant: challengeProvider, applicant: challengeProvider,
applyConfig: applyConfig,
}, nil }, nil
} }
type SSLProviderConfig struct { func apply(challengeProvider challenge.Provider, applyConfig *applyConfig) (*ApplyResult, error) {
Config SSLProviderConfigContent `json:"config"`
Provider string `json:"provider"`
}
type SSLProviderConfigContent struct {
Zerossl SSLProviderEab `json:"zerossl"`
Gts SSLProviderEab `json:"gts"`
}
type SSLProviderEab struct {
EabHmacKey string `json:"eabHmacKey"`
EabKid string `json:"eabKid"`
}
func apply(option *applyConfig, provider challenge.Provider) (*Certificate, error) {
record, _ := app.GetApp().Dao().FindFirstRecordByFilter("settings", "name='sslProvider'") record, _ := app.GetApp().Dao().FindFirstRecordByFilter("settings", "name='sslProvider'")
sslProvider := &SSLProviderConfig{ sslProvider := &acmeSSLProviderConfig{
Config: SSLProviderConfigContent{}, Config: acmeSSLProviderConfigContent{},
Provider: defaultSSLProvider, Provider: defaultSSLProvider,
} }
if record != nil { if record != nil {
@ -196,9 +86,9 @@ func apply(option *applyConfig, provider challenge.Provider) (*Certificate, erro
// Some unified lego environment variables are configured here. // Some unified lego environment variables are configured here.
// link: https://github.com/go-acme/lego/issues/1867 // link: https://github.com/go-acme/lego/issues/1867
os.Setenv("LEGO_DISABLE_CNAME_SUPPORT", strconv.FormatBool(option.DisableFollowCNAME)) os.Setenv("LEGO_DISABLE_CNAME_SUPPORT", strconv.FormatBool(applyConfig.DisableFollowCNAME))
myUser, err := newApplyUser(sslProvider.Provider, option.ContactEmail) myUser, err := newAcmeUser(sslProvider.Provider, applyConfig.ContactEmail)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -207,7 +97,7 @@ func apply(option *applyConfig, provider challenge.Provider) (*Certificate, erro
// This CA URL is configured for a local dev instance of Boulder running in Docker in a VM. // This CA URL is configured for a local dev instance of Boulder running in Docker in a VM.
config.CADirURL = sslProviderUrls[sslProvider.Provider] config.CADirURL = sslProviderUrls[sslProvider.Provider]
config.Certificate.KeyType = parseKeyAlgorithm(option.KeyAlgorithm) config.Certificate.KeyType = parseKeyAlgorithm(applyConfig.KeyAlgorithm)
// A client facilitates communication with the CA server. // A client facilitates communication with the CA server.
client, err := lego.NewClient(config) client, err := lego.NewClient(config)
@ -216,25 +106,24 @@ func apply(option *applyConfig, provider challenge.Provider) (*Certificate, erro
} }
challengeOptions := make([]dns01.ChallengeOption, 0) challengeOptions := make([]dns01.ChallengeOption, 0)
if len(option.Nameservers) > 0 { if len(applyConfig.Nameservers) > 0 {
challengeOptions = append(challengeOptions, dns01.AddRecursiveNameservers(dns01.ParseNameservers(strings.Split(option.Nameservers, ";")))) challengeOptions = append(challengeOptions, dns01.AddRecursiveNameservers(dns01.ParseNameservers(strings.Split(applyConfig.Nameservers, ";"))))
challengeOptions = append(challengeOptions, dns01.DisableAuthoritativeNssPropagationRequirement()) challengeOptions = append(challengeOptions, dns01.DisableAuthoritativeNssPropagationRequirement())
} }
client.Challenge.SetDNS01Provider(provider, challengeOptions...) client.Challenge.SetDNS01Provider(challengeProvider, challengeOptions...)
// New users will need to register // New users will need to register
if !myUser.hasRegistration() { if !myUser.hasRegistration() {
reg, err := getReg(client, sslProvider, myUser) reg, err := registerAcmeUser(client, sslProvider, myUser)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to register: %w", err) return nil, fmt.Errorf("failed to register: %w", err)
} }
myUser.Registration = reg myUser.Registration = reg
} }
domains := strings.Split(option.Domains, ";")
request := certificate.ObtainRequest{ request := certificate.ObtainRequest{
Domains: domains, Domains: strings.Split(applyConfig.Domains, ";"),
Bundle: true, Bundle: true,
} }
certificates, err := client.Certificate.Obtain(request) certificates, err := client.Certificate.Obtain(request)
@ -242,70 +131,16 @@ func apply(option *applyConfig, provider challenge.Provider) (*Certificate, erro
return nil, err return nil, err
} }
return &Certificate{ return &ApplyResult{
CertUrl: certificates.CertURL,
CertStableUrl: certificates.CertStableURL,
PrivateKey: string(certificates.PrivateKey), PrivateKey: string(certificates.PrivateKey),
Certificate: string(certificates.Certificate), Certificate: string(certificates.Certificate),
IssuerCertificate: string(certificates.IssuerCertificate), IssuerCertificate: string(certificates.IssuerCertificate),
CSR: string(certificates.CSR), CSR: string(certificates.CSR),
ACMECertUrl: certificates.CertURL,
ACMECertStableUrl: certificates.CertStableURL,
}, nil }, nil
} }
type AcmeAccountRepository interface {
GetByCAAndEmail(ca, email string) (*domain.AcmeAccount, error)
Save(ca, email, key string, resource *registration.Resource) error
}
func getAcmeAccountRepository() AcmeAccountRepository {
return repository.NewAcmeAccountRepository()
}
func getReg(client *lego.Client, sslProvider *SSLProviderConfig, user *applyUser) (*registration.Resource, error) {
// TODO: fix 潜在的并发问题
var reg *registration.Resource
var err error
switch sslProvider.Provider {
case sslProviderZeroSSL:
reg, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
TermsOfServiceAgreed: true,
Kid: sslProvider.Config.Zerossl.EabKid,
HmacEncoded: sslProvider.Config.Zerossl.EabHmacKey,
})
case sslProviderGts:
reg, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
TermsOfServiceAgreed: true,
Kid: sslProvider.Config.Gts.EabKid,
HmacEncoded: sslProvider.Config.Gts.EabHmacKey,
})
case sslProviderLetsencrypt:
reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
default:
err = errors.New("unknown ssl provider")
}
if err != nil {
return nil, err
}
repo := getAcmeAccountRepository()
resp, err := repo.GetByCAAndEmail(sslProvider.Provider, user.GetEmail())
if err == nil {
user.privkey = resp.Key
return resp.Resource, nil
}
if err := repo.Save(sslProvider.Provider, user.GetEmail(), user.getPrivateKeyString(), reg); err != nil {
return nil, fmt.Errorf("failed to save registration: %w", err)
}
return reg, nil
}
func parseKeyAlgorithm(algo string) certcrypto.KeyType { func parseKeyAlgorithm(algo string) certcrypto.KeyType {
switch algo { switch algo {
case "RSA2048": case "RSA2048":
@ -324,3 +159,13 @@ func parseKeyAlgorithm(algo string) certcrypto.KeyType {
return certcrypto.RSA2048 return certcrypto.RSA2048
} }
} }
// TODO: 暂时使用代理模式以兼容之前版本代码,后续重新实现此处逻辑
type proxyApplicant struct {
applicant challenge.Provider
applyConfig *applyConfig
}
func (d *proxyApplicant) Apply() (*ApplyResult, error) {
return apply(d.applicant, d.applyConfig)
}

View File

@ -15,14 +15,14 @@ type DeployerOption struct {
AccessConfig string `json:"accessConfig"` AccessConfig string `json:"accessConfig"`
AccessRecord *domain.Access `json:"-"` AccessRecord *domain.Access `json:"-"`
DeployConfig domain.DeployConfig `json:"deployConfig"` DeployConfig domain.DeployConfig `json:"deployConfig"`
Certificate applicant.Certificate `json:"certificate"` Certificate applicant.ApplyResult `json:"certificate"`
} }
type Deployer interface { type Deployer interface {
Deploy(ctx context.Context) error Deploy(ctx context.Context) error
} }
func GetWithProviderAndOption(provider string, option *DeployerOption) (Deployer, error) { func NewWithProviderAndOption(provider string, option *DeployerOption) (Deployer, error) {
deployer, logger, err := createDeployer(domain.DeployProviderType(provider), option.AccessRecord.Config, option.DeployConfig.NodeConfig) deployer, logger, err := createDeployer(domain.DeployProviderType(provider), option.AccessRecord.Config, option.DeployConfig.NodeConfig)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -1,15 +1,5 @@
package domain package domain
// Deprecated: TODO: 即将废弃
type ApplyConfig struct {
ContactEmail string `json:"contactEmail"`
ProviderAccessId string `json:"providerAccessId"`
KeyAlgorithm string `json:"keyAlgorithm"`
Nameservers string `json:"nameservers"`
PropagationTimeout int32 `json:"propagationTimeout"`
DisableFollowCNAME bool `json:"disableFollowCNAME"`
}
// Deprecated: TODO: 即将废弃 // Deprecated: TODO: 即将废弃
type DeployConfig struct { type DeployConfig struct {
NodeId string `json:"nodeId"` NodeId string `json:"nodeId"`

View File

@ -60,7 +60,7 @@ func (a *applyNode) Run(ctx context.Context) error {
} }
// 获取Applicant // 获取Applicant
applicant, err := applicant.GetWithApplyNode(a.node) applicant, err := applicant.NewWithApplyNode(a.node)
if err != nil { if err != nil {
a.AddOutput(ctx, a.node.Name, "获取申请对象失败", err.Error()) a.AddOutput(ctx, a.node.Name, "获取申请对象失败", err.Error())
return err return err
@ -101,8 +101,8 @@ func (a *applyNode) Run(ctx context.Context) error {
Certificate: applyResult.Certificate, Certificate: applyResult.Certificate,
PrivateKey: applyResult.PrivateKey, PrivateKey: applyResult.PrivateKey,
IssuerCertificate: applyResult.IssuerCertificate, IssuerCertificate: applyResult.IssuerCertificate,
ACMECertUrl: applyResult.CertUrl, ACMECertUrl: applyResult.ACMECertUrl,
ACMECertStableUrl: applyResult.CertStableUrl, ACMECertStableUrl: applyResult.ACMECertStableUrl,
EffectAt: certX509.NotBefore, EffectAt: certX509.NotBefore,
ExpireAt: certX509.NotAfter, ExpireAt: certX509.NotAfter,
WorkflowId: GetWorkflowId(ctx), WorkflowId: GetWorkflowId(ctx),

View File

@ -70,9 +70,9 @@ func (d *deployNode) Run(ctx context.Context) error {
Domains: cert.SubjectAltNames, Domains: cert.SubjectAltNames,
AccessConfig: access.Config, AccessConfig: access.Config,
AccessRecord: access, AccessRecord: access,
Certificate: applicant.Certificate{ Certificate: applicant.ApplyResult{
CertUrl: cert.ACMECertUrl, ACMECertUrl: cert.ACMECertUrl,
CertStableUrl: cert.ACMECertStableUrl, ACMECertStableUrl: cert.ACMECertStableUrl,
PrivateKey: cert.PrivateKey, PrivateKey: cert.PrivateKey,
Certificate: cert.Certificate, Certificate: cert.Certificate,
IssuerCertificate: cert.IssuerCertificate, IssuerCertificate: cert.IssuerCertificate,
@ -85,7 +85,7 @@ func (d *deployNode) Run(ctx context.Context) error {
}, },
} }
deploy, err := deployer.GetWithProviderAndOption(d.node.GetConfigString("provider"), option) deploy, err := deployer.NewWithProviderAndOption(d.node.GetConfigString("provider"), option)
if err != nil { if err != nil {
d.AddOutput(ctx, d.node.Name, "获取部署对象失败", err.Error()) d.AddOutput(ctx, d.node.Name, "获取部署对象失败", err.Error())
return err return err

View File

@ -2,7 +2,7 @@ import { forwardRef, useImperativeHandle, useMemo } from "react";
import { Form, type FormInstance } from "antd"; import { Form, type FormInstance } from "antd";
import { NOTIFY_CHANNELS, type NotifyChannelsSettingsContent } from "@/domain/settings"; import { NOTIFY_CHANNELS, type NotifyChannelsSettingsContent } from "@/domain/settings";
import { useAntdForm, useAntdFormName } from "@/hooks"; import { useAntdForm } from "@/hooks";
import NotifyChannelEditFormBarkFields from "./NotifyChannelEditFormBarkFields"; import NotifyChannelEditFormBarkFields from "./NotifyChannelEditFormBarkFields";
import NotifyChannelEditFormDingTalkFields from "./NotifyChannelEditFormDingTalkFields"; import NotifyChannelEditFormDingTalkFields from "./NotifyChannelEditFormDingTalkFields";

View File

@ -1,6 +1,6 @@
import { type RecordListOptions } from "pocketbase"; import { type RecordListOptions } from "pocketbase";
import { type WorkflowModel, type WorkflowNode } from "@/domain/workflow"; import { type WorkflowModel } from "@/domain/workflow";
import { getPocketBase } from "./pocketbase"; import { getPocketBase } from "./pocketbase";
const COLLECTION_NAME = "workflow"; const COLLECTION_NAME = "workflow";