2 Commits

Author SHA1 Message Date
0a78b70821 Refactored config system again
All checks were successful
Build (artifact) / build (push) Successful in 27s
2026-06-30 16:48:05 -04:00
c01195643a Lets see if this works
All checks were successful
Build (artifact) / build (push) Successful in 1m13s
2026-06-29 07:57:03 -04:00
24 changed files with 1078 additions and 686 deletions

View File

@@ -44,7 +44,7 @@ jobs:
run: echo "COMMIT_MSG=$(git log -1 --pretty=%s)" >> $GITHUB_ENV
- name: Build
run: make build
run: make client server
- name: Upload artifact
uses: https://github.com/actions/upload-artifact@v3

View File

@@ -1,12 +1,13 @@
VERSION := 1.1.5-beta-claude
VERSION := 1.1.7-beta
BUILD := $(shell git rev-parse --short HEAD)
UPDATE_SRC := "https://git.nevets.tech/api/v1/repos/Steven/certman/releases"
GO := go
BUILD_FLAGS := -buildmode=pie -trimpath
LDFLAGS := -linkmode=external -extldflags="-Wl,-z,relro,-z,now" -X git.nevets.tech/Keys/certman/common.Version=$(VERSION) -X git.nevets.tech/Keys/certman/common.Build=$(BUILD)
LDFLAGS := -linkmode=external -extldflags="-Wl,-z,relro,-z,now" -X git.nevets.tech/Steven/certman/common.Version=$(VERSION) -X git.nevets.tech/Steven/certman/common.Build=$(BUILD) -X git.nevets.tech/Steven/certman/app.SourceCertmanRepo=$(UPDATE_SRC)
.PHONY: proto bundle client server executor build debug stage
.PHONY: proto bundle client server executor cryptr build debug stage help
proto:
@protoc --go_out=./proto --go-grpc_out=./proto proto/hook.proto
@@ -28,7 +29,11 @@ executor: proto
@echo "Building Certman Executor"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w $(LDFLAGS)" -o ./bin/certman-executor-$(VERSION)-amd64 ./app/executor
build: proto bundle client server executor
cryptr:
@echo "Building Cryptr"
$(GO) build $(BUILD_FLAGS) -ldflags="-s -w -linkmode=external -extldflags="-Wl,-z,relro,-z,now"" -o ./bin/cryptr ./app/cryptr
build: proto bundle client server cryptr
@echo "All binaries successfully built"
debug: proto
@@ -38,3 +43,13 @@ debug: proto
stage: build
@sudo cp ./certman /srv/vm-passthru/certman
@ssh steven@192.168.122.44 updateCertman.sh
help:
@echo "proto - Generate gRPC proto stubs"
@echo "bundle - Build bundled binary (client, server, executor)"
@echo "client - Build client binary"
@echo "server - Build server binary"
@echo "executor - Build executor binary"
@echo "build - Build all binaries"
@echo "debug - Build bundled binary without stripping and hardening"
@echo "stage - Build all binaries and upload to dev environment (vm)"

View File

@@ -30,3 +30,6 @@ sudo certman new-domain example.com
## Scratch Board
- Server Flow
- Read from
# Coding Conventions
- Keep Config() calls in app space

View File

@@ -2,10 +2,13 @@ package main
import (
"fmt"
"path/filepath"
"git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/client"
"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"
)
@@ -45,24 +48,49 @@ func init() {
func renewCert(domain string) error {
config := app.Config()
domainConfig, exists := app.DomainStore().Get(domain)
domainConfig, exists := app.ClientDomainStore().Get(domain)
if !exists {
return app.ErrConfigNotFound
}
url := common.RepoURL(config, domainConfig, domain)
ws := common.NewGitWorkspace(domain, url)
if err := common.CloneRepo(ws, config); err != nil {
return fmt.Errorf("clone %s: %w", domain, err)
gitWorkspace := &common.GitWorkspace{
Domain: domain,
URL: config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git",
Storage: memory.NewStorage(),
FS: memfs.New(),
}
certsDir := common.CertsDir(config, domainConfig, domain)
return client.DecryptAndWriteCertificates(certsDir, domainConfig, ws)
if err := client.PullCerts(config, gitWorkspace); err != nil {
return err
}
certsDir := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
return client.DecryptAndWriteCertificates(certsDir, config, domainConfig, gitWorkspace)
}
func updateLinks(domain string) error {
domainConfig, exists := app.DomainStore().Get(domain)
domainConfig, exists := app.ClientDomainStore().Get(domain)
if !exists {
return fmt.Errorf("domain %s does not exist", domain)
}
certsDir := common.CertsDir(app.Config(), domainConfig, domain)
return client.UpdateSymlinks(domain, domainConfig, certsDir)
effectiveDataRoot := common.EffectiveDataRoot(app.Config(), domainConfig.Certificates.DataRoot)
certsDir := filepath.Join(effectiveDataRoot, "certificates", domain)
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+".key"), keyLink, domain, ".key")
if err != nil {
fmt.Printf("Error linking cert %s to %s: %v", keyLink, domain, err)
continue
}
}
return nil
}

View File

@@ -1,84 +1,137 @@
package main
import (
"errors"
"fmt"
"io"
"log"
"path/filepath"
"strings"
"git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/client"
"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{}
func (d *Daemon) Init() {
fmt.Println("Starting CertManager in client mode...")
if err := app.LoadDomainConfigs(); err != nil {
err := app.LoadClientDomainConfigs()
if err != nil {
log.Fatalf("Error loading domain configs: %v", err)
}
d.Tick()
}
func (d *Daemon) Tick() {
fmt.Println("tick!")
// Get local copy of configs
config := app.Config()
localDomainConfigs := app.DomainStore().Snapshot()
localDomainConfigs := app.ClientDomainStore().Snapshot()
// Loop over all domain configs (domains)
for domainStr, domainConfig := range localDomainConfigs {
// Skip non-enabled domains
if !domainConfig.Domain.Enabled {
continue
}
certsDir := common.CertsDir(config, domainConfig, domainStr)
// Short-circuit when the local copy already matches the remote HEAD.
// Only useful once the server has provisioned the repo; otherwise
// the RemoteCommitHash call returns ErrRepoNotFound and we skip
// this tick entirely (nothing to pull yet).
if domainConfig.Internal.RepoExists {
localHash, err := client.LocalCommitHash(certsDir)
if err != nil {
fmt.Printf("Error reading local hash for %s: %v\n", domainStr, err)
}
remoteHash, err := client.RemoteCommitHash(config, domainConfig, domainStr)
if err != nil {
if errors.Is(err, common.ErrRepoNotFound) {
fmt.Printf("Remote repo not yet provisioned for %s; skipping\n", domainStr)
continue
}
fmt.Printf("Error getting remote hash for %s: %v\n", domainStr, err)
continue
}
if localHash != "" && localHash == remoteHash {
fmt.Printf("Domain %s is up to date. Skipping...\n", domainStr)
continue
}
gitWorkspace := &common.GitWorkspace{
Domain: domainStr,
URL: app.Config().Git.Server + "/" + config.Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git",
Storage: memory.NewStorage(),
FS: memfs.New(),
}
url := common.RepoURL(config, domainConfig, domainStr)
ws := common.NewGitWorkspace(domainStr, url)
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?)
err := gitWorkspace.CloneRepo(common.Client, config)
if err != nil {
fmt.Printf("Error cloning domain repo %s: %v\n", domainStr, err)
continue
}
if err := client.DecryptAndWriteCertificates(certsDir, domainConfig, ws); err != nil {
fmt.Printf("Error decrypting certificates for %s: %v\n", domainStr, err)
effectiveDataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
certsDir := filepath.Join(effectiveDataRoot, "certificates", domainStr)
// 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
}
if err := client.UpdateSymlinks(domainStr, domainConfig, certsDir); err != nil {
fmt.Printf("Error updating symlinks for %s: %v\n", domainStr, err)
continue
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added
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", domainStr, err)
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
}
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
err = client.WriteCommitHash(headRef.Hash().String(), dataRoot)
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() {
fmt.Println("Reloading configs...")
if err := app.LoadDomainConfigs(); err != nil {
err := app.LoadClientDomainConfigs()
if err != nil {
fmt.Printf("Error loading domain configs: %v\n", err)
return
}
}

View File

@@ -3,36 +3,13 @@ package main
import (
"context"
"fmt"
"log"
"time"
"git.nevets.tech/Steven/certman/app"
pb "git.nevets.tech/Steven/certman/proto/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func SendHook(domain string) {
conn, err := grpc.NewClient(
"unix:///run/certman.sock",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewHookServiceClient(conn)
hooks, err := app.PostPullHooks(domain)
if err != nil {
fmt.Printf("Error getting hooks: %v\n", err)
return
}
for _, hook := range hooks {
sendHook(client, hook)
}
}
// SendHook is currently a no-op pending hook config modeling on ClientDomainConfig.
func SendHook(domain string) {}
func sendHook(client pb.HookServiceClient, hook *pb.Hook) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

View File

@@ -20,6 +20,7 @@ func main() {
rootCmd.AddCommand(app.VersionCmd)
rootCmd.AddCommand(app.NewKeyCmd)
rootCmd.AddCommand(app.UpdateCmd)
rootCmd.AddCommand(app.DevCmd)
rootCmd.AddCommand(app.NewDomainCmd)

View File

@@ -1,8 +1,11 @@
package app
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"os/user"
@@ -15,7 +18,8 @@ import (
var (
VersionCmd = basicCmd("version", "Show version", versionCmd)
NewKeyCmd = basicCmd("gen-key", "Generates encryption key", newKeyCmd)
NewKeyCmd = basicCmd("gen-key", "Generates encryption key", GenKeyCmd)
UpdateCmd = basicCmd("update", "Updates if new version is found", updateCmd)
DevCmd = basicCmd("dev", "Dev Function", devCmd)
domainCertDir string
@@ -55,17 +59,17 @@ func init() {
}
func devCmd(cmd *cobra.Command, args []string) {
testDomain := "lunamc.org"
err := LoadConfig()
if err != nil {
log.Fatalf("Error loading configuration: %v\n", err)
}
err = LoadDomainConfigs()
if err != nil {
log.Fatalf("Error loading configs: %v\n", err)
}
fmt.Println(testDomain)
//testDomain := "lunamc.org"
//err := LoadConfig()
//if err != nil {
// log.Fatalf("Error loading configuration: %v\n", err)
//}
//err = LoadDomainConfigs()
//if err != nil {
// log.Fatalf("Error loading configs: %v\n", err)
//}
//
//fmt.Println(testDomain)
}
func versionCmd(cmd *cobra.Command, args []string) {
@@ -74,12 +78,47 @@ func versionCmd(cmd *cobra.Command, args []string) {
)
}
func newKeyCmd(cmd *cobra.Command, args []string) {
func GenKeyCmd(cmd *cobra.Command, args []string) {
key, err := common.GenerateKey()
if err != nil {
log.Fatalf("%v", err)
}
fmt.Println(key)
fmt.Printf(key)
}
func updateCmd(cmd *cobra.Command, args []string) {
if os.Geteuid() != 0 {
log.Fatal(fmt.Errorf("installation must be run as root"))
}
err := LoadConfig()
if err != nil {
log.Fatalf("%v", err)
}
resp, err := http.Get(SourceCertmanRepo + "/latest")
if err != nil {
log.Fatalf("%v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
var release GiteaRelease
err = json.Unmarshal(body, &release)
if err != nil {
log.Fatalf("%v", err)
}
for _, asset := range release.Assets {
if strings.Contains(asset.Name, Config().App.Mode) {
if !strings.Contains(asset.Name, common.Version) {
fmt.Printf("Found a newer version: %s\n", asset.Name)
err = downloadFile("/usr/local/bin/certman", SourceCertmanRepo+"/"+strconv.Itoa(release.Id)+"/assets/"+strconv.Itoa(asset.Id))
if err != nil {
log.Fatalf("%v", err)
}
}
}
}
}
func newDomainCmd(domain, domainDir string, dirOverridden bool) error {
@@ -160,15 +199,8 @@ func installCmd(isThin bool, mode string) error {
return fmt.Errorf("error creating group: %v: output %s", err, output)
}
}
certmanUser, err := user.Lookup("certman")
if err != nil {
return fmt.Errorf("error getting user certman: %v", err)
}
uid, err := strconv.Atoi(strings.TrimSpace(certmanUser.Uid))
if err != nil {
return err
}
gid, err := strconv.Atoi(strings.TrimSpace(certmanUser.Gid))
//TODO chmod after chown
uid, gid, err := GetUserIds("certman")
if err != nil {
return err
}
@@ -187,5 +219,12 @@ func installCmd(isThin bool, mode string) error {
} else {
CreateConfig(mode)
}
//TODO move executable to /usr/bin
//execPath, err := os.Executable()
//if err != nil {
// return err
//}
return nil
}

View File

@@ -10,7 +10,6 @@ import (
"sync"
"git.nevets.tech/Steven/certman/common"
pb "git.nevets.tech/Steven/certman/proto/v1"
"github.com/google/uuid"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper"
@@ -21,42 +20,46 @@ var (
ErrConfigNotFound = errors.New("config file not found")
)
type DomainConfigStore struct {
// ---------------------------------------------------------------------------
// Generic domain config store
// ---------------------------------------------------------------------------
type DomainConfigStore[T any] struct {
mu sync.RWMutex
configs map[string]*common.DomainConfig
configs map[string]*T
}
func NewDomainConfigStore() *DomainConfigStore {
return &DomainConfigStore{
configs: make(map[string]*common.DomainConfig),
func NewDomainConfigStore[T any]() *DomainConfigStore[T] {
return &DomainConfigStore[T]{
configs: make(map[string]*T),
}
}
func (s *DomainConfigStore) Get(domain string) (*common.DomainConfig, bool) {
func (s *DomainConfigStore[T]) Get(domain string) (*T, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.configs[domain]
return v, ok
}
func (s *DomainConfigStore) Set(domain string, v *common.DomainConfig) {
func (s *DomainConfigStore[T]) Set(domain string, v *T) {
s.mu.Lock()
defer s.mu.Unlock()
s.configs[domain] = v
}
// Swap atomically replaces the entire config map (used during reload).
func (s *DomainConfigStore) Swap(newConfigs map[string]*common.DomainConfig) {
func (s *DomainConfigStore[T]) Swap(newConfigs map[string]*T) {
s.mu.Lock()
defer s.mu.Unlock()
s.configs = newConfigs
}
// Snapshot returns a shallow copy safe to iterate without holding the lock.
func (s *DomainConfigStore) Snapshot() map[string]*common.DomainConfig {
func (s *DomainConfigStore[T]) Snapshot() map[string]*T {
s.mu.RLock()
defer s.mu.RUnlock()
snap := make(map[string]*common.DomainConfig, len(s.configs))
snap := make(map[string]*T, len(s.configs))
for k, v := range s.configs {
snap[k] = v
}
@@ -68,9 +71,10 @@ func (s *DomainConfigStore) Snapshot() map[string]*common.DomainConfig {
// ---------------------------------------------------------------------------
var (
config *common.AppConfig
configMu sync.RWMutex
domainStore = NewDomainConfigStore()
config *common.AppConfig
configMu sync.RWMutex
serverDomainStore = NewDomainConfigStore[common.ServerDomainConfig]()
clientDomainStore = NewDomainConfigStore[common.ClientDomainConfig]()
)
func Config() *common.AppConfig {
@@ -79,8 +83,12 @@ func Config() *common.AppConfig {
return config
}
func DomainStore() *DomainConfigStore {
return domainStore
func ServerDomainStore() *DomainConfigStore[common.ServerDomainConfig] {
return serverDomainStore
}
func ClientDomainStore() *DomainConfigStore[common.ClientDomainConfig] {
return clientDomainStore
}
// ---------------------------------------------------------------------------
@@ -110,15 +118,16 @@ func LoadConfig() error {
return nil
}
// LoadDomainConfigs reads every .conf file in the domains directory.
func LoadDomainConfigs() error {
// loadDomainConfigs walks /etc/certman/domains and unmarshals every .conf file
// into T, keyed by domain.domain_name.
func loadDomainConfigs[T any]() (map[string]*T, error) {
dir := "/etc/certman/domains/"
entries, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("reading domain config dir: %w", err)
return nil, fmt.Errorf("reading domain config dir: %w", err)
}
temp := make(map[string]*common.DomainConfig)
out := make(map[string]*T)
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".conf" {
@@ -131,26 +140,47 @@ func LoadDomainConfigs() error {
v.SetConfigType("toml")
if err := v.ReadInConfig(); err != nil {
return fmt.Errorf("loading %s: %w", path, err)
return nil, fmt.Errorf("loading %s: %w", path, err)
}
domain := v.GetString("domain.domain_name")
if domain == "" {
return fmt.Errorf("%s: missing domain.domain_name", path)
return nil, fmt.Errorf("%s: missing domain.domain_name", path)
}
if _, exists := temp[domain]; exists {
if _, exists := out[domain]; exists {
fmt.Printf("Duplicate domain in %s, skipping...\n", path)
continue
}
cfg := &common.DomainConfig{}
cfg := new(T)
if err = v.Unmarshal(cfg); err != nil {
return fmt.Errorf("unmarshaling %s: %w", path, err)
return nil, fmt.Errorf("unmarshaling %s: %w", path, err)
}
temp[domain] = cfg
out[domain] = cfg
}
domainStore.Swap(temp)
return out, nil
}
// LoadServerDomainConfigs reads every .conf file in the domains directory into
// the server-typed store.
func LoadServerDomainConfigs() error {
configs, err := loadDomainConfigs[common.ServerDomainConfig]()
if err != nil {
return err
}
serverDomainStore.Swap(configs)
return nil
}
// LoadClientDomainConfigs reads every .conf file in the domains directory into
// the client-typed store.
func LoadClientDomainConfigs() error {
configs, err := loadDomainConfigs[common.ClientDomainConfig]()
if err != nil {
return err
}
clientDomainStore.Swap(configs)
return nil
}
@@ -170,40 +200,44 @@ func WriteConfig(filePath string, config *common.AppConfig) error {
return nil
}
func WriteDomainConfig(config *common.DomainConfig) error {
buf, err := toml.Marshal(config)
func writeDomainConfigFile(domainName string, v any) error {
buf, err := toml.Marshal(v)
if err != nil {
return fmt.Errorf("marshaling domain config: %w", err)
}
configPath := filepath.Join("/etc/certman/domains", config.Domain.DomainName+".conf")
configPath := filepath.Join("/etc/certman/domains", domainName+".conf")
if err = os.WriteFile(configPath, buf, 0640); err != nil {
return fmt.Errorf("write config file: %w", err)
}
return nil
}
// SaveDomainConfigs writes every loaded domain config back to disk.
func SaveDomainConfigs() error {
for _, v := range domainStore.Snapshot() {
err := WriteDomainConfig(v)
if err != nil {
func WriteServerDomainConfig(config *common.ServerDomainConfig) error {
return writeDomainConfigFile(config.Domain.DomainName, config)
}
func WriteClientDomainConfig(config *common.ClientDomainConfig) error {
return writeDomainConfigFile(config.Domain.DomainName, config)
}
// SaveServerDomainConfigs writes every loaded server domain config back to disk.
func SaveServerDomainConfigs() error {
for _, v := range serverDomainStore.Snapshot() {
if err := WriteServerDomainConfig(v); err != nil {
return err
}
}
return nil
}
// ---------------------------------------------------------------------------
// Domain Specific Lookups
// ---------------------------------------------------------------------------
func PostPullHooks(domain string) ([]*pb.Hook, error) {
var hooks []*pb.Hook
if err := viper.UnmarshalKey("Hooks.PostPull", hooks); err != nil {
return nil, err
// SaveClientDomainConfigs writes every loaded client domain config back to disk.
func SaveClientDomainConfigs() error {
for _, v := range clientDomainStore.Snapshot() {
if err := WriteClientDomainConfig(v); err != nil {
return err
}
}
return hooks, nil
return nil
}
// ---------------------------------------------------------------------------

117
app/cryptr/main.go Normal file
View File

@@ -0,0 +1,117 @@
package main
import (
"bufio"
"bytes"
"encoding/base64"
"fmt"
"os"
"git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/common"
"github.com/spf13/cobra"
)
func main() {
rootCmd := &cobra.Command{
Use: "cryptr",
Short: "cryptr is a tool for encrypting and decrypting files",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
rootCmd.AddCommand(&cobra.Command{
Use: "key-gen",
Short: "Generates encryption key",
Run: app.GenKeyCmd,
})
var (
keyUTF8 bool
keyFile string
)
encryptCmd := &cobra.Command{
Use: "encrypt",
Short: "encrypt a file",
RunE: func(cmd *cobra.Command, args []string) error {
key, err := getKey(keyFile, keyUTF8)
if err != nil {
return err
}
fmt.Println(key)
inFilePath := args[0]
outFilePath := args[1]
return common.EncryptFileXChaCha(key, inFilePath, outFilePath, nil)
},
}
encryptCmd.Flags().BoolVar(&keyUTF8, "utf8", false, "Use UTF-8 encoded key")
encryptCmd.Flags().StringVar(&keyFile, "key", "", "File containing key")
rootCmd.AddCommand(encryptCmd)
decryptCmd := &cobra.Command{
Use: "decrypt",
Short: "decrypt a file",
RunE: func(cmd *cobra.Command, args []string) error {
key, err := getKey(keyFile, keyUTF8)
if err != nil {
return err
}
inFilePath := args[0]
outFilePath := args[1]
inFile, err := os.ReadFile(inFilePath)
if err != nil {
return err
}
return common.DecryptFileFromBytes(key, inFile, outFilePath, nil)
},
}
decryptCmd.Flags().BoolVar(&keyUTF8, "utf8", false, "Use UTF-8 encoded key")
decryptCmd.Flags().StringVar(&keyFile, "key", "", "File containing key")
rootCmd.AddCommand(decryptCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func normalizeKey(b []byte) []byte {
out := make([]byte, 32)
copy(out, b)
return out
}
func getKey(keyFile string, keyUTF8 bool) (string, error) {
var raw []byte
if keyFile != "" {
b, err := os.ReadFile(keyFile)
if err != nil {
return "", err
}
raw = b
} else {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Key: ")
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return "", err
}
}
raw = scanner.Bytes()
}
var keyBytes []byte
if keyUTF8 {
keyBytes = normalizeKey(bytes.TrimSpace(raw))
} else {
decoded, err := base64.StdEncoding.DecodeString(string(bytes.TrimSpace(raw)))
if err != nil {
return "", fmt.Errorf("key is not valid base64: %w", err)
}
keyBytes = normalizeKey(decoded)
}
return base64.StdEncoding.EncodeToString(keyBytes), nil
}

View File

@@ -8,6 +8,8 @@ import (
"git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/common"
"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"
)
@@ -32,54 +34,92 @@ func renewCertCmd(domain string, noPush bool) error {
if err := app.LoadConfig(); err != nil {
return err
}
if err := app.LoadDomainConfigs(); err != nil {
if err := app.LoadServerDomainConfigs(); err != nil {
return err
}
mgr, err := server.NewACMEManager(app.Config())
if err != nil {
return err
}
return renewCerts(domain, noPush, mgr)
err = 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 {
config := app.Config()
domainConfig, exists := app.DomainStore().Get(domain)
domainConfig, exists := app.ServerDomainStore().Get(domain)
if !exists {
return fmt.Errorf("domain %s does not exist", domain)
}
if _, err := mgr.RenewForDomain(domain); err != nil {
// If the domain has no stored resource yet, fall through to Obtain.
if _, err := mgr.ObtainForDomain(domain, config, domainConfig); err != nil {
_, err := mgr.RenewForDomain(domainConfig)
if err != nil {
// if no existing cert, obtain instead
_, err = mgr.ObtainForDomain(config, domainConfig)
if err != nil {
return fmt.Errorf("error obtaining domain certificates for domain %s: %v", domain, err)
}
}
domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
if err := app.WriteDomainConfig(domainConfig); err != nil {
err = app.WriteServerDomainConfig(domainConfig)
if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err)
}
certsDir := filepath.Join(mgr.CertsRoot, domain)
if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domain+".crt"), filepath.Join(certsDir, domain+".crt.crpt"), nil); err != nil {
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(mgr.CertsRoot, domain, domain+".crt"), filepath.Join(mgr.CertsRoot, domain, domain+".crt.crpt"), nil)
if err != nil {
return fmt.Errorf("error encrypting domain cert for domain %s: %v", domain, err)
}
if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domain+".key"), filepath.Join(certsDir, domain+".key.crpt"), nil); err != nil {
err = common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(mgr.CertsRoot, domain, domain+".key"), filepath.Join(mgr.CertsRoot, domain, domain+".key.crpt"), nil)
if err != nil {
return fmt.Errorf("error encrypting domain key for domain %s: %v", domain, err)
}
if noPush {
return nil
if !noPush {
giteaClient := common.CreateGiteaClient(config)
if giteaClient == nil {
return fmt.Errorf("error creating gitea client for domain %s: %v", domain, err)
}
gitWorkspace := &common.GitWorkspace{
Storage: memory.NewStorage(),
FS: memfs.New(),
}
if !domainConfig.Internal.RepoExists {
gitWorkspace.URL = common.CreateGiteaRepo(domain, giteaClient, config, domainConfig)
if gitWorkspace.URL == "" {
return fmt.Errorf("error creating Gitea repo for domain %s", domain)
}
domainConfig.Internal.RepoExists = true
err = app.WriteServerDomainConfig(domainConfig)
if err != nil {
return fmt.Errorf("error saving domain config %s: %v", domain, err)
}
err = gitWorkspace.InitRepo()
if err != nil {
return fmt.Errorf("error initializing repo for domain %s: %v", domain, err)
}
} else {
gitWorkspace.URL = config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git"
err = gitWorkspace.CloneRepo(common.Server, config)
if err != nil {
return fmt.Errorf("error cloning repo for domain %s: %v", domain, err)
}
}
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
err = server.AddAndPushCerts(gitWorkspace, dataRoot, domainConfig.Repo.RepoSuffix, config)
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)
}
ws, err := prepareServerWorkspace(config, domainConfig, domain)
if err != nil {
return fmt.Errorf("prepare workspace for %s: %w", domain, err)
}
if err := server.AddAndPushCerts(ws, certsDir, config); err != nil {
return fmt.Errorf("push certificates for %s: %w", domain, err)
}
fmt.Printf("Successfully pushed certificates for domain %s\n", domain)
return nil
}

View File

@@ -12,6 +12,8 @@ import (
appShared "git.nevets.tech/Steven/certman/app"
"git.nevets.tech/Steven/certman/common"
"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 {
@@ -36,7 +38,7 @@ func (d *Daemon) loadACMEManager() error {
func (d *Daemon) Init() {
fmt.Println("Starting CertManager in server mode...")
err := appShared.LoadDomainConfigs()
err := appShared.LoadServerDomainConfigs()
if err != nil {
log.Fatalf("Error loading domain configs: %v", err)
}
@@ -57,7 +59,7 @@ func (d *Daemon) Tick() {
now := time.Now().UTC()
config := appShared.Config()
localDomainConfigs := appShared.DomainStore().Snapshot()
localDomainConfigs := appShared.ServerDomainStore().Snapshot()
for domainStr, domainConfig := range localDomainConfigs {
if !domainConfig.Domain.Enabled {
@@ -67,95 +69,94 @@ func (d *Daemon) Tick() {
renewPeriod := domainConfig.Certificates.RenewPeriod
lastIssued := time.Unix(domainConfig.Internal.LastIssued, 0).UTC()
renewalDue := lastIssued.AddDate(0, 0, renewPeriod)
if !now.After(renewalDue) {
continue
}
//TODO extra check if certificate expiry (create cache?)
if _, err := d.ACMEManager.RenewForDomain(domainStr); err != nil {
if errors.Is(err, os.ErrNotExist) {
if _, err := d.ACMEManager.ObtainForDomain(domainStr, config, domainConfig); err != nil {
fmt.Printf("Error obtaining domain certificates for domain %s: %v\n", domainStr, err)
continue
if now.After(renewalDue) {
//TODO extra check if certificate expiry (create cache?)
_, err := d.ACMEManager.RenewForDomain(domainConfig)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// if no existing cert, obtain instead
_, err = d.ACMEManager.ObtainForDomain(appShared.Config(), domainConfig)
if err != nil {
fmt.Printf("Error obtaining domain certificates for domain %s: %v\n", domainStr, err)
continue
}
}
} else {
fmt.Printf("Error: %v\n", err)
continue
}
}
domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
if err := appShared.WriteDomainConfig(domainConfig); err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err)
continue
}
domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
err = appShared.WriteServerDomainConfig(domainConfig)
if err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err)
continue
}
certsDir := filepath.Join(d.ACMEManager.CertsRoot, domainStr)
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)
continue
}
if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domainStr+".key"), filepath.Join(certsDir, domainStr+".key.crpt"), nil); err != nil {
fmt.Printf("Error encrypting domain key for domain %s: %v\n", domainStr, err)
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)
if err != nil {
fmt.Printf("Error encrypting domain cert for domain %s: %v\n", domainStr, err)
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 != nil {
fmt.Printf("Error encrypting domain key for domain %s: %v\n", domainStr, err)
continue
}
ws, err := prepareServerWorkspace(config, domainConfig, domainStr)
if err != nil {
fmt.Printf("Error preparing git workspace for domain %s: %v\n", domainStr, err)
continue
}
giteaClient := common.CreateGiteaClient(config)
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(),
}
if err := server.AddAndPushCerts(ws, certsDir, config); err != nil {
fmt.Printf("Error pushing certificates for domain %s: %v\n", domainStr, err)
continue
if !domainConfig.Internal.RepoExists {
gitWorkspace.URL = common.CreateGiteaRepo(domainStr, giteaClient, config, domainConfig)
if gitWorkspace.URL == "" {
fmt.Printf("Error creating Gitea repo for domain %s\n", domainStr)
continue
}
domainConfig.Internal.RepoExists = true
err = appShared.WriteServerDomainConfig(domainConfig)
if err != nil {
fmt.Printf("Error saving domain config %s: %v\n", domainStr, err)
continue
}
err = gitWorkspace.InitRepo()
if err != nil {
fmt.Printf("Error initializing repo for domain %s: %v\n", domainStr, err)
continue
}
} else {
gitWorkspace.URL = appShared.Config().Git.Server + "/" + appShared.Config().Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git"
err = gitWorkspace.CloneRepo(common.Server, config)
if err != nil {
fmt.Printf("Error cloning repo for domain %s: %v\n", domainStr, err)
continue
}
}
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
err = server.AddAndPushCerts(gitWorkspace, dataRoot, domainConfig.Repo.RepoSuffix, config)
if err != nil {
fmt.Printf("Error pushing certificates for domain %s: %v\n", domainStr, err)
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.SaveServerDomainConfigs(); err != nil {
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() {
fmt.Println("Reloading configs...")
err := appShared.LoadDomainConfigs()
err := appShared.LoadServerDomainConfigs()
if err != nil {
fmt.Printf("Error loading domain configs: %v\n", err)

View File

@@ -20,9 +20,11 @@ func main() {
rootCmd.AddCommand(app.VersionCmd)
rootCmd.AddCommand(app.NewKeyCmd)
rootCmd.AddCommand(app.UpdateCmd)
rootCmd.AddCommand(app.DevCmd)
rootCmd.AddCommand(app.NewDomainCmd)
//-----------------------------------
rootCmd.AddCommand(app.InstallCmd)
rootCmd.AddCommand(app.CertCmd)

View File

@@ -2,11 +2,44 @@ package app
import (
"fmt"
"io"
"net/http"
"os"
"os/user"
"strconv"
"strings"
"github.com/spf13/cobra"
)
var SourceCertmanRepo = "http://127.0.0.1"
type GiteaRelease struct {
Id int `json:"id"`
Assets []Asset `json:"assets"`
}
type Asset struct {
Id int `json:"id"`
Name string `json:"name"`
}
func GetUserIds(username string) (int, int, error) {
userEntry, err := user.Lookup(username)
if err != nil {
return -1, -1, fmt.Errorf("error getting user %s: %v", username, err)
}
uid, err := strconv.Atoi(strings.TrimSpace(userEntry.Uid))
if err != nil {
return -1, -1, err
}
gid, err := strconv.Atoi(strings.TrimSpace(userEntry.Gid))
if err != nil {
return -1, -1, err
}
return uid, gid, nil
}
func createFile(fileName string, filePermission os.FileMode, data []byte) {
fileInfo, err := os.Stat(fileName)
if err != nil {
@@ -49,6 +82,45 @@ func createFile(fileName string, filePermission os.FileMode, data []byte) {
}
}
// downloadFile streams data from a URL and saves it directly to a local file path
func downloadFile(filepath string, url string) error {
// 1. Send the HTTP GET request
resp, err := http.Get(url)
if err != nil {
return err
}
// Always close the response body to prevent resource leaks
defer resp.Body.Close()
// 2. Check for a valid HTTP 200 OK status code
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
// 3. Create the local destination file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
uid, gid, err := GetUserIds("certman")
if err != nil {
return err
}
err = out.Chown(uid, gid)
if err != nil {
return err
}
err = out.Chmod(775)
if err != nil {
return err
}
// 4. Stream the server response body directly into the local file
_, err = io.Copy(out, resp.Body)
return err
}
func basicCmd(use, short string, commandFunc func(cmd *cobra.Command, args []string)) *cobra.Command {
return &cobra.Command{
Use: use,

View File

@@ -1,7 +1,6 @@
package client
import (
"errors"
"fmt"
"io"
"os"
@@ -11,118 +10,100 @@ import (
"git.nevets.tech/Steven/certman/common"
)
// DecryptAndWriteCertificates walks the workspace's root directory, decrypts
// every *.crpt file using the domain's crypto key, and writes the cleartext
// output into certsDir.
//
// 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("/")
func PullCerts(config *common.AppConfig, gitWorkspace *common.GitWorkspace) error {
// Ex: https://git.example.com/Org/Repo-suffix.git
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
err := gitWorkspace.CloneRepo(common.Client, config)
if err != nil {
return fmt.Errorf("read workspace root: %w", err)
return fmt.Errorf("Error cloning domain repo %s: %v\n", gitWorkspace.Domain, 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
}
head, err := ws.Repo.Head()
if err != nil {
return fmt.Errorf("get repo head: %w", err)
}
return WriteCommitHash(certsDir, head.Hash().String())
return nil
}
func DecryptAndWriteCertificates(certsDir string, config *common.AppConfig, domainConfig *common.ClientDomainConfig, gitWorkspace *common.GitWorkspace) error {
// Get files in repo
fileInfos, err := gitWorkspace.FS.ReadDir("/")
if err != nil {
return fmt.Errorf("Error reading directory in memFS on domain %s: %v\n", gitWorkspace.Domain, err)
}
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added
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
}
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
err = WriteCommitHash(headRef.Hash().String(), dataRoot)
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 {
entries, err := os.ReadDir(certPath)
// Get files in repo
fileInfos, err := os.ReadDir(certPath)
if err != nil {
return fmt.Errorf("read %s: %w", certPath, err)
return fmt.Errorf("error reading directory: %v", err)
}
var errs []error
for _, entry := range entries {
name := entry.Name()
if !strings.HasSuffix(name, ".crpt") {
continue
}
plainName, _ := strings.CutSuffix(name, ".crpt")
// Iterate over files, filtering by .crpt (encrypted) files in case other files were accidentally added
for _, fileInfo := range fileInfos {
if strings.HasSuffix(fileInfo.Name(), ".crpt") {
filename, _ := strings.CutSuffix(fileInfo.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
}
data, err := os.ReadFile(filepath.Join(certPath, name))
if err != nil {
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
err = common.DecryptFileFromBytes(cryptoKey, fileBytes, filepath.Join(certPath, filename), nil)
if err != nil {
fmt.Printf("Error decrypting file %s: %v\n", filename, err)
continue
}
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
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

@@ -10,42 +10,52 @@ import (
"git.nevets.tech/Steven/certman/common"
)
// hashFile is the filename inside a domain's local data root that records
// the last remote commit SHA the client successfully synced from. The daemon
// compares it against the remote HEAD to decide whether a sync is needed.
const hashFile = "hash"
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
//}
// defaultBranch is the branch the client tracks on the remote repo.
const defaultBranch = "master"
err := os.WriteFile(filepath.Join(dataRoot, "hash"), []byte(hash), 0644)
if err != nil {
return err
}
// 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)
return nil
}
// 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))
func LocalCommitHash(domain string, certsDir string) (string, error) {
data, err := os.ReadFile(filepath.Join(certsDir, "hash"))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return "", nil
if !os.IsNotExist(err) {
fmt.Printf("Error reading file for domain %s: %v\n", domain, err)
return "", err
}
return "", fmt.Errorf("read hash file: %w", err)
}
return strings.TrimSpace(string(data)), nil
}
// RemoteCommitHash returns the current HEAD commit SHA of the domain's repo
// on the configured git host. It returns common.ErrRepoNotFound if the repo
// does not exist yet, letting the daemon handle the "not provisioned" case
// without string-matching errors.
func RemoteCommitHash(config *common.AppConfig, domainConfig *common.DomainConfig, domain string) (string, error) {
provider, err := common.ProviderFor(config)
func RemoteCommitHash(domain string, gitSource common.GitSource, config *common.AppConfig, domainConfig *common.ClientDomainConfig) (string, error) {
switch gitSource {
case common.Gitea:
return getRemoteCommitHashGitea(config.Git.OrgName, domain+domainConfig.Repo.RepoSuffix, "master", config)
default:
fmt.Printf("Unimplemented git source %v\n", gitSource)
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 {
fmt.Printf("Error getting repo branch: %v\n", err)
return "", err
}
return provider.HeadCommit(domain, defaultBranch, domainConfig)
//TODO catch repo not found as ErrRepoNotInit
return branch.Commit.ID, nil
}

View File

@@ -36,30 +36,6 @@ type Cloudflare struct {
CFAPIKey string `mapstructure:"cf_api_key" toml:"cf_api_key"`
}
type DomainConfig struct {
Domain DomainCfg `mapstructure:"domain" toml:"domain"`
Certificates DomainCerts `mapstructure:"certificates" toml:"certificates"`
Repo Repo `mapstructure:"repo" toml:"repo"`
Internal Internal `mapstructure:"shared" toml:"shared"`
}
type DomainCfg struct {
DomainName string `mapstructure:"domain_name" toml:"domain_name"`
Enabled bool `mapstructure:"enabled" toml:"enabled"`
DNSServer string `mapstructure:"dns_server" toml:"dns_server"`
}
type DomainCerts struct {
DataRoot string `mapstructure:"data_root" toml:"data_root"`
RequestMethod string `mapstructure:"request_method" toml:"request_method"`
CryptoKey string `mapstructure:"crypto_key" toml:"crypto_key"`
Expiry int `mapstructure:"expiry" toml:"expiry"`
RenewPeriod int `mapstructure:"renew_period" toml:"renew_period"`
SubDomains []string `mapstructure:"sub_domains" toml:"sub_domains"`
CertSymlinks []string `mapstructure:"cert_symlinks" toml:"cert_symlinks"`
KeySymlinks []string `mapstructure:"key_symlinks" toml:"key_symlinks"`
}
type Repo struct {
RepoSuffix string `mapstructure:"repo_suffix" toml:"repo_suffix"`
}
@@ -69,3 +45,51 @@ type Internal struct {
RepoExists bool `mapstructure:"repo_exists" toml:"repo_exists"`
Status string `mapstructure:"status" toml:"status"`
}
// ---------------------------------------------------------------------------
// Server domain config
// ---------------------------------------------------------------------------
type ServerDomainConfig struct {
Domain ServerDomainCfg `mapstructure:"domain" toml:"domain"`
Certificates ServerDomainCerts `mapstructure:"certificates" toml:"certificates"`
Repo Repo `mapstructure:"repo" toml:"repo"`
Internal Internal `mapstructure:"internal" toml:"internal"`
}
type ServerDomainCfg struct {
DomainName string `mapstructure:"domain_name" toml:"domain_name"`
Enabled bool `mapstructure:"enabled" toml:"enabled"`
DNSServer string `mapstructure:"dns_server" toml:"dns_server"`
}
type ServerDomainCerts struct {
DataRoot string `mapstructure:"data_root" toml:"data_root"`
CryptoKey string `mapstructure:"crypto_key" toml:"crypto_key"`
RequestMethod string `mapstructure:"request_method" toml:"request_method"`
Expiry int `mapstructure:"expiry" toml:"expiry"`
RenewPeriod int `mapstructure:"renew_period" toml:"renew_period"`
SubDomains []string `mapstructure:"sub_domains" toml:"sub_domains"`
}
// ---------------------------------------------------------------------------
// Client domain config
// ---------------------------------------------------------------------------
type ClientDomainConfig struct {
Domain ClientDomainCfg `mapstructure:"domain" toml:"domain"`
Certificates ClientDomainCerts `mapstructure:"certificates" toml:"certificates"`
Repo Repo `mapstructure:"repo" toml:"repo"`
}
type ClientDomainCfg struct {
DomainName string `mapstructure:"domain_name" toml:"domain_name"`
Enabled bool `mapstructure:"enabled" toml:"enabled"`
}
type ClientDomainCerts struct {
DataRoot string `mapstructure:"data_root" toml:"data_root"`
CryptoKey string `mapstructure:"crypto_key" toml:"crypto_key"`
CertSymlinks []string `mapstructure:"cert_symlinks" toml:"cert_symlinks"`
KeySymlinks []string `mapstructure:"key_symlinks" toml:"key_symlinks"`
}

View File

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

View File

@@ -1,55 +0,0 @@
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
}

View File

@@ -1,33 +0,0 @@
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,6 +11,8 @@ import (
"strconv"
"strings"
"syscall"
"code.gitea.io/sdk/gitea"
)
var (
@@ -19,6 +21,13 @@ var (
ErrBlankCert = errors.New("cert is blank")
)
type Domain struct {
name *string
config *AppConfig
description *string
gtClient *gitea.Client
}
// 0x01
func createPIDFile() {
file, err := os.Create("/var/run/certman.pid")
@@ -284,31 +293,15 @@ func MakeCredential(username, groupname string) (*syscall.Credential, error) {
return &syscall.Credential{Uid: uid, Gid: gid}, nil
}
// CertsDir returns the on-disk directory where a domain's encrypted and
// decrypted certificate files live, along with the client's sync-state
// `hash` marker. A per-domain data_root override (domainConfig.Certificates.DataRoot)
// is used as-is; otherwise the path is <config.data_root>/certificates/<domain>.
// This is the single source of truth for that convention — callers should
// not assemble the path themselves.
func CertsDir(config *AppConfig, domainConfig *DomainConfig, domain string) string {
if domainConfig != nil && domainConfig.Certificates.DataRoot != "" {
return domainConfig.Certificates.DataRoot
}
if config == nil {
return filepath.Join("certificates", domain)
}
return filepath.Join(config.Certificates.DataRoot, "certificates", domain)
}
func EffectiveDataRoot(config *AppConfig, domainConfig *DomainConfig) string {
// EffectiveDataRoot resolves the data root for a domain. The per-domain
// override takes precedence; otherwise the app-level data root is used; if
// both are empty, the current working directory is used.
func EffectiveDataRoot(config *AppConfig, domainDataRoot string) string {
if config == nil {
return ""
}
if domainConfig == nil {
return ""
}
if domainConfig.Certificates.DataRoot == "" {
if domainDataRoot == "" {
if config.Certificates.DataRoot == "" {
workDir, err := os.Getwd()
if err != nil {
@@ -318,7 +311,7 @@ func EffectiveDataRoot(config *AppConfig, domainConfig *DomainConfig) string {
}
return config.Certificates.DataRoot
}
return domainConfig.Certificates.DataRoot
return domainDataRoot
}
var fqdnRegex = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$`)

View File

@@ -19,6 +19,7 @@ import (
"git.nevets.tech/Steven/certman/common"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/providers/dns/cloudflare"
"github.com/go-acme/lego/v4/registration"
@@ -58,6 +59,11 @@ type ACMEManager struct {
Client *lego.Client
User *fileUser
// cached DNS-01 provider so we can re-bind it with per-domain recursive nameservers
cfProvider *cloudflare.DNSProvider
// snapshot of /etc/resolv.conf nameservers taken at manager init
defaultNameservers []string
// root dirs
dataRoot string // e.g. /var/local/certman
accountRoot string // e.g. /var/local/certman/accounts
@@ -143,7 +149,10 @@ func NewACMEManager(config *common.AppConfig) (*ACMEManager, error) {
return nil, fmt.Errorf("cloudflare dns provider: %w", err)
}
if err := client.Challenge.SetDNS01Provider(cfProvider); err != nil {
mgr.cfProvider = cfProvider
mgr.defaultNameservers = dns01.ParseNameservers(readResolvConfNameservers("/etc/resolv.conf"))
if err = client.Challenge.SetDNS01Provider(cfProvider, dns01.AddRecursiveNameservers(mgr.defaultNameservers)); err != nil {
return nil, fmt.Errorf("set dns-01 provider: %w", err)
}
@@ -159,7 +168,7 @@ func NewACMEManager(config *common.AppConfig) (*ACMEManager, error) {
return nil, fmt.Errorf("acme registration: %w", err)
}
mgr.User.Registration = reg
if err := saveACMEUser(mgr.accountRoot, mgr.User); err != nil {
if err = saveACMEUser(mgr.accountRoot, mgr.User); err != nil {
return nil, fmt.Errorf("save acme User registration: %w", err)
}
}
@@ -168,7 +177,9 @@ func NewACMEManager(config *common.AppConfig) (*ACMEManager, error) {
}
// ObtainForDomain obtains a new cert for a configured domain and saves it to disk.
func (m *ACMEManager) ObtainForDomain(domainKey string, config *common.AppConfig, domainConfig *common.DomainConfig) (*certificate.Resource, error) {
func (m *ACMEManager) ObtainForDomain(config *common.AppConfig, domainConfig *common.ServerDomainConfig) (*certificate.Resource, error) {
domainKey := domainConfig.Domain.DomainName
rcfg, err := buildDomainRuntimeConfig(config, domainConfig)
if err != nil {
return nil, err
@@ -187,6 +198,10 @@ func (m *ACMEManager) ObtainForDomain(domainKey string, config *common.AppConfig
m.MU.Lock()
defer m.MU.Unlock()
if err := m.applyDNS01ForDomain(domainConfig); err != nil {
return nil, fmt.Errorf("apply dns-01 nameservers for %q: %w", domainKey, err)
}
res, err := m.Client.Certificate.Obtain(req)
if err != nil {
return nil, fmt.Errorf("obtain %q: %w", domainKey, err)
@@ -200,7 +215,9 @@ func (m *ACMEManager) ObtainForDomain(domainKey string, config *common.AppConfig
}
// RenewForDomain renews an existing stored cert for a domain key.
func (m *ACMEManager) RenewForDomain(domainKey string) (*certificate.Resource, error) {
func (m *ACMEManager) RenewForDomain(domainConfig *common.ServerDomainConfig) (*certificate.Resource, error) {
domainKey := domainConfig.Domain.DomainName
m.MU.Lock()
defer m.MU.Unlock()
@@ -209,6 +226,10 @@ func (m *ACMEManager) RenewForDomain(domainKey string) (*certificate.Resource, e
return nil, fmt.Errorf("load stored resource for %q: %w", domainKey, err)
}
if err := m.applyDNS01ForDomain(domainConfig); err != nil {
return nil, fmt.Errorf("apply dns-01 nameservers for %q: %w", domainKey, err)
}
// RenewWithOptions is preferred in newer lego versions.
renewed, err := m.Client.Certificate.RenewWithOptions(*existing, &certificate.RenewOptions{
Bundle: true,
@@ -232,17 +253,55 @@ func (m *ACMEManager) GetCertPaths(domainKey string) (certPEM, keyPEM string) {
filepath.Join(dir, base+".key")
}
// applyDNS01ForDomain re-binds the lego DNS-01 provider with recursive nameservers
// appropriate for this domain. When ServerDomainCfg.DNSServer is empty or "default", the
// resolv.conf snapshot taken at NewACMEManager time is used; otherwise the configured
// server is used. Caller must hold m.MU.
func (m *ACMEManager) applyDNS01ForDomain(domainConfig *common.ServerDomainConfig) error {
ns := m.defaultNameservers
cfgDNS := strings.TrimSpace(domainConfig.Domain.DNSServer)
if cfgDNS != "" && !strings.EqualFold(cfgDNS, "default") {
ns = dns01.ParseNameservers([]string{cfgDNS})
}
return m.Client.Challenge.SetDNS01Provider(m.cfProvider, dns01.AddRecursiveNameservers(ns))
}
// readResolvConfNameservers parses `nameserver` lines from a resolv.conf-style file.
// Returns nil on any error so the caller falls through to lego's own defaults.
func readResolvConfNameservers(path string) []string {
data, err := os.ReadFile(path)
if err != nil {
return nil
}
var servers []string
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
continue
}
rest, ok := strings.CutPrefix(line, "nameserver")
if !ok {
continue
}
ns := strings.TrimSpace(rest)
if ns != "" {
servers = append(servers, ns)
}
}
return servers
}
// ---------------------------------------------
// Domain runtime config assembly
// ---------------------------------------------
func buildDomainRuntimeConfig(config *common.AppConfig, domainConfig *common.DomainConfig) (*DomainRuntimeConfig, error) {
func buildDomainRuntimeConfig(config *common.AppConfig, domainConfig *common.ServerDomainConfig) (*DomainRuntimeConfig, error) {
domainName := domainConfig.Domain.DomainName
email := config.Certificates.Email
// domain override data_root can be blank -> main fallback
dataRoot := common.EffectiveDataRoot(config, domainConfig)
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
caDirURL := config.Certificates.CADirURL
@@ -270,6 +329,7 @@ func buildDomainRuntimeConfig(config *common.AppConfig, domainConfig *common.Dom
// If a subdomain entry looks like a full FQDN already, it is used as-is.
func buildDomainList(baseDomain string, subs []string) []string {
seen := map[string]struct{}{}
out := make([]string, 0, len(subs)+1)
add := func(d string) {
d = strings.TrimSpace(strings.ToLower(d))
if d == "" {
@@ -279,6 +339,7 @@ func buildDomainList(baseDomain string, subs []string) []string {
return
}
seen[d] = struct{}{}
out = append(out, d)
}
add(baseDomain)
@@ -310,10 +371,6 @@ func buildDomainList(baseDomain string, subs []string) []string {
add(s + "." + baseDomain)
}
out := make([]string, 0, len(seen))
for d := range seen {
out = append(out, d)
}
return out
}

View File

@@ -0,0 +1,15 @@
package server
import (
"fmt"
"slices"
"testing"
)
func TestBuildDomainList(t *testing.T) {
domains := buildDomainList("example.com", []string{"*", "dev"})
fmt.Printf("domains: %v\n", domains)
if slices.Compare(domains, []string{"example.com", "*.example.com", "dev.example.com"}) != 0 {
t.Errorf("domains not equal")
}
}

View File

@@ -2,7 +2,6 @@ package server
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
@@ -15,142 +14,105 @@ import (
"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)
func AddAndPushCerts(ws *common.GitWorkspace, dataRoot, repoSuffix string, config *common.AppConfig) error {
certFiles, err := os.ReadDir(dataRoot)
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 certsDir 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, certsDir string, config *common.AppConfig) error {
if err := stageCerts(ws, certsDir); err != nil {
fmt.Printf("Error reading from directory: %v\n", err)
return err
}
if err := stageFile(ws, serverIDFile, []byte(config.App.UUID)); err != nil {
return fmt.Errorf("stage SERVER_ID: %w", 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 {
return fmt.Errorf("get worktree status: %w", err)
fmt.Printf("Error getting repo status: %v\n", err)
return err
}
if status.IsClean() {
fmt.Printf("Repository is clean, skipping commit...\n")
return nil
}
sig := &object.Signature{
fmt.Println("Work Tree Status:\n" + status.String())
signature := &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.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: &http.BasicAuth{
Username: config.Git.Username,
Password: config.Git.APIToken,
},
Auth: creds,
Force: true,
RemoteName: "origin",
RefSpecs: []gitconf.RefSpec{gitconf.RefSpec("refs/heads/" + pushBranch + ":refs/heads/" + pushBranch)},
RefSpecs: []gitconf.RefSpec{
"refs/heads/master:refs/heads/master",
},
})
if err != nil {
return fmt.Errorf("push %s: %w", ws.URL, err)
fmt.Printf("Error pushing to origin: %v\n", err)
return err
}
return nil
}
// stageCerts copies every *.crpt file in certsDir into the workspace
// filesystem and adds it to the work tree.
func stageCerts(ws *common.GitWorkspace, certsDir string) error {
entries, err := os.ReadDir(certsDir)
if err != nil {
return fmt.Errorf("read %s: %w", certsDir, err)
}
for _, entry := range entries {
name := entry.Name()
if !strings.HasSuffix(name, ".crpt") {
continue
}
body, err := os.ReadFile(filepath.Join(certsDir, 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
}
fmt.Println("Successfully uploaded to " + config.Git.Server + "/" + config.Git.OrgName + "/" + ws.Domain + repoSuffix + ".git")
// 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
}