[CI-SKIP] Store Pre-Claude Code
All checks were successful
Build (artifact) / build (push) Has been skipped

This commit is contained in:
2026-04-22 22:26:21 -04:00
parent 727de333b4
commit 6aacbfbb71
30 changed files with 239 additions and 246 deletions

View File

@@ -1,4 +1,4 @@
VERSION := 1.1.4-beta VERSION := 1.1.5-beta
BUILD := $(shell git rev-parse --short HEAD) BUILD := $(shell git rev-parse --short HEAD)
GO := go GO := go
@@ -14,19 +14,19 @@ proto:
bundle: proto bundle: proto
@echo "Building Bundled Certman" @echo "Building Bundled Certman"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-$(VERSION)-amd64 ./cmd/bundle $(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-$(VERSION)-amd64 ./app/bundle
client: proto client: proto
@echo "Building Certman Client" @echo "Building Certman Client"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-client-$(VERSION)-amd64 ./cmd/client $(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-client-$(VERSION)-amd64 ./app/client
server: proto server: proto
@echo "Building Certman Server" @echo "Building Certman Server"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-server-$(VERSION)-amd64 ./cmd/server $(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-server-$(VERSION)-amd64 ./app/server
executor: proto executor: proto
@echo "Building Certman Executor" @echo "Building Certman Executor"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-executor-$(VERSION)-amd64 ./cmd/executor $(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-executor-$(VERSION)-amd64 ./app/executor
build: proto bundle client server executor build: proto bundle client server executor
@echo "All binaries successfully built" @echo "All binaries successfully built"

View File

@@ -24,4 +24,9 @@ sudo certman new-domain example.com
### TODO ### TODO
- Add systemd units during install - Add systemd units during install
- Add update command to pull from latest release - Add update command to pull from latest release
## Scratch Board
- Server Flow
- Read from

View File

@@ -4,8 +4,7 @@ import (
"fmt" "fmt"
"os" "os"
"git.nevets.tech/Steven/certman/app/executor" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/app/shared"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -21,18 +20,18 @@ func main() {
}, },
} }
rootCmd.AddCommand(shared.VersionCmd) rootCmd.AddCommand(app.VersionCmd)
rootCmd.AddCommand(shared.NewKeyCmd) rootCmd.AddCommand(app.NewKeyCmd)
rootCmd.AddCommand(shared.DevCmd) rootCmd.AddCommand(app.DevCmd)
rootCmd.AddCommand(shared.NewDomainCmd) rootCmd.AddCommand(app.NewDomainCmd)
rootCmd.AddCommand(shared.InstallCmd) rootCmd.AddCommand(app.InstallCmd)
rootCmd.AddCommand(shared.CertCmd) rootCmd.AddCommand(app.CertCmd)
rootCmd.AddCommand(executor.ExecutorCmd) //rootCmd.AddCommand(executor.ExecutorCmd)
rootCmd.AddCommand(shared.DaemonCmd) rootCmd.AddCommand(app.DaemonCmd)
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)

View File

@@ -1,4 +1,4 @@
package shared package app
import ( import (
"github.com/spf13/cobra" "github.com/spf13/cobra"

View File

@@ -1,10 +1,10 @@
package client package main
import ( import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"git.nevets.tech/Steven/certman/app/shared" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/client" "git.nevets.tech/Steven/certman/client"
"git.nevets.tech/Steven/certman/common" "git.nevets.tech/Steven/certman/common"
"github.com/go-git/go-billy/v5/memfs" "github.com/go-git/go-billy/v5/memfs"
@@ -43,7 +43,7 @@ var (
func init() { func init() {
renewCertSubCmd.AddCommand(updateCertLinkSubCmd, decryptCertsSubCmd) renewCertSubCmd.AddCommand(updateCertLinkSubCmd, decryptCertsSubCmd)
shared.CertCmd.AddCommand(renewCertSubCmd) app.CertCmd.AddCommand(renewCertSubCmd)
} }
func renewCert(domain string) error { func renewCert(domain string) error {
@@ -52,25 +52,26 @@ func renewCert(domain string) error {
Storage: memory.NewStorage(), Storage: memory.NewStorage(),
FS: memfs.New(), FS: memfs.New(),
} }
config := shared.Config() config := app.Config()
domainConfig, exists := shared.DomainStore().Get(domain) domainConfig, exists := app.DomainStore().Get(domain)
if !exists { if !exists {
return shared.ErrConfigNotFound return app.ErrConfigNotFound
} }
if err := client.PullCerts(config, domainConfig, gitWorkspace); err != nil { if err := client.PullCerts(config, domainConfig, gitWorkspace); err != nil {
return err return err
} }
certsDir := common.CertsDir(config, domainConfig) certsDir := common.EffectiveDataRoot(config, domainConfig)
return client.DecryptAndWriteCertificates(certsDir, config, domainConfig, gitWorkspace) return client.DecryptAndWriteCertificates(certsDir, config, domainConfig, gitWorkspace)
} }
func updateLinks(domain string) error { func updateLinks(domain string) error {
domainConfig, exists := shared.DomainStore().Get(domain) domainConfig, exists := app.DomainStore().Get(domain)
if !exists { if !exists {
return fmt.Errorf("domain %s does not exist", domain) return fmt.Errorf("domain %s does not exist", domain)
} }
certsDir := shared.DomainCertsDirWConf(domain, domainConfig) effectiveDataRoot := common.EffectiveDataRoot(app.Config(), domainConfig)
certsDir := filepath.Join(effectiveDataRoot, "certificates", domain)
certLinks := domainConfig.Certificates.CertSymlinks certLinks := domainConfig.Certificates.CertSymlinks
for _, certLink := range certLinks { for _, certLink := range certLinks {
@@ -83,7 +84,7 @@ func updateLinks(domain string) error {
keyLinks := domainConfig.Certificates.KeySymlinks keyLinks := domainConfig.Certificates.KeySymlinks
for _, keyLink := range keyLinks { for _, keyLink := range keyLinks {
err := common.LinkFile(filepath.Join(certsDir, domain+".crt"), keyLink, domain, ".key") err := common.LinkFile(filepath.Join(certsDir, domain+".key"), keyLink, domain, ".key")
if err != nil { if err != nil {
fmt.Printf("Error linking cert %s to %s: %v", keyLink, domain, err) fmt.Printf("Error linking cert %s to %s: %v", keyLink, domain, err)
continue continue

View File

@@ -1 +0,0 @@
package client

View File

@@ -1,18 +1,17 @@
package main package main
import ( import (
"git.nevets.tech/Steven/certman/app/client" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/app/shared"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
func init() { func init() {
shared.DaemonCmd.AddCommand(&cobra.Command{ app.DaemonCmd.AddCommand(&cobra.Command{
Use: "start", Use: "start",
Short: "Start the daemon", Short: "Start the daemon",
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return shared.RunDaemonCmd(&client.Daemon{}) return app.RunDaemonCmd(&Daemon{})
}, },
}) })
} }

View File

@@ -1,4 +1,4 @@
package client package main
import ( import (
"fmt" "fmt"
@@ -7,7 +7,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
appShared "git.nevets.tech/Steven/certman/app/shared" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/client" "git.nevets.tech/Steven/certman/client"
"git.nevets.tech/Steven/certman/common" "git.nevets.tech/Steven/certman/common"
"github.com/go-git/go-billy/v5/memfs" "github.com/go-git/go-billy/v5/memfs"
@@ -18,7 +18,7 @@ type Daemon struct{}
func (d *Daemon) Init() { func (d *Daemon) Init() {
fmt.Println("Starting CertManager in client mode...") fmt.Println("Starting CertManager in client mode...")
err := appShared.LoadDomainConfigs() err := app.LoadDomainConfigs()
if err != nil { if err != nil {
log.Fatalf("Error loading domain configs: %v", err) log.Fatalf("Error loading domain configs: %v", err)
} }
@@ -30,8 +30,8 @@ func (d *Daemon) Tick() {
fmt.Println("tick!") fmt.Println("tick!")
// Get local copy of configs // Get local copy of configs
config := appShared.Config() config := app.Config()
localDomainConfigs := appShared.DomainStore().Snapshot() localDomainConfigs := app.DomainStore().Snapshot()
// Loop over all domain configs (domains) // Loop over all domain configs (domains)
for domainStr, domainConfig := range localDomainConfigs { for domainStr, domainConfig := range localDomainConfigs {
@@ -44,17 +44,12 @@ func (d *Daemon) Tick() {
// If the repo doesn't exist, we can't check for a remote commit, so stop the rest of the check // If the repo doesn't exist, we can't check for a remote commit, so stop the rest of the check
repoExists := domainConfig.Internal.RepoExists repoExists := domainConfig.Internal.RepoExists
if repoExists { if repoExists {
var dataRoot string dataRoot := common.EffectiveDataRoot(config, domainConfig)
if domainConfig.Certificates.DataRoot == "" {
config.Certificates.DataRoot = domainStr
} else {
dataRoot = domainConfig.Certificates.DataRoot
}
localHash, err := client.LocalCommitHash(domainStr, dataRoot) localHash, err := client.LocalCommitHash(domainStr, dataRoot)
if err != nil { if err != nil {
fmt.Printf("No local commit hash found for domain %s\n", domainStr) fmt.Printf("No local commit hash found for domain %s\n", domainStr)
} }
gitSource, err := common.StrToGitSource(appShared.Config().Git.Host) gitSource, err := common.StrToGitSource(app.Config().Git.Host)
if err != nil { if err != nil {
fmt.Printf("Error getting git source for domain %s: %v\n", domainStr, err) fmt.Printf("Error getting git source for domain %s: %v\n", domainStr, err)
continue continue
@@ -77,14 +72,15 @@ func (d *Daemon) Tick() {
} }
// Ex: https://git.example.com/Org/Repo-suffix.git // Ex: https://git.example.com/Org/Repo-suffix.git
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?) // Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
repoUrl := appShared.Config().Git.Server + "/" + config.Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git" repoUrl := app.Config().Git.Server + "/" + config.Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git"
err := common.CloneRepo(repoUrl, gitWorkspace, common.Client, config) err := common.CloneRepo(repoUrl, gitWorkspace, common.Client, config)
if err != nil { if err != nil {
fmt.Printf("Error cloning domain repo %s: %v\n", domainStr, err) fmt.Printf("Error cloning domain repo %s: %v\n", domainStr, err)
continue continue
} }
certsDir := appShared.DomainCertsDirWConf(domainStr, domainConfig) effectiveDataRoot := common.EffectiveDataRoot(config, domainConfig)
certsDir := filepath.Join(effectiveDataRoot, "certificates", domainStr)
// Get files in repo // Get files in repo
fileInfos, err := gitWorkspace.FS.ReadDir("/") fileInfos, err := gitWorkspace.FS.ReadDir("/")
@@ -156,7 +152,7 @@ func (d *Daemon) Tick() {
func (d *Daemon) Reload() { func (d *Daemon) Reload() {
fmt.Println("Reloading configs...") fmt.Println("Reloading configs...")
err := appShared.LoadDomainConfigs() err := app.LoadDomainConfigs()
if err != nil { if err != nil {
fmt.Printf("Error loading domain configs: %v\n", err) fmt.Printf("Error loading domain configs: %v\n", err)
return return

View File

@@ -1,4 +1,4 @@
package client package main
import ( import (
"context" "context"
@@ -6,7 +6,7 @@ import (
"log" "log"
"time" "time"
"git.nevets.tech/Steven/certman/app/shared" "git.nevets.tech/Steven/certman/app"
pb "git.nevets.tech/Steven/certman/proto/v1" pb "git.nevets.tech/Steven/certman/proto/v1"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/credentials/insecure"
@@ -23,7 +23,7 @@ func SendHook(domain string) {
defer conn.Close() defer conn.Close()
client := pb.NewHookServiceClient(conn) client := pb.NewHookServiceClient(conn)
hooks, err := shared.PostPullHooks(domain) hooks, err := app.PostPullHooks(domain)
if err != nil { if err != nil {
fmt.Printf("Error getting hooks: %v\n", err) fmt.Printf("Error getting hooks: %v\n", err)
return return

View File

@@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"os" "os"
"git.nevets.tech/Steven/certman/app/shared" "git.nevets.tech/Steven/certman/app"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -18,16 +18,16 @@ func main() {
}, },
} }
rootCmd.AddCommand(shared.VersionCmd) rootCmd.AddCommand(app.VersionCmd)
rootCmd.AddCommand(shared.NewKeyCmd) rootCmd.AddCommand(app.NewKeyCmd)
rootCmd.AddCommand(shared.DevCmd) rootCmd.AddCommand(app.DevCmd)
rootCmd.AddCommand(shared.NewDomainCmd) rootCmd.AddCommand(app.NewDomainCmd)
rootCmd.AddCommand(shared.InstallCmd) rootCmd.AddCommand(app.InstallCmd)
rootCmd.AddCommand(shared.CertCmd) rootCmd.AddCommand(app.CertCmd)
rootCmd.AddCommand(shared.DaemonCmd) rootCmd.AddCommand(app.DaemonCmd)
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)

View File

@@ -1,4 +1,4 @@
package shared package app
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package shared package app
import ( import (
"errors" "errors"
@@ -80,8 +80,6 @@ func Config() *common.AppConfig {
} }
func DomainStore() *DomainConfigStore { func DomainStore() *DomainConfigStore {
domainStore.mu.RLock()
defer domainStore.mu.RUnlock()
return domainStore return domainStore
} }

View File

@@ -1,4 +1,4 @@
package shared package app
import ( import (
"context" "context"

View File

@@ -1,4 +1,4 @@
package executor package main
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package executor package main
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package executor package main
import ( import (
"context" "context"

View File

@@ -1,4 +1,4 @@
package executor package main
import "fmt" import "fmt"

View File

@@ -1,11 +1,11 @@
package server package main
import ( import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"time" "time"
"git.nevets.tech/Steven/certman/app/shared" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/common" "git.nevets.tech/Steven/certman/common"
"git.nevets.tech/Steven/certman/server" "git.nevets.tech/Steven/certman/server"
"github.com/go-git/go-billy/v5/memfs" "github.com/go-git/go-billy/v5/memfs"
@@ -27,17 +27,17 @@ var (
func init() { func init() {
renewCertSubCmd.Flags().BoolVar(&noPush, "no-push", false, "Don't push certs to repo, renew locally only [server mode only]") renewCertSubCmd.Flags().BoolVar(&noPush, "no-push", false, "Don't push certs to repo, renew locally only [server mode only]")
shared.CertCmd.AddCommand(renewCertSubCmd) app.CertCmd.AddCommand(renewCertSubCmd)
} }
func renewCertCmd(domain string, noPush bool) error { func renewCertCmd(domain string, noPush bool) error {
if err := shared.LoadConfig(); err != nil { if err := app.LoadConfig(); err != nil {
return err return err
} }
if err := shared.LoadDomainConfigs(); err != nil { if err := app.LoadDomainConfigs(); err != nil {
return err return err
} }
mgr, err := server.NewACMEManager(shared.Config()) mgr, err := server.NewACMEManager(app.Config())
if err != nil { if err != nil {
return err return err
} }
@@ -50,8 +50,8 @@ func renewCertCmd(domain string, noPush bool) error {
} }
func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error { func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error {
config := shared.Config() config := app.Config()
domainConfig, exists := shared.DomainStore().Get(domain) domainConfig, exists := app.DomainStore().Get(domain)
if !exists { if !exists {
return fmt.Errorf("domain %s does not exist", domain) return fmt.Errorf("domain %s does not exist", domain)
} }
@@ -66,7 +66,7 @@ func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error {
} }
domainConfig.Internal.LastIssued = time.Now().UTC().Unix() domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
err = shared.WriteDomainConfig(domainConfig) err = app.WriteDomainConfig(domainConfig)
if err != nil { if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err) return fmt.Errorf("error saving domain config %s: %v", domain, err)
} }
@@ -97,7 +97,7 @@ func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error {
return fmt.Errorf("error creating Gitea repo for domain %s", domain) return fmt.Errorf("error creating Gitea repo for domain %s", domain)
} }
domainConfig.Internal.RepoExists = true domainConfig.Internal.RepoExists = true
err = shared.WriteDomainConfig(domainConfig) err = app.WriteDomainConfig(domainConfig)
if err != nil { if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err) return fmt.Errorf("error saving domain config %s: %v", domain, err)
} }

View File

@@ -1,18 +1,17 @@
package main package main
import ( import (
"git.nevets.tech/Steven/certman/app/server" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/app/shared"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
func init() { func init() {
shared.DaemonCmd.AddCommand(&cobra.Command{ app.DaemonCmd.AddCommand(&cobra.Command{
Use: "start", Use: "start",
Short: "Start the daemon", Short: "Start the daemon",
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return shared.RunDaemonCmd(&server.Daemon{}) return app.RunDaemonCmd(&Daemon{})
}, },
}) })
} }

View File

@@ -1,13 +1,15 @@
package server package main
import ( import (
"errors"
"fmt" "fmt"
"log" "log"
"os"
"path/filepath" "path/filepath"
"sync" "sync"
"time" "time"
appShared "git.nevets.tech/Steven/certman/app/shared" appShared "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/common" "git.nevets.tech/Steven/certman/common"
"git.nevets.tech/Steven/certman/server" "git.nevets.tech/Steven/certman/server"
"github.com/go-git/go-billy/v5/memfs" "github.com/go-git/go-billy/v5/memfs"
@@ -63,6 +65,7 @@ func (d *Daemon) Tick() {
if !domainConfig.Domain.Enabled { if !domainConfig.Domain.Enabled {
continue continue
} }
//TODO: have renewPeriod logic default to use certificate expiry if available
renewPeriod := domainConfig.Certificates.RenewPeriod renewPeriod := domainConfig.Certificates.RenewPeriod
lastIssued := time.Unix(domainConfig.Internal.LastIssued, 0).UTC() lastIssued := time.Unix(domainConfig.Internal.LastIssued, 0).UTC()
renewalDue := lastIssued.AddDate(0, 0, renewPeriod) renewalDue := lastIssued.AddDate(0, 0, renewPeriod)
@@ -70,12 +73,16 @@ func (d *Daemon) Tick() {
//TODO extra check if certificate expiry (create cache?) //TODO extra check if certificate expiry (create cache?)
_, err := d.ACMEManager.RenewForDomain(domainStr) _, err := d.ACMEManager.RenewForDomain(domainStr)
if err != nil { if err != nil {
// if no existing cert, obtain instead if errors.Is(err, os.ErrNotExist) {
_, err = d.ACMEManager.ObtainForDomain(domainStr, appShared.Config(), domainConfig) // if no existing cert, obtain instead
if err != nil { _, err = d.ACMEManager.ObtainForDomain(domainStr, appShared.Config(), domainConfig)
fmt.Printf("Error obtaining domain certificates for domain %s: %v\n", domainStr, err) if err != nil {
continue fmt.Printf("Error obtaining domain certificates for domain %s: %v\n", domainStr, err)
continue
}
} }
fmt.Printf("Error: %v\n", err)
continue
} }
domainConfig.Internal.LastIssued = time.Now().UTC().Unix() domainConfig.Internal.LastIssued = time.Now().UTC().Unix()

View File

@@ -1 +0,0 @@
package server

View File

@@ -1 +0,0 @@
package shared

View File

@@ -1,11 +1,9 @@
package shared package app
import ( import (
"fmt" "fmt"
"os" "os"
"path/filepath"
"git.nevets.tech/Steven/certman/common"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -51,18 +49,6 @@ func createFile(fileName string, filePermission os.FileMode, data []byte) {
} }
} }
// DomainCertsDirWConf Can return ErrBlankConfigEntry or other errors
func DomainCertsDirWConf(domain string, domainConfig *common.DomainConfig) string {
var effectiveDataRoot string
if domainConfig.Certificates.DataRoot == "" {
effectiveDataRoot = config.Certificates.DataRoot
} else {
effectiveDataRoot = domainConfig.Certificates.DataRoot
}
return filepath.Join(effectiveDataRoot, "certificates", domain)
}
func basicCmd(use, short string, commandFunc func(cmd *cobra.Command, args []string)) *cobra.Command { func basicCmd(use, short string, commandFunc func(cmd *cobra.Command, args []string)) *cobra.Command {
return &cobra.Command{ return &cobra.Command{
Use: use, Use: use,

View File

@@ -10,6 +10,23 @@ import (
"git.nevets.tech/Steven/certman/common" "git.nevets.tech/Steven/certman/common"
) )
func WriteCommitHash(hash, dataRoot string) error {
//TODO: unfuck this logic, maybe use a domain struct with a flag for non-standard data root?
//var dataRoot string
//if domainConfig.Certificates.DataRoot == "" {
// dataRoot = filepath.Join(config.Certificates.DataRoot, "certificates", domainConfig.Domain.DomainName)
//} else {
// dataRoot = domainConfig.Certificates.DataRoot
//}
err := os.WriteFile(filepath.Join(dataRoot, "hash"), []byte(hash), 0644)
if err != nil {
return err
}
return nil
}
func LocalCommitHash(domain string, certsDir string) (string, error) { func LocalCommitHash(domain string, certsDir string) (string, error) {
data, err := os.ReadFile(filepath.Join(certsDir, "hash")) data, err := os.ReadFile(filepath.Join(certsDir, "hash"))
if err != nil { if err != nil {

View File

@@ -5,15 +5,12 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath"
"strings" "strings"
"time"
"code.gitea.io/sdk/gitea" "code.gitea.io/sdk/gitea"
"github.com/go-git/go-billy/v5" "github.com/go-git/go-billy/v5"
"github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5"
gitconf "github.com/go-git/go-git/v5/config" gitconf "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http" "github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/memory" "github.com/go-git/go-git/v5/storage/memory"
) )
@@ -27,6 +24,7 @@ const (
type GitWorkspace struct { type GitWorkspace struct {
Domain string Domain string
URL string
Repo *git.Repository Repo *git.Repository
Storage *memory.Storage Storage *memory.Storage
FS billy.Filesystem FS billy.Filesystem
@@ -121,7 +119,7 @@ func CreateGiteaRepo(domain string, giteaClient *gitea.Client, config *AppConfig
return giteaRepo.CloneURL return giteaRepo.CloneURL
} }
func InitRepo(url string, ws *GitWorkspace) error { func (ws *GitWorkspace) InitRepo() error {
var err error var err error
ws.Repo, err = git.Init(ws.Storage, ws.FS) ws.Repo, err = git.Init(ws.Storage, ws.FS)
if err != nil { if err != nil {
@@ -131,7 +129,7 @@ func InitRepo(url string, ws *GitWorkspace) error {
_, err = ws.Repo.CreateRemote(&gitconf.RemoteConfig{ _, err = ws.Repo.CreateRemote(&gitconf.RemoteConfig{
Name: "origin", Name: "origin",
URLs: []string{url}, URLs: []string{ws.URL},
}) })
if err != nil && !errors.Is(err, git.ErrRemoteExists) { if err != nil && !errors.Is(err, git.ErrRemoteExists) {
fmt.Printf("Error creating remote origin repo: %v\n", err) fmt.Printf("Error creating remote origin repo: %v\n", err)
@@ -147,13 +145,13 @@ func InitRepo(url string, ws *GitWorkspace) error {
return nil return nil
} }
func CloneRepo(url string, ws *GitWorkspace, certmanMode CertManMode, config *AppConfig) error { func (ws *GitWorkspace) CloneRepo(certmanMode CertManMode, config *AppConfig) error {
creds := &http.BasicAuth{ creds := &http.BasicAuth{
Username: config.Git.Username, Username: config.Git.Username,
Password: config.Git.APIToken, Password: config.Git.APIToken,
} }
var err error var err error
ws.Repo, err = git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: url, Auth: creds}) ws.Repo, err = git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: ws.URL, Auth: creds})
if err != nil { if err != nil {
fmt.Printf("Error cloning repo: %v\n", err) fmt.Printf("Error cloning repo: %v\n", err)
} }
@@ -167,7 +165,7 @@ func CloneRepo(url string, ws *GitWorkspace, certmanMode CertManMode, config *Ap
serverIdFile, err := ws.FS.OpenFile("/SERVER_ID", os.O_RDWR, 0640) serverIdFile, err := ws.FS.OpenFile("/SERVER_ID", os.O_RDWR, 0640)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
fmt.Printf("server ID file not found for %s, adopting domain\n", url) fmt.Printf("server ID file not found for %s, adopting domain\n", ws.URL)
return nil return nil
} }
return err return err
@@ -183,129 +181,3 @@ func CloneRepo(url string, ws *GitWorkspace, certmanMode CertManMode, config *Ap
} }
return nil return nil
} }
func AddAndPushCerts(domain string, ws *GitWorkspace, config *AppConfig, domainConfig *DomainConfig) error {
var dataRoot string
if domainConfig.Certificates.DataRoot == "" {
dataRoot = config.Certificates.DataRoot
} else {
dataRoot = domainConfig.Certificates.DataRoot
}
certFiles, err := os.ReadDir(dataRoot)
if err != nil {
fmt.Printf("Error reading from directory: %v\n", err)
return err
}
for _, entry := range certFiles {
if strings.HasSuffix(entry.Name(), ".crpt") {
file, err := ws.FS.Create(entry.Name())
if err != nil {
fmt.Printf("Error copying file to memfs: %v\n", err)
return err
}
certFile, err := os.ReadFile(filepath.Join(dataRoot, entry.Name()))
if err != nil {
fmt.Printf("Error reading file to memfs: %v\n", err)
file.Close()
return err
}
_, err = file.Write(certFile)
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
file.Close()
return err
}
_, err = ws.WorkTree.Add(file.Name())
if err != nil {
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
file.Close()
return err
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
}
}
file, err := ws.FS.Create("/SERVER_ID")
if err != nil {
fmt.Printf("Error creating file in memfs: %v\n", err)
return err
}
_, err = file.Write([]byte(config.App.UUID))
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
file.Close()
return err
}
_, err = ws.WorkTree.Add(file.Name())
if err != nil {
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
file.Close()
return err
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
}
}
status, err := ws.WorkTree.Status()
if err != nil {
fmt.Printf("Error getting repo status: %v\n", err)
return err
}
if status.IsClean() {
fmt.Printf("Repository is clean, skipping commit...\n")
return nil
}
fmt.Println("Work Tree Status:\n" + status.String())
signature := &object.Signature{
Name: "Cert Manager",
Email: config.Certificates.Email,
When: time.Now(),
}
_, err = ws.WorkTree.Commit("Update "+domain+" @ "+time.Now().Format("Mon Jan _2 2006 15:04:05 MST"), &git.CommitOptions{Author: signature, Committer: signature})
if err != nil {
fmt.Printf("Error committing certs: %v\n", err)
return err
}
creds := &http.BasicAuth{
Username: config.Git.Username,
Password: config.Git.APIToken,
}
err = ws.Repo.Push(&git.PushOptions{
Auth: creds,
Force: true,
RemoteName: "origin",
RefSpecs: []gitconf.RefSpec{
"refs/heads/master:refs/heads/master",
},
})
if err != nil {
fmt.Printf("Error pushing to origin: %v\n", err)
return err
}
fmt.Println("Successfully uploaded to " + config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git")
return nil
}
func WriteCommitHash(hash string, config *AppConfig, domainConfig *DomainConfig) error {
var dataRoot string
if domainConfig.Certificates.DataRoot == "" {
dataRoot = filepath.Join(config.Certificates.DataRoot, "certificates", domainConfig.Domain.DomainName)
} else {
dataRoot = domainConfig.Certificates.DataRoot
}
err := os.WriteFile(filepath.Join(dataRoot, "hash"), []byte(hash), 0644)
if err != nil {
return err
}
return nil
}

View File

@@ -293,7 +293,7 @@ func MakeCredential(username, groupname string) (*syscall.Credential, error) {
return &syscall.Credential{Uid: uid, Gid: gid}, nil return &syscall.Credential{Uid: uid, Gid: gid}, nil
} }
func CertsDir(config *AppConfig, domainConfig *DomainConfig) string { func EffectiveDataRoot(config *AppConfig, domainConfig *DomainConfig) string {
if config == nil { if config == nil {
return "" return ""
} }

View File

@@ -242,12 +242,7 @@ func buildDomainRuntimeConfig(config *common.AppConfig, domainConfig *common.Dom
email := config.Certificates.Email email := config.Certificates.Email
// domain override data_root can be blank -> main fallback // domain override data_root can be blank -> main fallback
var dataRoot string dataRoot := common.EffectiveDataRoot(config, domainConfig)
if domainConfig.Certificates.DataRoot == "" {
dataRoot = config.Certificates.DataRoot
} else {
dataRoot = domainConfig.Certificates.DataRoot
}
caDirURL := config.Certificates.CADirURL caDirURL := config.Certificates.CADirURL
@@ -584,6 +579,9 @@ func (m *ACMEManager) loadStoredResource(domainKey string) (*certificate.Resourc
dir := filepath.Join(m.CertsRoot, base) dir := filepath.Join(m.CertsRoot, base)
raw, err := os.ReadFile(filepath.Join(dir, base+".json")) raw, err := os.ReadFile(filepath.Join(dir, base+".json"))
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, os.ErrNotExist
}
return nil, err return nil, err
} }

View File

@@ -1 +1,120 @@
package server package server
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"git.nevets.tech/Steven/certman/common"
"github.com/go-git/go-git/v5"
gitconf "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
)
type GitWorkspace common.GitWorkspace
func (ws *GitWorkspace) AddAndPushCerts(dataRoot, repoSuffix string, config *common.AppConfig) error {
certFiles, err := os.ReadDir(dataRoot)
if err != nil {
fmt.Printf("Error reading from directory: %v\n", err)
return err
}
for _, entry := range certFiles {
if strings.HasSuffix(entry.Name(), ".crpt") {
file, err := ws.FS.Create(entry.Name())
if err != nil {
fmt.Printf("Error copying file to memfs: %v\n", err)
return err
}
certFile, err := os.ReadFile(filepath.Join(dataRoot, entry.Name()))
if err != nil {
fmt.Printf("Error reading file to memfs: %v\n", err)
file.Close()
return err
}
_, err = file.Write(certFile)
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
file.Close()
return err
}
_, err = ws.WorkTree.Add(file.Name())
if err != nil {
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
file.Close()
return err
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
}
}
}
file, err := ws.FS.Create("/SERVER_ID")
if err != nil {
fmt.Printf("Error creating file in memfs: %v\n", err)
return err
}
_, err = file.Write([]byte(config.App.UUID))
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
file.Close()
return err
}
_, err = ws.WorkTree.Add(file.Name())
if err != nil {
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
file.Close()
return err
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
}
status, err := ws.WorkTree.Status()
if err != nil {
fmt.Printf("Error getting repo status: %v\n", err)
return err
}
if status.IsClean() {
fmt.Printf("Repository is clean, skipping commit...\n")
return nil
}
fmt.Println("Work Tree Status:\n" + status.String())
signature := &object.Signature{
Name: "Cert Manager",
Email: config.Certificates.Email,
When: time.Now(),
}
_, err = ws.WorkTree.Commit("Update "+ws.Domain+" @ "+time.Now().Format("Mon Jan _2 2006 15:04:05 MST"), &git.CommitOptions{Author: signature, Committer: signature})
if err != nil {
fmt.Printf("Error committing certs: %v\n", err)
return err
}
creds := &http.BasicAuth{
Username: config.Git.Username,
Password: config.Git.APIToken,
}
err = ws.Repo.Push(&git.PushOptions{
Auth: creds,
Force: true,
RemoteName: "origin",
RefSpecs: []gitconf.RefSpec{
"refs/heads/master:refs/heads/master",
},
})
if err != nil {
fmt.Printf("Error pushing to origin: %v\n", err)
return err
}
fmt.Println("Successfully uploaded to " + config.Git.Server + "/" + config.Git.OrgName + "/" + ws.Domain + repoSuffix + ".git")
return nil
}