[CI-SKIP] Upload current

This commit is contained in:
2026-04-24 10:37:46 -04:00
parent 6aacbfbb71
commit fb1abd6211
12 changed files with 519 additions and 579 deletions

View File

@@ -3,34 +3,29 @@ package common
import (
"errors"
"fmt"
"io"
"os"
"strings"
"code.gitea.io/sdk/gitea"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
gitconf "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/memory"
)
type CertManMode int
const (
Server CertManMode = iota
Client
)
// GitWorkspace is an in-memory git working tree for a single domain's
// certificate repository. It is the shared primitive that both client and
// server modes operate on: client mode clones and reads, server mode
// init/clones and pushes. The struct carries no mode-specific state.
type GitWorkspace struct {
Domain string
URL string
Repo *git.Repository
Storage *memory.Storage
FS billy.Filesystem
Repo *git.Repository
WorkTree *git.Worktree
}
// GitSource identifies a supported git repository host.
type GitSource int
const (
@@ -42,6 +37,8 @@ const (
CodeCommit
)
// GitSourceName maps GitSource to the string used in the app config's
// git.host field.
var GitSourceName = map[GitSource]string{
Github: "github",
Gitlab: "gitlab",
@@ -51,133 +48,80 @@ var GitSourceName = map[GitSource]string{
CodeCommit: "code-commit",
}
// StrToGitSource parses a config string (e.g. "gitea") into a GitSource.
func StrToGitSource(s string) (GitSource, error) {
for k, v := range GitSourceName {
if v == s {
return k, nil
}
}
return GitSource(0), errors.New("invalid gitsource name")
return 0, fmt.Errorf("invalid git source %q", s)
}
//func createGithubClient() *github.Client {
// return github.NewClient(nil).WithAuthToken(config.GetString("Git.api_token"))
//}
// ErrRepoNotFound is returned by RepoProvider implementations when a domain's
// repository does not exist on the remote. Callers use it to distinguish
// "repo hasn't been created yet" from transport or auth failures.
var ErrRepoNotFound = errors.New("repository not found")
func CreateGiteaClient(config *AppConfig) *gitea.Client {
client, err := gitea.NewClient(config.Git.Server, gitea.SetToken(config.Git.APIToken))
if err != nil {
fmt.Printf("Error connecting to gitea instance: %v\n", err)
return nil
// NewGitWorkspace returns a workspace with an in-memory filesystem and storage
// wired up. Call InitRepo (for a brand-new remote) or CloneRepo (for an
// existing one) to populate Repo and WorkTree.
func NewGitWorkspace(domain, url string) *GitWorkspace {
return &GitWorkspace{
Domain: domain,
URL: url,
Storage: memory.NewStorage(),
FS: memfs.New(),
}
return client
}
//func createGithubRepo(domain *Domain, Client *github.Client) string {
// name := domain.name
// owner := domain.config.GetString("Repo.owner")
// description := domain.description
// private := true
// includeAllBranches := false
//
// ctx := context.Background()
// template := &github.TemplateRepoRequest{
// Name: name,
// Owner: &owner,
// Description: description,
// Private: &private,
// IncludeAllBranches: &includeAllBranches,
// }
// repo, _, err := Client.Repositories.CreateFromTemplate(ctx, config.GetString("Git.org_name"), config.GetString("Git.template_name"), template)
// if err != nil {
// fmt.Println("Error creating repository from template,", err)
// return ""
// }
// return *repo.CloneURL
//}
func CreateGiteaRepo(domain string, giteaClient *gitea.Client, config *AppConfig, domainConfig *DomainConfig) string {
options := gitea.CreateRepoOption{
Name: domain + domainConfig.Repo.RepoSuffix,
Description: "Certificate storage for " + domain,
Private: true,
IssueLabels: "",
AutoInit: false,
Template: false,
Gitignores: "",
License: "",
Readme: "",
DefaultBranch: "master",
TrustModel: gitea.TrustModelDefault,
}
giteaRepo, _, err := giteaClient.CreateOrgRepo(config.Git.OrgName, options)
if err != nil {
fmt.Printf("Error creating repo: %v\n", err)
return ""
}
return giteaRepo.CloneURL
// RepoURL builds the canonical clone URL for a domain's certificate repo. It
// is the single authoritative place for the "<server>/<org>/<domain><suffix>.git"
// pattern so callers do not assemble URLs by hand.
func RepoURL(config *AppConfig, domainConfig *DomainConfig, domain string) string {
return config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git"
}
func (ws *GitWorkspace) InitRepo() error {
var err error
ws.Repo, err = git.Init(ws.Storage, ws.FS)
// InitRepo initializes an empty local repository in ws and registers origin
// pointed at ws.URL. Use this on the first push for a new domain; use
// CloneRepo on subsequent runs.
func InitRepo(ws *GitWorkspace) error {
repo, err := git.Init(ws.Storage, ws.FS)
if err != nil {
fmt.Printf("Error initializing local repo: %v\n", err)
return err
return fmt.Errorf("git init: %w", err)
}
_, err = ws.Repo.CreateRemote(&gitconf.RemoteConfig{
if _, err := repo.CreateRemote(&gitconf.RemoteConfig{
Name: "origin",
URLs: []string{ws.URL},
})
if err != nil && !errors.Is(err, git.ErrRemoteExists) {
fmt.Printf("Error creating remote origin repo: %v\n", err)
return err
}); err != nil && !errors.Is(err, git.ErrRemoteExists) {
return fmt.Errorf("add remote: %w", err)
}
ws.WorkTree, err = ws.Repo.Worktree()
wt, err := repo.Worktree()
if err != nil {
fmt.Printf("Error getting worktree from local repo: %v\n", err)
return err
return fmt.Errorf("get worktree: %w", err)
}
ws.Repo = repo
ws.WorkTree = wt
return nil
}
func (ws *GitWorkspace) CloneRepo(certmanMode CertManMode, config *AppConfig) error {
creds := &http.BasicAuth{
// CloneRepo clones ws.URL into ws using the git credentials from config. It
// performs no ownership or mode-specific checks: server mode must follow up
// with server.VerifyOwnership before pushing.
func CloneRepo(ws *GitWorkspace, config *AppConfig) error {
auth := &http.BasicAuth{
Username: config.Git.Username,
Password: config.Git.APIToken,
}
var err error
ws.Repo, err = git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: ws.URL, Auth: creds})
repo, err := git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: ws.URL, Auth: auth})
if err != nil {
fmt.Printf("Error cloning repo: %v\n", err)
return fmt.Errorf("git clone %s: %w", ws.URL, err)
}
ws.WorkTree, err = ws.Repo.Worktree()
wt, err := repo.Worktree()
if err != nil {
fmt.Printf("Error getting worktree from cloned repo: %v\n", err)
return err
}
if certmanMode == Server {
serverIdFile, err := ws.FS.OpenFile("/SERVER_ID", os.O_RDWR, 0640)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("server ID file not found for %s, adopting domain\n", ws.URL)
return nil
}
return err
}
serverIdBytes, err := io.ReadAll(serverIdFile)
if err != nil {
return err
}
serverId := strings.TrimSpace(string(serverIdBytes))
if serverId != config.App.UUID {
return fmt.Errorf("domain is already managed by server with uuid %s", serverId)
}
return fmt.Errorf("get worktree: %w", err)
}
ws.Repo = repo
ws.WorkTree = wt
return nil
}

55
common/provider_gitea.go Normal file
View File

@@ -0,0 +1,55 @@
package common
import (
"fmt"
"net/http"
"code.gitea.io/sdk/gitea"
)
// giteaProvider implements RepoProvider against a Gitea instance.
type giteaProvider struct {
config *AppConfig
client *gitea.Client
}
func newGiteaProvider(config *AppConfig) (*giteaProvider, error) {
client, err := gitea.NewClient(config.Git.Server, gitea.SetToken(config.Git.APIToken))
if err != nil {
return nil, fmt.Errorf("connect gitea %s: %w", config.Git.Server, err)
}
return &giteaProvider{config: config, client: client}, nil
}
// CreateRepo creates a private org repo named "<domain><repo_suffix>" and
// returns its clone URL.
func (p *giteaProvider) CreateRepo(domain string, domainConfig *DomainConfig) (string, error) {
name := domain + domainConfig.Repo.RepoSuffix
opts := gitea.CreateRepoOption{
Name: name,
Description: "Certificate storage for " + domain,
Private: true,
AutoInit: false,
DefaultBranch: "master",
TrustModel: gitea.TrustModelDefault,
}
repo, _, err := p.client.CreateOrgRepo(p.config.Git.OrgName, opts)
if err != nil {
return "", fmt.Errorf("create gitea repo %s/%s: %w", p.config.Git.OrgName, name, err)
}
return repo.CloneURL, nil
}
// HeadCommit returns the commit ID of branch in the domain's repo. A 404
// from Gitea (repo or branch missing) is mapped to ErrRepoNotFound.
func (p *giteaProvider) HeadCommit(domain, branch string, domainConfig *DomainConfig) (string, error) {
name := domain + domainConfig.Repo.RepoSuffix
b, resp, err := p.client.GetRepoBranch(p.config.Git.OrgName, name, branch)
if err != nil {
if resp != nil && resp.Response != nil && resp.StatusCode == http.StatusNotFound {
return "", ErrRepoNotFound
}
return "", fmt.Errorf("gitea branch %s/%s@%s: %w", p.config.Git.OrgName, name, branch, err)
}
return b.Commit.ID, nil
}

33
common/repo_provider.go Normal file
View File

@@ -0,0 +1,33 @@
package common
import "fmt"
// RepoProvider abstracts the remote git host (Gitea, GitHub, etc.) so the
// client and server packages stay host-agnostic. Provider-specific code lives
// in a single file per host (e.g. provider_gitea.go) that implements this
// interface. Adding a new host is a matter of adding a new file and a case
// in ProviderFor; no caller needs to change.
type RepoProvider interface {
// CreateRepo creates a new private domain repo on the remote and returns
// its canonical clone URL.
CreateRepo(domain string, domainConfig *DomainConfig) (string, error)
// HeadCommit returns the commit SHA at the tip of branch for the domain's
// repo. It returns ErrRepoNotFound if either the repo or the branch does
// not exist, so callers can treat "not created yet" as a non-fatal state.
HeadCommit(domain, branch string, domainConfig *DomainConfig) (string, error)
}
// ProviderFor returns a RepoProvider matching config.Git.Host.
func ProviderFor(config *AppConfig) (RepoProvider, error) {
source, err := StrToGitSource(config.Git.Host)
if err != nil {
return nil, err
}
switch source {
case Gitea:
return newGiteaProvider(config)
default:
return nil, fmt.Errorf("git source %q is not implemented", config.Git.Host)
}
}

View File

@@ -11,8 +11,6 @@ import (
"strconv"
"strings"
"syscall"
"code.gitea.io/sdk/gitea"
)
var (
@@ -21,13 +19,6 @@ var (
ErrBlankCert = errors.New("cert is blank")
)
type Domain struct {
name *string
config *AppConfig
description *string
gtClient *gitea.Client
}
// 0x01
func createPIDFile() {
file, err := os.Create("/var/run/certman.pid")
@@ -293,6 +284,22 @@ func MakeCredential(username, groupname string) (*syscall.Credential, error) {
return &syscall.Credential{Uid: uid, Gid: gid}, nil
}
// CertsDir returns the on-disk directory where a domain's encrypted and
// decrypted certificate files live, along with the client's sync-state
// `hash` marker. A per-domain data_root override (domainConfig.Certificates.DataRoot)
// is used as-is; otherwise the path is <config.data_root>/certificates/<domain>.
// This is the single source of truth for that convention — callers should
// not assemble the path themselves.
func CertsDir(config *AppConfig, domainConfig *DomainConfig, domain string) string {
if domainConfig != nil && domainConfig.Certificates.DataRoot != "" {
return domainConfig.Certificates.DataRoot
}
if config == nil {
return filepath.Join("certificates", domain)
}
return filepath.Join(config.Certificates.DataRoot, "certificates", domain)
}
func EffectiveDataRoot(config *AppConfig, domainConfig *DomainConfig) string {
if config == nil {
return ""