5 Commits

Author SHA1 Message Date
fb1abd6211 [CI-SKIP] Upload current 2026-04-24 10:37:46 -04:00
6aacbfbb71 [CI-SKIP] Store Pre-Claude Code
All checks were successful
Build (artifact) / build (push) Has been skipped
2026-04-22 22:26:21 -04:00
727de333b4 Fixed data_root hash file bug
All checks were successful
Build (artifact) / build (push) Successful in 50s
2026-03-21 10:59:47 +01:00
f4e7a37fa6 Fixed bug with hash being written in wrong location
All checks were successful
Build (artifact) / build (push) Successful in 41s
2026-03-21 10:52:46 +01:00
18f414e474 [CI-SKIP] Fixed module name
All checks were successful
Build (artifact) / build (push) Has been skipped
2026-03-16 23:03:08 +01:00
33 changed files with 670 additions and 733 deletions

View File

@@ -1,4 +1,4 @@
VERSION := 1.1.1-beta VERSION := 1.1.5-beta-claude
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

@@ -21,3 +21,12 @@ sudo certman new-domain example.com
sudo certman install -mode client sudo certman install -mode client
sudo certman new-domain example.com sudo certman new-domain example.com
``` ```
### TODO
- Add systemd units during install
- 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/Keys/certman/app/executor" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Keys/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,14 +1,11 @@
package client package main
import ( import (
"fmt" "fmt"
"path/filepath"
"git.nevets.tech/Keys/certman/app/shared" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Keys/certman/client" "git.nevets.tech/Steven/certman/client"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -43,51 +40,29 @@ 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 {
gitWorkspace := &common.GitWorkspace{ config := app.Config()
Domain: domain, domainConfig, exists := app.DomainStore().Get(domain)
Storage: memory.NewStorage(),
FS: memfs.New(),
}
config := shared.Config()
domainConfig, exists := shared.DomainStore().Get(domain)
if !exists { if !exists {
return shared.ErrConfigNotFound return app.ErrConfigNotFound
} }
if err := client.PullCerts(config, domainConfig, gitWorkspace); err != nil { url := common.RepoURL(config, domainConfig, domain)
return err ws := common.NewGitWorkspace(domain, url)
if err := common.CloneRepo(ws, config); err != nil {
return fmt.Errorf("clone %s: %w", domain, err)
} }
certsDir := common.CertsDir(config, domainConfig) certsDir := common.CertsDir(config, domainConfig, domain)
return client.DecryptAndWriteCertificates(certsDir, config, domainConfig, gitWorkspace) return client.DecryptAndWriteCertificates(certsDir, domainConfig, ws)
} }
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 := common.CertsDir(app.Config(), domainConfig, domain)
certsDir := shared.DomainCertsDirWConf(domain, domainConfig) return client.UpdateSymlinks(domain, domainConfig, certsDir)
certLinks := domainConfig.Certificates.CertSymlinks
for _, certLink := range certLinks {
err := common.LinkFile(filepath.Join(certsDir, domain+".crt"), certLink, domain, ".crt")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v", certLink, domain, err)
continue
}
}
keyLinks := domainConfig.Certificates.KeySymlinks
for _, keyLink := range keyLinks {
err := common.LinkFile(filepath.Join(certsDir, domain+".crt"), keyLink, domain, ".key")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v", keyLink, domain, err)
continue
}
}
return nil
} }

View File

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

View File

@@ -1,18 +1,17 @@
package main package main
import ( import (
"git.nevets.tech/Keys/certman/app/client" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Keys/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,165 +1,84 @@
package client package main
import ( import (
"errors"
"fmt" "fmt"
"io"
"log" "log"
"path/filepath"
"strings"
appShared "git.nevets.tech/Keys/certman/app/shared" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Keys/certman/client" "git.nevets.tech/Steven/certman/client"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
) )
type Daemon struct{} 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() if err := app.LoadDomainConfigs(); err != nil {
if err != nil {
log.Fatalf("Error loading domain configs: %v", err) log.Fatalf("Error loading domain configs: %v", err)
} }
d.Tick() d.Tick()
} }
func (d *Daemon) Tick() { func (d *Daemon) Tick() {
fmt.Println("tick!") fmt.Println("tick!")
// Get local copy of configs config := app.Config()
config := appShared.Config() localDomainConfigs := app.DomainStore().Snapshot()
localDomainConfigs := appShared.DomainStore().Snapshot()
// Loop over all domain configs (domains)
for domainStr, domainConfig := range localDomainConfigs { for domainStr, domainConfig := range localDomainConfigs {
// Skip non-enabled domains
if !domainConfig.Domain.Enabled { if !domainConfig.Domain.Enabled {
continue continue
} }
// Skip domains with up-to-date commit hashes certsDir := common.CertsDir(config, domainConfig, domainStr)
// 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 // Short-circuit when the local copy already matches the remote HEAD.
if repoExists { // Only useful once the server has provisioned the repo; otherwise
var dataRoot string // the RemoteCommitHash call returns ErrRepoNotFound and we skip
if domainConfig.Certificates.DataRoot == "" { // this tick entirely (nothing to pull yet).
config.Certificates.DataRoot = domainStr if domainConfig.Internal.RepoExists {
} else { localHash, err := client.LocalCommitHash(certsDir)
dataRoot = domainConfig.Certificates.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("Error reading local hash for %s: %v\n", domainStr, err)
} }
gitSource, err := common.StrToGitSource(appShared.Config().Git.Host) remoteHash, err := client.RemoteCommitHash(config, domainConfig, domainStr)
if err != nil { if err != nil {
fmt.Printf("Error getting git source for domain %s: %v\n", domainStr, err) if errors.Is(err, common.ErrRepoNotFound) {
fmt.Printf("Remote repo not yet provisioned for %s; skipping\n", domainStr)
continue continue
} }
remoteHash, err := client.RemoteCommitHash(domainStr, gitSource, config, domainConfig) fmt.Printf("Error getting remote hash for %s: %v\n", domainStr, err)
if err != nil { continue
fmt.Printf("Error getting remote commit hash for domain %s: %v\n", domainStr, err)
} }
// If both hashes are blank (errored), break if localHash != "" && localHash == remoteHash {
// If localHash equals remoteHash (local is up-to-date), skip
if !(localHash == "" && remoteHash == "") && localHash == remoteHash {
fmt.Printf("Domain %s is up to date. Skipping...\n", domainStr) fmt.Printf("Domain %s is up to date. Skipping...\n", domainStr)
continue continue
} }
} }
gitWorkspace := &common.GitWorkspace{ url := common.RepoURL(config, domainConfig, domainStr)
Storage: memory.NewStorage(), ws := common.NewGitWorkspace(domainStr, url)
FS: memfs.New(), if err := common.CloneRepo(ws, config); err != nil {
}
// Ex: https://git.example.com/Org/Repo-suffix.git
// 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"
err := common.CloneRepo(repoUrl, gitWorkspace, common.Client, config)
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) if err := client.DecryptAndWriteCertificates(certsDir, domainConfig, ws); err != nil {
fmt.Printf("Error decrypting certificates for %s: %v\n", domainStr, err)
// Get files in repo
fileInfos, err := gitWorkspace.FS.ReadDir("/")
if err != nil {
fmt.Printf("Error reading directory in memFS on domain %s: %v\n", domainStr, err)
continue continue
} }
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added if err := client.UpdateSymlinks(domainStr, domainConfig, certsDir); err != nil {
for _, fileInfo := range fileInfos { fmt.Printf("Error updating symlinks for %s: %v\n", domainStr, err)
if strings.HasSuffix(fileInfo.Name(), ".crpt") {
filename, _ := strings.CutSuffix(fileInfo.Name(), ".crpt")
file, err := gitWorkspace.FS.Open(fileInfo.Name())
if err != nil {
fmt.Printf("Error opening file in memFS on domain %s: %v\n", domainStr, err)
continue continue
} }
fileBytes, err := io.ReadAll(file)
if err != nil {
fmt.Printf("Error reading file in memFS on domain %s: %v\n", domainStr, err)
file.Close()
continue
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file on domain %s: %v\n", domainStr, err)
continue
}
err = common.DecryptFileFromBytes(domainConfig.Certificates.CryptoKey, fileBytes, filepath.Join(certsDir, filename), nil)
if err != nil {
fmt.Printf("Error decrypting file %s in domain %s: %v\n", filename, domainStr, err)
continue
}
headRef, err := gitWorkspace.Repo.Head()
if err != nil {
fmt.Printf("Error getting head reference for domain %s: %v\n", domainStr, err)
continue
}
err = common.WriteCommitHash(headRef.Hash().String(), config, domainConfig)
if err != nil {
fmt.Printf("Error writing commit hash: %v\n", err)
continue
}
certLinks := domainConfig.Certificates.CertSymlinks
for _, certLink := range certLinks {
err = common.LinkFile(filepath.Join(certsDir, domainStr+".crt"), certLink, domainStr, ".crt")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v\n", certLink, domainStr, err)
continue
}
}
keyLinks := domainConfig.Certificates.KeySymlinks
for _, keyLink := range keyLinks {
err = common.LinkFile(filepath.Join(certsDir, domainStr+".key"), keyLink, domainStr, ".key")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v\n", keyLink, domainStr, err)
continue
}
}
}
}
} }
} }
func (d *Daemon) Reload() { func (d *Daemon) Reload() {
fmt.Println("Reloading configs...") fmt.Println("Reloading configs...")
if err := app.LoadDomainConfigs(); err != nil {
err := appShared.LoadDomainConfigs()
if err != nil {
fmt.Printf("Error loading domain configs: %v\n", err) fmt.Printf("Error loading domain configs: %v\n", err)
return
} }
} }

View File

@@ -1,4 +1,4 @@
package client package main
import ( import (
"context" "context"
@@ -6,8 +6,8 @@ import (
"log" "log"
"time" "time"
"git.nevets.tech/Keys/certman/app/shared" "git.nevets.tech/Steven/certman/app"
pb "git.nevets.tech/Keys/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/Keys/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"
@@ -9,7 +9,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@@ -1,4 +1,4 @@
package shared package app
import ( import (
"errors" "errors"
@@ -9,8 +9,8 @@ import (
"strings" "strings"
"sync" "sync"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
pb "git.nevets.tech/Keys/certman/proto/v1" pb "git.nevets.tech/Steven/certman/proto/v1"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/pelletier/go-toml/v2" "github.com/pelletier/go-toml/v2"
"github.com/spf13/viper" "github.com/spf13/viper"
@@ -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"
@@ -10,7 +10,7 @@ import (
"syscall" "syscall"
"time" "time"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

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

View File

@@ -1,11 +1,11 @@
package executor package main
import ( import (
"fmt" "fmt"
"net" "net"
"sync" "sync"
pb "git.nevets.tech/Keys/certman/proto/v1" pb "git.nevets.tech/Steven/certman/proto/v1"
"github.com/coreos/go-systemd/v22/activation" "github.com/coreos/go-systemd/v22/activation"
"google.golang.org/grpc" "google.golang.org/grpc"
) )

View File

@@ -1,4 +1,4 @@
package executor package main
import ( import (
"context" "context"
@@ -8,8 +8,8 @@ import (
"syscall" "syscall"
"time" "time"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
pb "git.nevets.tech/Keys/certman/proto/v1" pb "git.nevets.tech/Steven/certman/proto/v1"
) )
type hookServer struct { type hookServer struct {

View File

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

View File

@@ -1,15 +1,13 @@
package server package main
import ( import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"time" "time"
"git.nevets.tech/Keys/certman/app/shared" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
"git.nevets.tech/Keys/certman/server" "git.nevets.tech/Steven/certman/server"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -27,99 +25,61 @@ 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
} }
err = renewCerts(domain, noPush, mgr) return renewCerts(domain, noPush, mgr)
if err != nil {
return err
}
// return ReloadDaemonCmd() // Not sure if this is necessary
return nil
} }
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)
} }
_, err := mgr.RenewForDomain(domain) if _, err := mgr.RenewForDomain(domain); err != nil {
if err != nil { // If the domain has no stored resource yet, fall through to Obtain.
// if no existing cert, obtain instead if _, err := mgr.ObtainForDomain(domain, config, domainConfig); err != nil {
_, err = mgr.ObtainForDomain(domain, config, domainConfig)
if err != nil {
return fmt.Errorf("error obtaining domain certificates for domain %s: %v", domain, err) return fmt.Errorf("error obtaining domain certificates for domain %s: %v", domain, err)
} }
} }
domainConfig.Internal.LastIssued = time.Now().UTC().Unix() domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
err = shared.WriteDomainConfig(domainConfig) if err := app.WriteDomainConfig(domainConfig); 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)
} }
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(mgr.CertsRoot, domain, domain+".crt"), filepath.Join(mgr.CertsRoot, domain, domain+".crt.crpt"), nil) certsDir := filepath.Join(mgr.CertsRoot, domain)
if err != nil { if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domain+".crt"), filepath.Join(certsDir, domain+".crt.crpt"), nil); err != nil {
return fmt.Errorf("error encrypting domain cert for domain %s: %v", domain, err) return fmt.Errorf("error encrypting domain cert for domain %s: %v", domain, err)
} }
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(mgr.CertsRoot, domain, domain+".key"), filepath.Join(mgr.CertsRoot, domain, domain+".key.crpt"), nil) if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domain+".key"), filepath.Join(certsDir, domain+".key.crpt"), nil); err != nil {
if err != nil {
return fmt.Errorf("error encrypting domain key for domain %s: %v", domain, err) return fmt.Errorf("error encrypting domain key for domain %s: %v", domain, err)
} }
if !noPush { if noPush {
giteaClient := common.CreateGiteaClient(config) return nil
if giteaClient == nil { }
return fmt.Errorf("error creating gitea client for domain %s: %v", domain, err)
} ws, err := prepareServerWorkspace(config, domainConfig, domain)
gitWorkspace := &common.GitWorkspace{ if err != nil {
Storage: memory.NewStorage(), return fmt.Errorf("prepare workspace for %s: %w", domain, err)
FS: memfs.New(), }
} if err := server.AddAndPushCerts(ws, certsDir, config); err != nil {
return fmt.Errorf("push certificates for %s: %w", domain, err)
var repoUrl string }
if !domainConfig.Internal.RepoExists { fmt.Printf("Successfully pushed certificates for domain %s\n", domain)
repoUrl = common.CreateGiteaRepo(domain, giteaClient, config, domainConfig)
if repoUrl == "" {
return fmt.Errorf("error creating Gitea repo for domain %s", domain)
}
domainConfig.Internal.RepoExists = true
err = shared.WriteDomainConfig(domainConfig)
if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err)
}
err = common.InitRepo(repoUrl, gitWorkspace)
if err != nil {
return fmt.Errorf("error initializing repo for domain %s: %v", domain, err)
}
} else {
repoUrl = config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git"
err = common.CloneRepo(repoUrl, gitWorkspace, common.Server, config)
if err != nil {
return fmt.Errorf("error cloning repo for domain %s: %v", domain, err)
}
}
err = common.AddAndPushCerts(domain, gitWorkspace, config, domainConfig)
if err != nil {
return fmt.Errorf("error pushing certificates for domain %s: %v", domain, err)
}
fmt.Printf("Successfully pushed certificates for domain %s\n", domain)
}
return nil return nil
} }

View File

@@ -1,18 +1,17 @@
package main package main
import ( import (
"git.nevets.tech/Keys/certman/app/server" "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Keys/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,17 +1,17 @@
package server package main
import ( import (
"errors"
"fmt" "fmt"
"log" "log"
"os"
"path/filepath" "path/filepath"
"sync" "sync"
"time" "time"
appShared "git.nevets.tech/Keys/certman/app/shared" appShared "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
"git.nevets.tech/Keys/certman/server" "git.nevets.tech/Steven/certman/server"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5/storage/memory"
) )
type Daemon struct { type Daemon struct {
@@ -63,90 +63,96 @@ 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)
if now.After(renewalDue) { if !now.After(renewalDue) {
continue
}
//TODO extra check if certificate expiry (create cache?) //TODO extra check if certificate expiry (create cache?)
_, err := d.ACMEManager.RenewForDomain(domainStr) if _, err := d.ACMEManager.RenewForDomain(domainStr); err != nil {
if err != nil { if errors.Is(err, os.ErrNotExist) {
// if no existing cert, obtain instead if _, err := d.ACMEManager.ObtainForDomain(domainStr, config, domainConfig); err != nil {
_, err = d.ACMEManager.ObtainForDomain(domainStr, appShared.Config(), domainConfig)
if err != nil {
fmt.Printf("Error obtaining domain certificates for domain %s: %v\n", domainStr, err) fmt.Printf("Error obtaining domain certificates for domain %s: %v\n", domainStr, err)
continue continue
} }
} else {
fmt.Printf("Error: %v\n", err)
continue
}
} }
domainConfig.Internal.LastIssued = time.Now().UTC().Unix() domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
err = appShared.WriteDomainConfig(domainConfig) if err := appShared.WriteDomainConfig(domainConfig); err != nil {
if err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err) fmt.Printf("Error saving domain config %s: %v\n", domainStr, err)
continue continue
} }
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(d.ACMEManager.CertsRoot, domainStr, domainStr+".crt"), filepath.Join(d.ACMEManager.CertsRoot, domainStr, domainStr+".crt.crpt"), nil) certsDir := filepath.Join(d.ACMEManager.CertsRoot, domainStr)
if err != nil { if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domainStr+".crt"), filepath.Join(certsDir, domainStr+".crt.crpt"), nil); err != nil {
fmt.Printf("Error encrypting domain cert for domain %s: %v\n", domainStr, err) fmt.Printf("Error encrypting domain cert for domain %s: %v\n", domainStr, err)
continue continue
} }
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(d.ACMEManager.CertsRoot, domainStr, domainStr+".key"), filepath.Join(d.ACMEManager.CertsRoot, domainStr, domainStr+".key.crpt"), nil) if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domainStr+".key"), filepath.Join(certsDir, domainStr+".key.crpt"), nil); err != nil {
if err != nil {
fmt.Printf("Error encrypting domain key for domain %s: %v\n", domainStr, err) fmt.Printf("Error encrypting domain key for domain %s: %v\n", domainStr, err)
continue continue
} }
giteaClient := common.CreateGiteaClient(config) ws, err := prepareServerWorkspace(config, domainConfig, domainStr)
if giteaClient == nil {
fmt.Printf("Error creating gitea client for domain %s: %v\n", domainStr, err)
continue
}
gitWorkspace := &common.GitWorkspace{
Storage: memory.NewStorage(),
FS: memfs.New(),
}
var repoUrl string
if !domainConfig.Internal.RepoExists {
repoUrl = common.CreateGiteaRepo(domainStr, giteaClient, config, domainConfig)
if repoUrl == "" {
fmt.Printf("Error creating Gitea repo for domain %s\n", domainStr)
continue
}
domainConfig.Internal.RepoExists = true
err = appShared.WriteDomainConfig(domainConfig)
if err != nil { if err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err) fmt.Printf("Error preparing git workspace for domain %s: %v\n", domainStr, err)
continue continue
} }
err = common.InitRepo(repoUrl, gitWorkspace) if err := server.AddAndPushCerts(ws, certsDir, config); err != nil {
if err != nil {
fmt.Printf("Error initializing repo for domain %s: %v\n", domainStr, err)
continue
}
} else {
repoUrl = appShared.Config().Git.Server + "/" + appShared.Config().Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git"
err = common.CloneRepo(repoUrl, gitWorkspace, common.Server, config)
if err != nil {
fmt.Printf("Error cloning repo for domain %s: %v\n", domainStr, err)
continue
}
}
err = common.AddAndPushCerts(domainStr, gitWorkspace, config, domainConfig)
if err != nil {
fmt.Printf("Error pushing certificates for domain %s: %v\n", domainStr, err) fmt.Printf("Error pushing certificates for domain %s: %v\n", domainStr, err)
continue continue
} }
fmt.Printf("Successfully pushed certificates for domain %s\n", domainStr) fmt.Printf("Successfully pushed certificates for domain %s\n", domainStr)
} }
}
if err := appShared.SaveDomainConfigs(); err != nil { if err := appShared.SaveDomainConfigs(); err != nil {
fmt.Printf("Error saving domain configs: %v\n", err) fmt.Printf("Error saving domain configs: %v\n", err)
} }
} }
// prepareServerWorkspace creates or clones the domain's remote repo into a
// fresh in-memory workspace. If the repo is being cloned, it verifies that
// SERVER_ID matches this server's UUID (or is absent, in which case the
// domain is adopted on the next push).
func prepareServerWorkspace(config *common.AppConfig, domainConfig *common.DomainConfig, domain string) (*common.GitWorkspace, error) {
if !domainConfig.Internal.RepoExists {
url, err := server.CreateRepo(config, domainConfig, domain)
if err != nil {
return nil, fmt.Errorf("create remote repo: %w", err)
}
domainConfig.Internal.RepoExists = true
if err := appShared.WriteDomainConfig(domainConfig); err != nil {
return nil, fmt.Errorf("save domain config: %w", err)
}
ws := common.NewGitWorkspace(domain, url)
if err := common.InitRepo(ws); err != nil {
return nil, fmt.Errorf("init workspace: %w", err)
}
return ws, nil
}
url := common.RepoURL(config, domainConfig, domain)
ws := common.NewGitWorkspace(domain, url)
if err := common.CloneRepo(ws, config); err != nil {
return nil, fmt.Errorf("clone: %w", err)
}
owned, err := server.VerifyOwnership(ws, config.App.UUID)
if err != nil {
return nil, err
}
if !owned {
fmt.Printf("Adopting unclaimed repo for domain %s\n", domain)
}
return ws, nil
}
func (d *Daemon) Reload() { func (d *Daemon) Reload() {
fmt.Println("Reloading configs...") fmt.Println("Reloading configs...")
err := appShared.LoadDomainConfigs() err := appShared.LoadDomainConfigs()

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/Keys/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

@@ -1,109 +1,128 @@
package client package client
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
) )
func PullCerts(config *common.AppConfig, domainConfig *common.DomainConfig, gitWorkspace *common.GitWorkspace) error { // DecryptAndWriteCertificates walks the workspace's root directory, decrypts
// Ex: https://git.example.com/Org/Repo-suffix.git // every *.crpt file using the domain's crypto key, and writes the cleartext
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?) // output into certsDir.
repoUrl := config.Git.Server + "/" + config.Git.OrgName + "/" + gitWorkspace.Domain + domainConfig.Repo.RepoSuffix + ".git" //
err := common.CloneRepo(repoUrl, gitWorkspace, common.Client, config) // On a fully successful pass it records the current HEAD commit SHA via
// WriteCommitHash, so the next tick can short-circuit when nothing changed.
// Per-file failures are collected and returned together; the commit-hash
// marker is only written when every file decrypted cleanly, so a partial
// sync never masquerades as up-to-date on the next tick.
func DecryptAndWriteCertificates(certsDir string, domainConfig *common.DomainConfig, ws *common.GitWorkspace) error {
entries, err := ws.FS.ReadDir("/")
if err != nil { if err != nil {
return fmt.Errorf("Error cloning domain repo %s: %v\n", gitWorkspace.Domain, err) return fmt.Errorf("read workspace root: %w", err)
} }
var errs []error
var wrote int
for _, entry := range entries {
name := entry.Name()
if !strings.HasSuffix(name, ".crpt") {
continue
}
plainName, _ := strings.CutSuffix(name, ".crpt")
data, err := readWorkspaceFile(ws, name)
if err != nil {
errs = append(errs, fmt.Errorf("%s: %w", name, err))
continue
}
if err := common.DecryptFileFromBytes(domainConfig.Certificates.CryptoKey, data, filepath.Join(certsDir, plainName), nil); err != nil {
errs = append(errs, fmt.Errorf("%s: decrypt: %w", name, err))
continue
}
wrote++
}
if len(errs) > 0 {
return errors.Join(errs...)
}
if wrote == 0 {
return nil return nil
} }
func DecryptAndWriteCertificates(certsDir string, config *common.AppConfig, domainConfig *common.DomainConfig, gitWorkspace *common.GitWorkspace) error { head, err := ws.Repo.Head()
// Get files in repo
fileInfos, err := gitWorkspace.FS.ReadDir("/")
if err != nil { if err != nil {
return fmt.Errorf("Error reading directory in memFS on domain %s: %v\n", gitWorkspace.Domain, err) return fmt.Errorf("get repo head: %w", err)
} }
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added return WriteCommitHash(certsDir, head.Hash().String())
for _, fileInfo := range fileInfos {
if strings.HasSuffix(fileInfo.Name(), ".crpt") {
filename, _ := strings.CutSuffix(fileInfo.Name(), ".crpt")
file, err := gitWorkspace.FS.Open(fileInfo.Name())
if err != nil {
fmt.Printf("Error opening file in memFS on domain %s: %v\n", gitWorkspace.Domain, err)
continue
}
fileBytes, err := io.ReadAll(file)
if err != nil {
fmt.Printf("Error reading file in memFS on domain %s: %v\n", gitWorkspace.Domain, err)
file.Close()
continue
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file on domain %s: %v\n", gitWorkspace.Domain, err)
continue
}
err = common.DecryptFileFromBytes(domainConfig.Certificates.CryptoKey, fileBytes, filepath.Join(certsDir, filename), nil)
if err != nil {
fmt.Printf("Error decrypting file %s in domain %s: %v\n", filename, gitWorkspace.Domain, err)
continue
}
headRef, err := gitWorkspace.Repo.Head()
if err != nil {
fmt.Printf("Error getting head reference for domain %s: %v\n", gitWorkspace.Domain, err)
continue
}
err = common.WriteCommitHash(headRef.Hash().String(), config, domainConfig)
if err != nil {
fmt.Printf("Error writing commit hash: %v\n", err)
continue
}
}
}
return nil
} }
// DecryptCertificates is a standalone utility that decrypts every *.crpt
// file in an on-disk directory. It is used by the `cert decrypt` CLI command
// and does not touch git state.
func DecryptCertificates(certPath, cryptoKey string) error { func DecryptCertificates(certPath, cryptoKey string) error {
// Get files in repo entries, err := os.ReadDir(certPath)
fileInfos, err := os.ReadDir(certPath)
if err != nil { if err != nil {
return fmt.Errorf("error reading directory: %v", err) return fmt.Errorf("read %s: %w", certPath, err)
} }
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added var errs []error
for _, fileInfo := range fileInfos { for _, entry := range entries {
if strings.HasSuffix(fileInfo.Name(), ".crpt") { name := entry.Name()
filename, _ := strings.CutSuffix(fileInfo.Name(), ".crpt") if !strings.HasSuffix(name, ".crpt") {
file, err := os.OpenFile(fileInfo.Name(), os.O_RDONLY, 0640)
if err != nil {
fmt.Printf("Error opening file: %v\n", err)
continue
}
fileBytes, err := io.ReadAll(file)
if err != nil {
fmt.Printf("Error reading file: %v\n", err)
file.Close()
continue
}
err = file.Close()
if err != nil {
fmt.Printf("Error closing file: %v\n", err)
continue continue
} }
plainName, _ := strings.CutSuffix(name, ".crpt")
err = common.DecryptFileFromBytes(cryptoKey, fileBytes, filepath.Join(certPath, filename), nil) data, err := os.ReadFile(filepath.Join(certPath, name))
if err != nil { if err != nil {
fmt.Printf("Error decrypting file %s: %v\n", filename, err) errs = append(errs, fmt.Errorf("%s: %w", name, err))
continue
}
if err := common.DecryptFileFromBytes(cryptoKey, data, filepath.Join(certPath, plainName), nil); err != nil {
errs = append(errs, fmt.Errorf("%s: decrypt: %w", name, err))
continue continue
} }
} }
if len(errs) > 0 {
return errors.Join(errs...)
} }
return nil return nil
} }
// UpdateSymlinks refreshes every configured cert and key symlink so it
// points at the domain's current cert/key files under certsDir. It reports
// all link failures together rather than stopping at the first one.
func UpdateSymlinks(domain string, domainConfig *common.DomainConfig, certsDir string) error {
var errs []error
for _, link := range domainConfig.Certificates.CertSymlinks {
if err := common.LinkFile(filepath.Join(certsDir, domain+".crt"), link, domain, ".crt"); err != nil {
errs = append(errs, fmt.Errorf("cert link %s: %w", link, err))
}
}
for _, link := range domainConfig.Certificates.KeySymlinks {
if err := common.LinkFile(filepath.Join(certsDir, domain+".key"), link, domain, ".key"); err != nil {
errs = append(errs, fmt.Errorf("key link %s: %w", link, err))
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
func readWorkspaceFile(ws *common.GitWorkspace, name string) ([]byte, error) {
f, err := ws.FS.Open(name)
if err != nil {
return nil, fmt.Errorf("open: %w", err)
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("read: %w", err)
}
return data, nil
}

View File

@@ -7,38 +7,45 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
) )
func LocalCommitHash(domain string, certsDir string) (string, error) { // hashFile is the filename inside a domain's local data root that records
data, err := os.ReadFile(filepath.Join(certsDir, "hash")) // the last remote commit SHA the client successfully synced from. The daemon
if err != nil { // compares it against the remote HEAD to decide whether a sync is needed.
if !os.IsNotExist(err) { const hashFile = "hash"
fmt.Printf("Error reading file for domain %s: %v\n", domain, err)
return "", err // defaultBranch is the branch the client tracks on the remote repo.
} const defaultBranch = "master"
// WriteCommitHash persists hash to <certsDir>/hash. Call it after a
// successful sync so the next tick can skip a no-op.
func WriteCommitHash(certsDir, hash string) error {
return os.WriteFile(filepath.Join(certsDir, hashFile), []byte(hash), 0o644)
} }
// LocalCommitHash returns the commit SHA recorded at <certsDir>/hash. A
// missing file is not an error: it returns "" so a fresh client falls
// through to the full sync path.
func LocalCommitHash(certsDir string) (string, error) {
data, err := os.ReadFile(filepath.Join(certsDir, hashFile))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
return "", fmt.Errorf("read hash file: %w", err)
}
return strings.TrimSpace(string(data)), nil return strings.TrimSpace(string(data)), nil
} }
func RemoteCommitHash(domain string, gitSource common.GitSource, config *common.AppConfig, domainConfig *common.DomainConfig) (string, error) { // RemoteCommitHash returns the current HEAD commit SHA of the domain's repo
switch gitSource { // on the configured git host. It returns common.ErrRepoNotFound if the repo
case common.Gitea: // does not exist yet, letting the daemon handle the "not provisioned" case
return getRemoteCommitHashGitea(config.Git.OrgName, domain+domainConfig.Repo.RepoSuffix, "master", config) // without string-matching errors.
default: func RemoteCommitHash(config *common.AppConfig, domainConfig *common.DomainConfig, domain string) (string, error) {
fmt.Printf("Unimplemented git source %v\n", gitSource) provider, err := common.ProviderFor(config)
return "", errors.New("unimplemented git source")
}
}
func getRemoteCommitHashGitea(org, repo, branchName string, config *common.AppConfig) (string, error) {
giteaClient := common.CreateGiteaClient(config)
branch, _, err := giteaClient.GetRepoBranch(org, repo, branchName)
if err != nil { if err != nil {
fmt.Printf("Error getting repo branch: %v\n", err)
return "", err return "", err
} }
//TODO catch repo not found as ErrRepoNotInit return provider.HeadCommit(domain, defaultBranch, domainConfig)
return branch.Commit.ID, nil
} }

View File

@@ -3,36 +3,29 @@ package common
import ( import (
"errors" "errors"
"fmt" "fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"code.gitea.io/sdk/gitea"
"github.com/go-git/go-billy/v5" "github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"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"
) )
type CertManMode int // GitWorkspace is an in-memory git working tree for a single domain's
// certificate repository. It is the shared primitive that both client and
const ( // server modes operate on: client mode clones and reads, server mode
Server CertManMode = iota // init/clones and pushes. The struct carries no mode-specific state.
Client
)
type GitWorkspace struct { type GitWorkspace struct {
Domain string Domain string
Repo *git.Repository URL string
Storage *memory.Storage Storage *memory.Storage
FS billy.Filesystem FS billy.Filesystem
Repo *git.Repository
WorkTree *git.Worktree WorkTree *git.Worktree
} }
// GitSource identifies a supported git repository host.
type GitSource int type GitSource int
const ( const (
@@ -44,6 +37,8 @@ const (
CodeCommit CodeCommit
) )
// GitSourceName maps GitSource to the string used in the app config's
// git.host field.
var GitSourceName = map[GitSource]string{ var GitSourceName = map[GitSource]string{
Github: "github", Github: "github",
Gitlab: "gitlab", Gitlab: "gitlab",
@@ -53,259 +48,80 @@ var GitSourceName = map[GitSource]string{
CodeCommit: "code-commit", CodeCommit: "code-commit",
} }
// StrToGitSource parses a config string (e.g. "gitea") into a GitSource.
func StrToGitSource(s string) (GitSource, error) { func StrToGitSource(s string) (GitSource, error) {
for k, v := range GitSourceName { for k, v := range GitSourceName {
if v == s { if v == s {
return k, nil return k, nil
} }
} }
return GitSource(0), errors.New("invalid gitsource name") return 0, fmt.Errorf("invalid git source %q", s)
} }
//func createGithubClient() *github.Client { // ErrRepoNotFound is returned by RepoProvider implementations when a domain's
// return github.NewClient(nil).WithAuthToken(config.GetString("Git.api_token")) // 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 { // NewGitWorkspace returns a workspace with an in-memory filesystem and storage
client, err := gitea.NewClient(config.Git.Server, gitea.SetToken(config.Git.APIToken)) // 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(),
}
}
// 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"
}
// 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 { if err != nil {
fmt.Printf("Error connecting to gitea instance: %v\n", err) return fmt.Errorf("git init: %w", err)
return nil
} }
return client if _, err := repo.CreateRemote(&gitconf.RemoteConfig{
}
//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
}
func InitRepo(url string, ws *GitWorkspace) error {
var err error
ws.Repo, err = git.Init(ws.Storage, ws.FS)
if err != nil {
fmt.Printf("Error initializing local repo: %v\n", err)
return err
}
_, err = ws.Repo.CreateRemote(&gitconf.RemoteConfig{
Name: "origin", Name: "origin",
URLs: []string{url}, URLs: []string{ws.URL},
}) }); err != nil && !errors.Is(err, git.ErrRemoteExists) {
if err != nil && !errors.Is(err, git.ErrRemoteExists) { return fmt.Errorf("add remote: %w", err)
fmt.Printf("Error creating remote origin repo: %v\n", err)
return err
} }
wt, err := repo.Worktree()
ws.WorkTree, err = ws.Repo.Worktree()
if err != nil { if err != nil {
fmt.Printf("Error getting worktree from local repo: %v\n", err) return fmt.Errorf("get worktree: %w", err)
return err
} }
ws.Repo = repo
ws.WorkTree = wt
return nil return nil
} }
func CloneRepo(url string, ws *GitWorkspace, certmanMode CertManMode, config *AppConfig) error { // CloneRepo clones ws.URL into ws using the git credentials from config. It
creds := &http.BasicAuth{ // 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, Username: config.Git.Username,
Password: config.Git.APIToken, Password: config.Git.APIToken,
} }
var err error repo, err := git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: ws.URL, Auth: auth})
ws.Repo, err = git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: url, Auth: creds})
if err != nil { if err != nil {
fmt.Printf("Error cloning repo: %v\n", err) return fmt.Errorf("git clone %s: %w", ws.URL, err)
} }
wt, err := repo.Worktree()
ws.WorkTree, err = ws.Repo.Worktree()
if err != nil { if err != nil {
fmt.Printf("Error getting worktree from cloned repo: %v\n", err) return fmt.Errorf("get worktree: %w", err)
return err
} }
if certmanMode == Server { ws.Repo = repo
serverIdFile, err := ws.FS.OpenFile("/SERVER_ID", os.O_RDWR, 0640) ws.WorkTree = wt
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("server ID file not found for %s, adopting domain\n", 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 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 = config.Certificates.DataRoot
} else {
dataRoot = domainConfig.Certificates.DataRoot
}
err := os.WriteFile(filepath.Join(dataRoot, "hash"), []byte(hash), 0644)
if err != nil {
return err
}
return nil 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" "strconv"
"strings" "strings"
"syscall" "syscall"
"code.gitea.io/sdk/gitea"
) )
var ( var (
@@ -21,13 +19,6 @@ var (
ErrBlankCert = errors.New("cert is blank") ErrBlankCert = errors.New("cert is blank")
) )
type Domain struct {
name *string
config *AppConfig
description *string
gtClient *gitea.Client
}
// 0x01 // 0x01
func createPIDFile() { func createPIDFile() {
file, err := os.Create("/var/run/certman.pid") file, err := os.Create("/var/run/certman.pid")
@@ -293,7 +284,23 @@ 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 { // 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 { if config == nil {
return "" return ""
} }

View File

@@ -16,7 +16,7 @@ import (
"sync" "sync"
"time" "time"
"git.nevets.tech/Keys/certman/common" "git.nevets.tech/Steven/certman/common"
"github.com/go-acme/lego/v4/certcrypto" "github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate" "github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/lego" "github.com/go-acme/lego/v4/lego"
@@ -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,156 @@
package server package server
import (
"fmt"
"io"
"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"
)
// serverIDFile is the filename inside the domain's git repo that records
// which server (by config.App.UUID) owns the repo. Only the owning server
// pushes to it; other servers must refuse.
const serverIDFile = "SERVER_ID"
// pushBranch is the branch server mode pushes to. The Gitea repo is created
// with this as its default branch; the client tracks the same name.
const pushBranch = "master"
// CreateRepo provisions the domain's remote repo via the configured provider
// and returns its clone URL.
func CreateRepo(config *common.AppConfig, domainConfig *common.DomainConfig, domain string) (string, error) {
provider, err := common.ProviderFor(config)
if err != nil {
return "", err
}
return provider.CreateRepo(domain, domainConfig)
}
// VerifyOwnership reads SERVER_ID from the cloned workspace and compares it
// against uuid. It returns:
//
// (true, nil) — SERVER_ID matches uuid (we own this repo).
// (false, nil) — SERVER_ID is missing (repo is unclaimed; safe to adopt).
// (false, err) — SERVER_ID names a different server (refuse to push).
//
// The caller decides what to do with an unclaimed repo; adoption must be an
// explicit decision, not a silent fall-through. AddAndPushCerts re-writes
// SERVER_ID on every push, so the first successful push after adoption
// claims the repo for this server.
func VerifyOwnership(ws *common.GitWorkspace, uuid string) (bool, error) {
f, err := ws.FS.Open(serverIDFile)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, fmt.Errorf("open SERVER_ID: %w", err)
}
defer f.Close()
raw, err := io.ReadAll(f)
if err != nil {
return false, fmt.Errorf("read SERVER_ID: %w", err)
}
existing := strings.TrimSpace(string(raw))
if existing == uuid {
return true, nil
}
return false, fmt.Errorf("domain is owned by server %q", existing)
}
// AddAndPushCerts stages every *.crpt file from dataRoot into the workspace,
// (re-)writes SERVER_ID with config.App.UUID, commits any resulting change,
// and pushes to origin/<pushBranch>. If nothing changed the call is a no-op
// and returns nil without pushing.
func AddAndPushCerts(ws *common.GitWorkspace, dataRoot string, config *common.AppConfig) error {
if err := stageCerts(ws, dataRoot); err != nil {
return err
}
if err := stageFile(ws, serverIDFile, []byte(config.App.UUID)); err != nil {
return fmt.Errorf("stage SERVER_ID: %w", err)
}
status, err := ws.WorkTree.Status()
if err != nil {
return fmt.Errorf("get worktree status: %w", err)
}
if status.IsClean() {
return nil
}
sig := &object.Signature{
Name: "Cert Manager",
Email: config.Certificates.Email,
When: time.Now(),
}
msg := fmt.Sprintf("Update %s @ %s", ws.Domain, time.Now().Format("Mon Jan _2 2006 15:04:05 MST"))
if _, err := ws.WorkTree.Commit(msg, &git.CommitOptions{Author: sig, Committer: sig}); err != nil {
return fmt.Errorf("commit: %w", err)
}
err = ws.Repo.Push(&git.PushOptions{
Auth: &http.BasicAuth{
Username: config.Git.Username,
Password: config.Git.APIToken,
},
Force: true,
RemoteName: "origin",
RefSpecs: []gitconf.RefSpec{gitconf.RefSpec("refs/heads/" + pushBranch + ":refs/heads/" + pushBranch)},
})
if err != nil {
return fmt.Errorf("push %s: %w", ws.URL, err)
}
return nil
}
// stageCerts copies every *.crpt file in dataRoot into the workspace
// filesystem and adds it to the work tree.
func stageCerts(ws *common.GitWorkspace, dataRoot string) error {
entries, err := os.ReadDir(dataRoot)
if err != nil {
return fmt.Errorf("read %s: %w", dataRoot, err)
}
for _, entry := range entries {
name := entry.Name()
if !strings.HasSuffix(name, ".crpt") {
continue
}
body, err := os.ReadFile(filepath.Join(dataRoot, name))
if err != nil {
return fmt.Errorf("read %s: %w", name, err)
}
if err := stageFile(ws, name, body); err != nil {
return fmt.Errorf("stage %s: %w", name, err)
}
}
return nil
}
// stageFile writes body to name in the workspace filesystem and adds it to
// the work tree. It is the single point where workspace-relative paths are
// constructed, so Create and Add always agree on the path.
func stageFile(ws *common.GitWorkspace, name string, body []byte) error {
f, err := ws.FS.Create(name)
if err != nil {
return fmt.Errorf("create: %w", err)
}
if _, err := f.Write(body); err != nil {
f.Close()
return fmt.Errorf("write: %w", err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("close: %w", err)
}
if _, err := ws.WorkTree.Add(f.Name()); err != nil {
return fmt.Errorf("git add: %w", err)
}
return nil
}