Compare commits
6 Commits
v1.1.1-bet
...
v1.1.7-bet
| Author | SHA1 | Date | |
|---|---|---|---|
| 0a78b70821 | |||
| c01195643a | |||
| 6aacbfbb71 | |||
| 727de333b4 | |||
| f4e7a37fa6 | |||
| 18f414e474 |
@@ -44,7 +44,7 @@ jobs:
|
|||||||
run: echo "COMMIT_MSG=$(git log -1 --pretty=%s)" >> $GITHUB_ENV
|
run: echo "COMMIT_MSG=$(git log -1 --pretty=%s)" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: make build
|
run: make client server
|
||||||
|
|
||||||
- name: Upload artifact
|
- name: Upload artifact
|
||||||
uses: https://github.com/actions/upload-artifact@v3
|
uses: https://github.com/actions/upload-artifact@v3
|
||||||
|
|||||||
31
Makefile
31
Makefile
@@ -1,12 +1,13 @@
|
|||||||
VERSION := 1.1.1-beta
|
VERSION := 1.1.7-beta
|
||||||
BUILD := $(shell git rev-parse --short HEAD)
|
BUILD := $(shell git rev-parse --short HEAD)
|
||||||
|
UPDATE_SRC := "https://git.nevets.tech/api/v1/repos/Steven/certman/releases"
|
||||||
|
|
||||||
GO := go
|
GO := go
|
||||||
|
|
||||||
BUILD_FLAGS := -buildmode=pie -trimpath
|
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:
|
proto:
|
||||||
@protoc --go_out=./proto --go-grpc_out=./proto proto/hook.proto
|
@protoc --go_out=./proto --go-grpc_out=./proto proto/hook.proto
|
||||||
@@ -14,21 +15,25 @@ 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
|
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"
|
@echo "All binaries successfully built"
|
||||||
|
|
||||||
debug: proto
|
debug: proto
|
||||||
@@ -38,3 +43,13 @@ debug: proto
|
|||||||
stage: build
|
stage: build
|
||||||
@sudo cp ./certman /srv/vm-passthru/certman
|
@sudo cp ./certman /srv/vm-passthru/certman
|
||||||
@ssh steven@192.168.122.44 updateCertman.sh
|
@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)"
|
||||||
12
README.md
12
README.md
@@ -21,3 +21,15 @@ 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
|
||||||
|
|
||||||
|
# Coding Conventions
|
||||||
|
- Keep Config() calls in app space
|
||||||
@@ -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)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package shared
|
package app
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
package client
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"path/filepath"
|
"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-billy/v5/memfs"
|
||||||
"github.com/go-git/go-git/v5/storage/memory"
|
"github.com/go-git/go-git/v5/storage/memory"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -43,34 +43,37 @@ 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 {
|
||||||
|
config := app.Config()
|
||||||
|
domainConfig, exists := app.ClientDomainStore().Get(domain)
|
||||||
|
if !exists {
|
||||||
|
return app.ErrConfigNotFound
|
||||||
|
}
|
||||||
|
|
||||||
gitWorkspace := &common.GitWorkspace{
|
gitWorkspace := &common.GitWorkspace{
|
||||||
Domain: domain,
|
Domain: domain,
|
||||||
|
URL: config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git",
|
||||||
Storage: memory.NewStorage(),
|
Storage: memory.NewStorage(),
|
||||||
FS: memfs.New(),
|
FS: memfs.New(),
|
||||||
}
|
}
|
||||||
config := shared.Config()
|
if err := client.PullCerts(config, gitWorkspace); err != nil {
|
||||||
domainConfig, exists := shared.DomainStore().Get(domain)
|
|
||||||
if !exists {
|
|
||||||
return shared.ErrConfigNotFound
|
|
||||||
}
|
|
||||||
if err := client.PullCerts(config, domainConfig, gitWorkspace); err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
certsDir := common.CertsDir(config, domainConfig)
|
certsDir := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
|
||||||
return client.DecryptAndWriteCertificates(certsDir, config, domainConfig, gitWorkspace)
|
return client.DecryptAndWriteCertificates(certsDir, config, domainConfig, gitWorkspace)
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateLinks(domain string) error {
|
func updateLinks(domain string) error {
|
||||||
domainConfig, exists := shared.DomainStore().Get(domain)
|
domainConfig, exists := app.ClientDomainStore().Get(domain)
|
||||||
if !exists {
|
if !exists {
|
||||||
return fmt.Errorf("domain %s does not exist", domain)
|
return fmt.Errorf("domain %s does not exist", domain)
|
||||||
}
|
}
|
||||||
|
|
||||||
certsDir := shared.DomainCertsDirWConf(domain, domainConfig)
|
effectiveDataRoot := common.EffectiveDataRoot(app.Config(), domainConfig.Certificates.DataRoot)
|
||||||
|
certsDir := filepath.Join(effectiveDataRoot, "certificates", domain)
|
||||||
|
|
||||||
certLinks := domainConfig.Certificates.CertSymlinks
|
certLinks := domainConfig.Certificates.CertSymlinks
|
||||||
for _, certLink := range certLinks {
|
for _, certLink := range certLinks {
|
||||||
@@ -83,7 +86,7 @@ func updateLinks(domain string) error {
|
|||||||
|
|
||||||
keyLinks := domainConfig.Certificates.KeySymlinks
|
keyLinks := domainConfig.Certificates.KeySymlinks
|
||||||
for _, keyLink := range keyLinks {
|
for _, keyLink := range keyLinks {
|
||||||
err := common.LinkFile(filepath.Join(certsDir, domain+".crt"), keyLink, domain, ".key")
|
err := common.LinkFile(filepath.Join(certsDir, domain+".key"), keyLink, domain, ".key")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error linking cert %s to %s: %v", keyLink, domain, err)
|
fmt.Printf("Error linking cert %s to %s: %v", keyLink, domain, err)
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
package client
|
|
||||||
@@ -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{})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package client
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -7,9 +7,9 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"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-billy/v5/memfs"
|
||||||
"github.com/go-git/go-git/v5/storage/memory"
|
"github.com/go-git/go-git/v5/storage/memory"
|
||||||
)
|
)
|
||||||
@@ -18,7 +18,7 @@ type Daemon struct{}
|
|||||||
|
|
||||||
func (d *Daemon) Init() {
|
func (d *Daemon) Init() {
|
||||||
fmt.Println("Starting CertManager in client mode...")
|
fmt.Println("Starting CertManager in client mode...")
|
||||||
err := appShared.LoadDomainConfigs()
|
err := app.LoadClientDomainConfigs()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error loading domain configs: %v", err)
|
log.Fatalf("Error loading domain configs: %v", err)
|
||||||
}
|
}
|
||||||
@@ -30,8 +30,8 @@ func (d *Daemon) Tick() {
|
|||||||
fmt.Println("tick!")
|
fmt.Println("tick!")
|
||||||
|
|
||||||
// Get local copy of configs
|
// Get local copy of configs
|
||||||
config := appShared.Config()
|
config := app.Config()
|
||||||
localDomainConfigs := appShared.DomainStore().Snapshot()
|
localDomainConfigs := app.ClientDomainStore().Snapshot()
|
||||||
|
|
||||||
// Loop over all domain configs (domains)
|
// Loop over all domain configs (domains)
|
||||||
for domainStr, domainConfig := range localDomainConfigs {
|
for domainStr, domainConfig := range localDomainConfigs {
|
||||||
@@ -40,51 +40,22 @@ func (d *Daemon) Tick() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip domains with up-to-date commit hashes
|
|
||||||
// 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
|
|
||||||
if repoExists {
|
|
||||||
var dataRoot string
|
|
||||||
if domainConfig.Certificates.DataRoot == "" {
|
|
||||||
config.Certificates.DataRoot = domainStr
|
|
||||||
} else {
|
|
||||||
dataRoot = domainConfig.Certificates.DataRoot
|
|
||||||
}
|
|
||||||
localHash, err := client.LocalCommitHash(domainStr, dataRoot)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("No local commit hash found for domain %s\n", domainStr)
|
|
||||||
}
|
|
||||||
gitSource, err := common.StrToGitSource(appShared.Config().Git.Host)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error getting git source for domain %s: %v\n", domainStr, err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
remoteHash, err := client.RemoteCommitHash(domainStr, gitSource, config, domainConfig)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error getting remote commit hash for domain %s: %v\n", domainStr, err)
|
|
||||||
}
|
|
||||||
// If both hashes are blank (errored), break
|
|
||||||
// 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)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
gitWorkspace := &common.GitWorkspace{
|
gitWorkspace := &common.GitWorkspace{
|
||||||
|
Domain: domainStr,
|
||||||
|
URL: app.Config().Git.Server + "/" + config.Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git",
|
||||||
Storage: memory.NewStorage(),
|
Storage: memory.NewStorage(),
|
||||||
FS: memfs.New(),
|
FS: memfs.New(),
|
||||||
}
|
}
|
||||||
// Ex: https://git.example.com/Org/Repo-suffix.git
|
// Ex: https://git.example.com/Org/Repo-suffix.git
|
||||||
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
|
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
|
||||||
repoUrl := appShared.Config().Git.Server + "/" + config.Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git"
|
err := gitWorkspace.CloneRepo(common.Client, config)
|
||||||
err := common.CloneRepo(repoUrl, gitWorkspace, common.Client, config)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error cloning domain repo %s: %v\n", domainStr, err)
|
fmt.Printf("Error cloning domain repo %s: %v\n", domainStr, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
certsDir := appShared.DomainCertsDirWConf(domainStr, domainConfig)
|
effectiveDataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
|
||||||
|
certsDir := filepath.Join(effectiveDataRoot, "certificates", domainStr)
|
||||||
|
|
||||||
// Get files in repo
|
// Get files in repo
|
||||||
fileInfos, err := gitWorkspace.FS.ReadDir("/")
|
fileInfos, err := gitWorkspace.FS.ReadDir("/")
|
||||||
@@ -125,7 +96,8 @@ func (d *Daemon) Tick() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
err = common.WriteCommitHash(headRef.Hash().String(), config, domainConfig)
|
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
|
||||||
|
err = client.WriteCommitHash(headRef.Hash().String(), dataRoot)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error writing commit hash: %v\n", err)
|
fmt.Printf("Error writing commit hash: %v\n", err)
|
||||||
continue
|
continue
|
||||||
@@ -156,7 +128,7 @@ func (d *Daemon) Tick() {
|
|||||||
func (d *Daemon) Reload() {
|
func (d *Daemon) Reload() {
|
||||||
fmt.Println("Reloading configs...")
|
fmt.Println("Reloading configs...")
|
||||||
|
|
||||||
err := appShared.LoadDomainConfigs()
|
err := app.LoadClientDomainConfigs()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error loading domain configs: %v\n", err)
|
fmt.Printf("Error loading domain configs: %v\n", err)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,38 +1,15 @@
|
|||||||
package client
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.nevets.tech/Keys/certman/app/shared"
|
pb "git.nevets.tech/Steven/certman/proto/v1"
|
||||||
pb "git.nevets.tech/Keys/certman/proto/v1"
|
|
||||||
"google.golang.org/grpc"
|
|
||||||
"google.golang.org/grpc/credentials/insecure"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func SendHook(domain string) {
|
// SendHook is currently a no-op pending hook config modeling on ClientDomainConfig.
|
||||||
conn, err := grpc.NewClient(
|
func SendHook(domain string) {}
|
||||||
"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 := shared.PostPullHooks(domain)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error getting hooks: %v\n", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, hook := range hooks {
|
|
||||||
sendHook(client, hook)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func sendHook(client pb.HookServiceClient, hook *pb.Hook) {
|
func sendHook(client pb.HookServiceClient, hook *pb.Hook) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|||||||
@@ -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,17 @@ 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.UpdateCmd)
|
||||||
|
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)
|
||||||
@@ -1,21 +1,25 @@
|
|||||||
package shared
|
package app
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"os/user"
|
"os/user"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"git.nevets.tech/Keys/certman/common"
|
"git.nevets.tech/Steven/certman/common"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
VersionCmd = basicCmd("version", "Show version", versionCmd)
|
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)
|
DevCmd = basicCmd("dev", "Dev Function", devCmd)
|
||||||
|
|
||||||
domainCertDir string
|
domainCertDir string
|
||||||
@@ -55,17 +59,17 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func devCmd(cmd *cobra.Command, args []string) {
|
func devCmd(cmd *cobra.Command, args []string) {
|
||||||
testDomain := "lunamc.org"
|
//testDomain := "lunamc.org"
|
||||||
err := LoadConfig()
|
//err := LoadConfig()
|
||||||
if err != nil {
|
//if err != nil {
|
||||||
log.Fatalf("Error loading configuration: %v\n", err)
|
// log.Fatalf("Error loading configuration: %v\n", err)
|
||||||
}
|
//}
|
||||||
err = LoadDomainConfigs()
|
//err = LoadDomainConfigs()
|
||||||
if err != nil {
|
//if err != nil {
|
||||||
log.Fatalf("Error loading configs: %v\n", err)
|
// log.Fatalf("Error loading configs: %v\n", err)
|
||||||
}
|
//}
|
||||||
|
//
|
||||||
fmt.Println(testDomain)
|
//fmt.Println(testDomain)
|
||||||
}
|
}
|
||||||
|
|
||||||
func versionCmd(cmd *cobra.Command, args []string) {
|
func versionCmd(cmd *cobra.Command, args []string) {
|
||||||
@@ -74,7 +78,7 @@ 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()
|
key, err := common.GenerateKey()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("%v", err)
|
log.Fatalf("%v", err)
|
||||||
@@ -82,6 +86,41 @@ func newKeyCmd(cmd *cobra.Command, args []string) {
|
|||||||
fmt.Printf(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 {
|
func newDomainCmd(domain, domainDir string, dirOverridden bool) error {
|
||||||
//TODO add config option for "overridden dir"
|
//TODO add config option for "overridden dir"
|
||||||
if !common.IsValidFQDN(domain) {
|
if !common.IsValidFQDN(domain) {
|
||||||
@@ -160,15 +199,8 @@ func installCmd(isThin bool, mode string) error {
|
|||||||
return fmt.Errorf("error creating group: %v: output %s", err, output)
|
return fmt.Errorf("error creating group: %v: output %s", err, output)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
certmanUser, err := user.Lookup("certman")
|
//TODO chmod after chown
|
||||||
if err != nil {
|
uid, gid, err := GetUserIds("certman")
|
||||||
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))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -187,5 +219,12 @@ func installCmd(isThin bool, mode string) error {
|
|||||||
} else {
|
} else {
|
||||||
CreateConfig(mode)
|
CreateConfig(mode)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//TODO move executable to /usr/bin
|
||||||
|
//execPath, err := os.Executable()
|
||||||
|
//if err != nil {
|
||||||
|
// return err
|
||||||
|
//}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package shared
|
package app
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
@@ -9,8 +9,7 @@ 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"
|
|
||||||
"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"
|
||||||
@@ -21,42 +20,46 @@ var (
|
|||||||
ErrConfigNotFound = errors.New("config file not found")
|
ErrConfigNotFound = errors.New("config file not found")
|
||||||
)
|
)
|
||||||
|
|
||||||
type DomainConfigStore struct {
|
// ---------------------------------------------------------------------------
|
||||||
|
// Generic domain config store
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
type DomainConfigStore[T any] struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
configs map[string]*common.DomainConfig
|
configs map[string]*T
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDomainConfigStore() *DomainConfigStore {
|
func NewDomainConfigStore[T any]() *DomainConfigStore[T] {
|
||||||
return &DomainConfigStore{
|
return &DomainConfigStore[T]{
|
||||||
configs: make(map[string]*common.DomainConfig),
|
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()
|
s.mu.RLock()
|
||||||
defer s.mu.RUnlock()
|
defer s.mu.RUnlock()
|
||||||
v, ok := s.configs[domain]
|
v, ok := s.configs[domain]
|
||||||
return v, ok
|
return v, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *DomainConfigStore) Set(domain string, v *common.DomainConfig) {
|
func (s *DomainConfigStore[T]) Set(domain string, v *T) {
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
s.configs[domain] = v
|
s.configs[domain] = v
|
||||||
}
|
}
|
||||||
|
|
||||||
// Swap atomically replaces the entire config map (used during reload).
|
// 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()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
s.configs = newConfigs
|
s.configs = newConfigs
|
||||||
}
|
}
|
||||||
|
|
||||||
// Snapshot returns a shallow copy safe to iterate without holding the lock.
|
// 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()
|
s.mu.RLock()
|
||||||
defer s.mu.RUnlock()
|
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 {
|
for k, v := range s.configs {
|
||||||
snap[k] = v
|
snap[k] = v
|
||||||
}
|
}
|
||||||
@@ -70,7 +73,8 @@ func (s *DomainConfigStore) Snapshot() map[string]*common.DomainConfig {
|
|||||||
var (
|
var (
|
||||||
config *common.AppConfig
|
config *common.AppConfig
|
||||||
configMu sync.RWMutex
|
configMu sync.RWMutex
|
||||||
domainStore = NewDomainConfigStore()
|
serverDomainStore = NewDomainConfigStore[common.ServerDomainConfig]()
|
||||||
|
clientDomainStore = NewDomainConfigStore[common.ClientDomainConfig]()
|
||||||
)
|
)
|
||||||
|
|
||||||
func Config() *common.AppConfig {
|
func Config() *common.AppConfig {
|
||||||
@@ -79,10 +83,12 @@ func Config() *common.AppConfig {
|
|||||||
return config
|
return config
|
||||||
}
|
}
|
||||||
|
|
||||||
func DomainStore() *DomainConfigStore {
|
func ServerDomainStore() *DomainConfigStore[common.ServerDomainConfig] {
|
||||||
domainStore.mu.RLock()
|
return serverDomainStore
|
||||||
defer domainStore.mu.RUnlock()
|
}
|
||||||
return domainStore
|
|
||||||
|
func ClientDomainStore() *DomainConfigStore[common.ClientDomainConfig] {
|
||||||
|
return clientDomainStore
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -112,15 +118,16 @@ func LoadConfig() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoadDomainConfigs reads every .conf file in the domains directory.
|
// loadDomainConfigs walks /etc/certman/domains and unmarshals every .conf file
|
||||||
func LoadDomainConfigs() error {
|
// into T, keyed by domain.domain_name.
|
||||||
|
func loadDomainConfigs[T any]() (map[string]*T, error) {
|
||||||
dir := "/etc/certman/domains/"
|
dir := "/etc/certman/domains/"
|
||||||
entries, err := os.ReadDir(dir)
|
entries, err := os.ReadDir(dir)
|
||||||
if err != nil {
|
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 {
|
for _, entry := range entries {
|
||||||
if entry.IsDir() || filepath.Ext(entry.Name()) != ".conf" {
|
if entry.IsDir() || filepath.Ext(entry.Name()) != ".conf" {
|
||||||
@@ -133,26 +140,47 @@ func LoadDomainConfigs() error {
|
|||||||
v.SetConfigType("toml")
|
v.SetConfigType("toml")
|
||||||
|
|
||||||
if err := v.ReadInConfig(); err != nil {
|
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")
|
domain := v.GetString("domain.domain_name")
|
||||||
if domain == "" {
|
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)
|
fmt.Printf("Duplicate domain in %s, skipping...\n", path)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
cfg := &common.DomainConfig{}
|
cfg := new(T)
|
||||||
if err = v.Unmarshal(cfg); err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,40 +200,44 @@ func WriteConfig(filePath string, config *common.AppConfig) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func WriteDomainConfig(config *common.DomainConfig) error {
|
func writeDomainConfigFile(domainName string, v any) error {
|
||||||
buf, err := toml.Marshal(config)
|
buf, err := toml.Marshal(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("marshaling domain config: %w", err)
|
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 {
|
if err = os.WriteFile(configPath, buf, 0640); err != nil {
|
||||||
return fmt.Errorf("write config file: %w", err)
|
return fmt.Errorf("write config file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SaveDomainConfigs writes every loaded domain config back to disk.
|
func WriteServerDomainConfig(config *common.ServerDomainConfig) error {
|
||||||
func SaveDomainConfigs() error {
|
return writeDomainConfigFile(config.Domain.DomainName, config)
|
||||||
for _, v := range domainStore.Snapshot() {
|
}
|
||||||
err := WriteDomainConfig(v)
|
|
||||||
if err != nil {
|
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 err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// SaveClientDomainConfigs writes every loaded client domain config back to disk.
|
||||||
// Domain Specific Lookups
|
func SaveClientDomainConfigs() error {
|
||||||
// ---------------------------------------------------------------------------
|
for _, v := range clientDomainStore.Snapshot() {
|
||||||
|
if err := WriteClientDomainConfig(v); err != nil {
|
||||||
func PostPullHooks(domain string) ([]*pb.Hook, error) {
|
return err
|
||||||
var hooks []*pb.Hook
|
|
||||||
if err := viper.UnmarshalKey("Hooks.PostPull", hooks); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
return hooks, nil
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
117
app/cryptr/main.go
Normal file
117
app/cryptr/main.go
Normal 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
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package executor
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|||||||
@@ -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"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package executor
|
package main
|
||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +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-billy/v5/memfs"
|
||||||
"github.com/go-git/go-git/v5/storage/memory"
|
"github.com/go-git/go-git/v5/storage/memory"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -27,17 +27,17 @@ var (
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
renewCertSubCmd.Flags().BoolVar(&noPush, "no-push", false, "Don't push certs to repo, renew locally only [server mode only]")
|
renewCertSubCmd.Flags().BoolVar(&noPush, "no-push", false, "Don't push certs to repo, renew locally only [server mode only]")
|
||||||
shared.CertCmd.AddCommand(renewCertSubCmd)
|
app.CertCmd.AddCommand(renewCertSubCmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
func renewCertCmd(domain string, noPush bool) error {
|
func renewCertCmd(domain string, noPush bool) error {
|
||||||
if err := shared.LoadConfig(); err != nil {
|
if err := app.LoadConfig(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := shared.LoadDomainConfigs(); err != nil {
|
if err := app.LoadServerDomainConfigs(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
mgr, err := server.NewACMEManager(shared.Config())
|
mgr, err := server.NewACMEManager(app.Config())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -50,23 +50,23 @@ func renewCertCmd(domain string, noPush bool) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error {
|
func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error {
|
||||||
config := shared.Config()
|
config := app.Config()
|
||||||
domainConfig, exists := shared.DomainStore().Get(domain)
|
domainConfig, exists := app.ServerDomainStore().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)
|
_, err := mgr.RenewForDomain(domainConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// if no existing cert, obtain instead
|
// if no existing cert, obtain instead
|
||||||
_, err = mgr.ObtainForDomain(domain, config, domainConfig)
|
_, err = mgr.ObtainForDomain(config, domainConfig)
|
||||||
if err != nil {
|
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)
|
err = app.WriteServerDomainConfig(domainConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error saving domain config %s: %v", domain, err)
|
return fmt.Errorf("error saving domain config %s: %v", domain, err)
|
||||||
}
|
}
|
||||||
@@ -90,31 +90,31 @@ func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error {
|
|||||||
FS: memfs.New(),
|
FS: memfs.New(),
|
||||||
}
|
}
|
||||||
|
|
||||||
var repoUrl string
|
|
||||||
if !domainConfig.Internal.RepoExists {
|
if !domainConfig.Internal.RepoExists {
|
||||||
repoUrl = common.CreateGiteaRepo(domain, giteaClient, config, domainConfig)
|
gitWorkspace.URL = common.CreateGiteaRepo(domain, giteaClient, config, domainConfig)
|
||||||
if repoUrl == "" {
|
if gitWorkspace.URL == "" {
|
||||||
return fmt.Errorf("error creating Gitea repo for domain %s", domain)
|
return fmt.Errorf("error creating Gitea repo for domain %s", domain)
|
||||||
}
|
}
|
||||||
domainConfig.Internal.RepoExists = true
|
domainConfig.Internal.RepoExists = true
|
||||||
err = shared.WriteDomainConfig(domainConfig)
|
err = app.WriteServerDomainConfig(domainConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error saving domain config %s: %v", domain, err)
|
return fmt.Errorf("error saving domain config %s: %v", domain, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = common.InitRepo(repoUrl, gitWorkspace)
|
err = gitWorkspace.InitRepo()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error initializing repo for domain %s: %v", domain, err)
|
return fmt.Errorf("error initializing repo for domain %s: %v", domain, err)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
repoUrl = config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git"
|
gitWorkspace.URL = config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git"
|
||||||
err = common.CloneRepo(repoUrl, gitWorkspace, common.Server, config)
|
err = gitWorkspace.CloneRepo(common.Server, config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error cloning repo for domain %s: %v", domain, err)
|
return fmt.Errorf("error cloning repo for domain %s: %v", domain, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err = common.AddAndPushCerts(domain, gitWorkspace, config, domainConfig)
|
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
|
||||||
|
err = server.AddAndPushCerts(gitWorkspace, dataRoot, domainConfig.Repo.RepoSuffix, config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error pushing certificates for domain %s: %v", domain, err)
|
return fmt.Errorf("error pushing certificates for domain %s: %v", domain, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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{})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1,15 +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-billy/v5/memfs"
|
||||||
"github.com/go-git/go-git/v5/storage/memory"
|
"github.com/go-git/go-git/v5/storage/memory"
|
||||||
)
|
)
|
||||||
@@ -36,7 +38,7 @@ func (d *Daemon) loadACMEManager() error {
|
|||||||
|
|
||||||
func (d *Daemon) Init() {
|
func (d *Daemon) Init() {
|
||||||
fmt.Println("Starting CertManager in server mode...")
|
fmt.Println("Starting CertManager in server mode...")
|
||||||
err := appShared.LoadDomainConfigs()
|
err := appShared.LoadServerDomainConfigs()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error loading domain configs: %v", err)
|
log.Fatalf("Error loading domain configs: %v", err)
|
||||||
}
|
}
|
||||||
@@ -57,29 +59,34 @@ func (d *Daemon) Tick() {
|
|||||||
now := time.Now().UTC()
|
now := time.Now().UTC()
|
||||||
|
|
||||||
config := appShared.Config()
|
config := appShared.Config()
|
||||||
localDomainConfigs := appShared.DomainStore().Snapshot()
|
localDomainConfigs := appShared.ServerDomainStore().Snapshot()
|
||||||
|
|
||||||
for domainStr, domainConfig := range localDomainConfigs {
|
for domainStr, domainConfig := range localDomainConfigs {
|
||||||
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) {
|
||||||
//TODO extra check if certificate expiry (create cache?)
|
//TODO extra check if certificate expiry (create cache?)
|
||||||
_, err := d.ACMEManager.RenewForDomain(domainStr)
|
_, err := d.ACMEManager.RenewForDomain(domainConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
// if no existing cert, obtain instead
|
// if no existing cert, obtain instead
|
||||||
_, err = d.ACMEManager.ObtainForDomain(domainStr, appShared.Config(), domainConfig)
|
_, err = d.ACMEManager.ObtainForDomain(appShared.Config(), domainConfig)
|
||||||
if err != nil {
|
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
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)
|
err = appShared.WriteServerDomainConfig(domainConfig)
|
||||||
if 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
|
||||||
@@ -106,35 +113,35 @@ func (d *Daemon) Tick() {
|
|||||||
FS: memfs.New(),
|
FS: memfs.New(),
|
||||||
}
|
}
|
||||||
|
|
||||||
var repoUrl string
|
|
||||||
if !domainConfig.Internal.RepoExists {
|
if !domainConfig.Internal.RepoExists {
|
||||||
repoUrl = common.CreateGiteaRepo(domainStr, giteaClient, config, domainConfig)
|
gitWorkspace.URL = common.CreateGiteaRepo(domainStr, giteaClient, config, domainConfig)
|
||||||
if repoUrl == "" {
|
if gitWorkspace.URL == "" {
|
||||||
fmt.Printf("Error creating Gitea repo for domain %s\n", domainStr)
|
fmt.Printf("Error creating Gitea repo for domain %s\n", domainStr)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
domainConfig.Internal.RepoExists = true
|
domainConfig.Internal.RepoExists = true
|
||||||
err = appShared.WriteDomainConfig(domainConfig)
|
err = appShared.WriteServerDomainConfig(domainConfig)
|
||||||
if 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.InitRepo(repoUrl, gitWorkspace)
|
err = gitWorkspace.InitRepo()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error initializing repo for domain %s: %v\n", domainStr, err)
|
fmt.Printf("Error initializing repo for domain %s: %v\n", domainStr, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
repoUrl = appShared.Config().Git.Server + "/" + appShared.Config().Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git"
|
gitWorkspace.URL = appShared.Config().Git.Server + "/" + appShared.Config().Git.OrgName + "/" + domainStr + domainConfig.Repo.RepoSuffix + ".git"
|
||||||
err = common.CloneRepo(repoUrl, gitWorkspace, common.Server, config)
|
err = gitWorkspace.CloneRepo(common.Server, config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error cloning repo for domain %s: %v\n", domainStr, err)
|
fmt.Printf("Error cloning repo for domain %s: %v\n", domainStr, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err = common.AddAndPushCerts(domainStr, gitWorkspace, config, domainConfig)
|
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
|
||||||
|
err = server.AddAndPushCerts(gitWorkspace, dataRoot, domainConfig.Repo.RepoSuffix, config)
|
||||||
if err != nil {
|
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
|
||||||
@@ -142,14 +149,14 @@ func (d *Daemon) Tick() {
|
|||||||
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)
|
fmt.Printf("Error saving domain configs: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Daemon) Reload() {
|
func (d *Daemon) Reload() {
|
||||||
fmt.Println("Reloading configs...")
|
fmt.Println("Reloading configs...")
|
||||||
err := appShared.LoadDomainConfigs()
|
err := appShared.LoadServerDomainConfigs()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error loading domain configs: %v\n", err)
|
fmt.Printf("Error loading domain configs: %v\n", err)
|
||||||
|
|||||||
38
app/server/main.go
Normal file
38
app/server/main.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"git.nevets.tech/Steven/certman/app"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
rootCmd := &cobra.Command{
|
||||||
|
Use: "certman",
|
||||||
|
Short: "CertMan",
|
||||||
|
Long: "Certificate Manager",
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
return cmd.Help()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
rootCmd.AddCommand(app.DaemonCmd)
|
||||||
|
|
||||||
|
if err := rootCmd.Execute(); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
package server
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
package shared
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
package shared
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
"git.nevets.tech/Keys/certman/common"
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
)
|
|
||||||
|
|
||||||
func createFile(fileName string, filePermission os.FileMode, data []byte) {
|
|
||||||
fileInfo, err := os.Stat(fileName)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
file, err := os.Create(fileName)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error creating configuration file: ", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
_, err = file.Write(data)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error writing to file: ", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
err = file.Chmod(filePermission)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error changing file permission: ", err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
fmt.Println("Error opening configuration file: ", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if fileInfo.Size() == 0 {
|
|
||||||
file, err := os.Create(fileName)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error creating configuration file: ", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
_, err = file.Write(data)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error writing to file:", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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 {
|
|
||||||
return &cobra.Command{
|
|
||||||
Use: use,
|
|
||||||
Short: short,
|
|
||||||
Run: commandFunc,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
130
app/util.go
Normal file
130
app/util.go
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
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 {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
file, err := os.Create(fileName)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error creating configuration file: ", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
_, err = file.Write(data)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error writing to file: ", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
err = file.Chmod(filePermission)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error changing file permission: ", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Println("Error opening configuration file: ", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if fileInfo.Size() == 0 {
|
||||||
|
file, err := os.Create(fileName)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error creating configuration file: ", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
_, err = file.Write(data)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error writing to file:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
Short: short,
|
||||||
|
Run: commandFunc,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,21 +7,20 @@ import (
|
|||||||
"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 {
|
func PullCerts(config *common.AppConfig, gitWorkspace *common.GitWorkspace) error {
|
||||||
// Ex: https://git.example.com/Org/Repo-suffix.git
|
// Ex: https://git.example.com/Org/Repo-suffix.git
|
||||||
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
|
// Clones repo and stores in gitWorkspace, skip if clone fails (doesn't exist?)
|
||||||
repoUrl := config.Git.Server + "/" + config.Git.OrgName + "/" + gitWorkspace.Domain + domainConfig.Repo.RepoSuffix + ".git"
|
err := gitWorkspace.CloneRepo(common.Client, config)
|
||||||
err := common.CloneRepo(repoUrl, gitWorkspace, common.Client, config)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("Error cloning domain repo %s: %v\n", gitWorkspace.Domain, err)
|
return fmt.Errorf("Error cloning domain repo %s: %v\n", gitWorkspace.Domain, err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func DecryptAndWriteCertificates(certsDir string, config *common.AppConfig, domainConfig *common.DomainConfig, gitWorkspace *common.GitWorkspace) error {
|
func DecryptAndWriteCertificates(certsDir string, config *common.AppConfig, domainConfig *common.ClientDomainConfig, gitWorkspace *common.GitWorkspace) error {
|
||||||
// Get files in repo
|
// Get files in repo
|
||||||
fileInfos, err := gitWorkspace.FS.ReadDir("/")
|
fileInfos, err := gitWorkspace.FS.ReadDir("/")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -60,7 +59,8 @@ func DecryptAndWriteCertificates(certsDir string, config *common.AppConfig, doma
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
err = common.WriteCommitHash(headRef.Hash().String(), config, domainConfig)
|
dataRoot := common.EffectiveDataRoot(config, domainConfig.Certificates.DataRoot)
|
||||||
|
err = WriteCommitHash(headRef.Hash().String(), dataRoot)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error writing commit hash: %v\n", err)
|
fmt.Printf("Error writing commit hash: %v\n", err)
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -7,9 +7,26 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"git.nevets.tech/Keys/certman/common"
|
"git.nevets.tech/Steven/certman/common"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func WriteCommitHash(hash, dataRoot string) error {
|
||||||
|
//TODO: unfuck this logic, maybe use a domain struct with a flag for non-standard data root?
|
||||||
|
//var dataRoot string
|
||||||
|
//if domainConfig.Certificates.DataRoot == "" {
|
||||||
|
// dataRoot = filepath.Join(config.Certificates.DataRoot, "certificates", domainConfig.Domain.DomainName)
|
||||||
|
//} else {
|
||||||
|
// dataRoot = domainConfig.Certificates.DataRoot
|
||||||
|
//}
|
||||||
|
|
||||||
|
err := os.WriteFile(filepath.Join(dataRoot, "hash"), []byte(hash), 0644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func LocalCommitHash(domain string, certsDir string) (string, error) {
|
func LocalCommitHash(domain string, certsDir string) (string, error) {
|
||||||
data, err := os.ReadFile(filepath.Join(certsDir, "hash"))
|
data, err := os.ReadFile(filepath.Join(certsDir, "hash"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -22,7 +39,7 @@ func LocalCommitHash(domain string, certsDir string) (string, error) {
|
|||||||
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) {
|
func RemoteCommitHash(domain string, gitSource common.GitSource, config *common.AppConfig, domainConfig *common.ClientDomainConfig) (string, error) {
|
||||||
switch gitSource {
|
switch gitSource {
|
||||||
case common.Gitea:
|
case common.Gitea:
|
||||||
return getRemoteCommitHashGitea(config.Git.OrgName, domain+domainConfig.Repo.RepoSuffix, "master", config)
|
return getRemoteCommitHashGitea(config.Git.OrgName, domain+domainConfig.Repo.RepoSuffix, "master", config)
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
fmt.Println("Hello server")
|
|
||||||
}
|
|
||||||
@@ -36,30 +36,6 @@ type Cloudflare struct {
|
|||||||
CFAPIKey string `mapstructure:"cf_api_key" toml:"cf_api_key"`
|
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 {
|
type Repo struct {
|
||||||
RepoSuffix string `mapstructure:"repo_suffix" toml:"repo_suffix"`
|
RepoSuffix string `mapstructure:"repo_suffix" toml:"repo_suffix"`
|
||||||
}
|
}
|
||||||
@@ -69,3 +45,51 @@ type Internal struct {
|
|||||||
RepoExists bool `mapstructure:"repo_exists" toml:"repo_exists"`
|
RepoExists bool `mapstructure:"repo_exists" toml:"repo_exists"`
|
||||||
Status string `mapstructure:"status" toml:"status"`
|
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"`
|
||||||
|
}
|
||||||
|
|||||||
142
common/git.go
142
common/git.go
@@ -5,15 +5,12 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"code.gitea.io/sdk/gitea"
|
"code.gitea.io/sdk/gitea"
|
||||||
"github.com/go-git/go-billy/v5"
|
"github.com/go-git/go-billy/v5"
|
||||||
"github.com/go-git/go-git/v5"
|
"github.com/go-git/go-git/v5"
|
||||||
gitconf "github.com/go-git/go-git/v5/config"
|
gitconf "github.com/go-git/go-git/v5/config"
|
||||||
"github.com/go-git/go-git/v5/plumbing/object"
|
|
||||||
"github.com/go-git/go-git/v5/plumbing/transport/http"
|
"github.com/go-git/go-git/v5/plumbing/transport/http"
|
||||||
"github.com/go-git/go-git/v5/storage/memory"
|
"github.com/go-git/go-git/v5/storage/memory"
|
||||||
)
|
)
|
||||||
@@ -27,6 +24,7 @@ const (
|
|||||||
|
|
||||||
type GitWorkspace struct {
|
type GitWorkspace struct {
|
||||||
Domain string
|
Domain string
|
||||||
|
URL string
|
||||||
Repo *git.Repository
|
Repo *git.Repository
|
||||||
Storage *memory.Storage
|
Storage *memory.Storage
|
||||||
FS billy.Filesystem
|
FS billy.Filesystem
|
||||||
@@ -98,7 +96,7 @@ func CreateGiteaClient(config *AppConfig) *gitea.Client {
|
|||||||
// return *repo.CloneURL
|
// return *repo.CloneURL
|
||||||
//}
|
//}
|
||||||
|
|
||||||
func CreateGiteaRepo(domain string, giteaClient *gitea.Client, config *AppConfig, domainConfig *DomainConfig) string {
|
func CreateGiteaRepo(domain string, giteaClient *gitea.Client, config *AppConfig, domainConfig *ServerDomainConfig) string {
|
||||||
options := gitea.CreateRepoOption{
|
options := gitea.CreateRepoOption{
|
||||||
Name: domain + domainConfig.Repo.RepoSuffix,
|
Name: domain + domainConfig.Repo.RepoSuffix,
|
||||||
Description: "Certificate storage for " + domain,
|
Description: "Certificate storage for " + domain,
|
||||||
@@ -121,7 +119,7 @@ func CreateGiteaRepo(domain string, giteaClient *gitea.Client, config *AppConfig
|
|||||||
return giteaRepo.CloneURL
|
return giteaRepo.CloneURL
|
||||||
}
|
}
|
||||||
|
|
||||||
func InitRepo(url string, ws *GitWorkspace) error {
|
func (ws *GitWorkspace) InitRepo() error {
|
||||||
var err error
|
var err error
|
||||||
ws.Repo, err = git.Init(ws.Storage, ws.FS)
|
ws.Repo, err = git.Init(ws.Storage, ws.FS)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -131,7 +129,7 @@ func InitRepo(url string, ws *GitWorkspace) error {
|
|||||||
|
|
||||||
_, err = ws.Repo.CreateRemote(&gitconf.RemoteConfig{
|
_, err = ws.Repo.CreateRemote(&gitconf.RemoteConfig{
|
||||||
Name: "origin",
|
Name: "origin",
|
||||||
URLs: []string{url},
|
URLs: []string{ws.URL},
|
||||||
})
|
})
|
||||||
if err != nil && !errors.Is(err, git.ErrRemoteExists) {
|
if err != nil && !errors.Is(err, git.ErrRemoteExists) {
|
||||||
fmt.Printf("Error creating remote origin repo: %v\n", err)
|
fmt.Printf("Error creating remote origin repo: %v\n", err)
|
||||||
@@ -147,13 +145,13 @@ func InitRepo(url string, ws *GitWorkspace) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func CloneRepo(url string, ws *GitWorkspace, certmanMode CertManMode, config *AppConfig) error {
|
func (ws *GitWorkspace) CloneRepo(certmanMode CertManMode, config *AppConfig) error {
|
||||||
creds := &http.BasicAuth{
|
creds := &http.BasicAuth{
|
||||||
Username: config.Git.Username,
|
Username: config.Git.Username,
|
||||||
Password: config.Git.APIToken,
|
Password: config.Git.APIToken,
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
ws.Repo, err = git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: url, Auth: creds})
|
ws.Repo, err = git.Clone(ws.Storage, ws.FS, &git.CloneOptions{URL: ws.URL, Auth: creds})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error cloning repo: %v\n", err)
|
fmt.Printf("Error cloning repo: %v\n", err)
|
||||||
}
|
}
|
||||||
@@ -167,7 +165,7 @@ func CloneRepo(url string, ws *GitWorkspace, certmanMode CertManMode, config *Ap
|
|||||||
serverIdFile, err := ws.FS.OpenFile("/SERVER_ID", os.O_RDWR, 0640)
|
serverIdFile, err := ws.FS.OpenFile("/SERVER_ID", os.O_RDWR, 0640)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
fmt.Printf("server ID file not found for %s, adopting domain\n", url)
|
fmt.Printf("server ID file not found for %s, adopting domain\n", ws.URL)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
@@ -183,129 +181,3 @@ func CloneRepo(url string, ws *GitWorkspace, certmanMode CertManMode, config *Ap
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func AddAndPushCerts(domain string, ws *GitWorkspace, config *AppConfig, domainConfig *DomainConfig) error {
|
|
||||||
var dataRoot string
|
|
||||||
if domainConfig.Certificates.DataRoot == "" {
|
|
||||||
dataRoot = config.Certificates.DataRoot
|
|
||||||
} else {
|
|
||||||
dataRoot = domainConfig.Certificates.DataRoot
|
|
||||||
}
|
|
||||||
certFiles, err := os.ReadDir(dataRoot)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error reading from directory: %v\n", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, entry := range certFiles {
|
|
||||||
if strings.HasSuffix(entry.Name(), ".crpt") {
|
|
||||||
file, err := ws.FS.Create(entry.Name())
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error copying file to memfs: %v\n", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
certFile, err := os.ReadFile(filepath.Join(dataRoot, entry.Name()))
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error reading file to memfs: %v\n", err)
|
|
||||||
file.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = file.Write(certFile)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error writing to memfs: %v\n", err)
|
|
||||||
file.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = ws.WorkTree.Add(file.Name())
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
|
|
||||||
file.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = file.Close()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error closing file: %v\n", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := ws.FS.Create("/SERVER_ID")
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error creating file in memfs: %v\n", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = file.Write([]byte(config.App.UUID))
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error writing to memfs: %v\n", err)
|
|
||||||
file.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = ws.WorkTree.Add(file.Name())
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
|
|
||||||
file.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = file.Close()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error closing file: %v\n", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
status, err := ws.WorkTree.Status()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error getting repo status: %v\n", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if status.IsClean() {
|
|
||||||
fmt.Printf("Repository is clean, skipping commit...\n")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println("Work Tree Status:\n" + status.String())
|
|
||||||
signature := &object.Signature{
|
|
||||||
Name: "Cert Manager",
|
|
||||||
Email: config.Certificates.Email,
|
|
||||||
When: time.Now(),
|
|
||||||
}
|
|
||||||
_, err = ws.WorkTree.Commit("Update "+domain+" @ "+time.Now().Format("Mon Jan _2 2006 15:04:05 MST"), &git.CommitOptions{Author: signature, Committer: signature})
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error committing certs: %v\n", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
creds := &http.BasicAuth{
|
|
||||||
Username: config.Git.Username,
|
|
||||||
Password: config.Git.APIToken,
|
|
||||||
}
|
|
||||||
err = ws.Repo.Push(&git.PushOptions{
|
|
||||||
Auth: creds,
|
|
||||||
Force: true,
|
|
||||||
RemoteName: "origin",
|
|
||||||
RefSpecs: []gitconf.RefSpec{
|
|
||||||
"refs/heads/master:refs/heads/master",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error pushing to origin: %v\n", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println("Successfully uploaded to " + config.Git.Server + "/" + config.Git.OrgName + "/" + domain + domainConfig.Repo.RepoSuffix + ".git")
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func WriteCommitHash(hash string, config *AppConfig, domainConfig *DomainConfig) error {
|
|
||||||
var dataRoot string
|
|
||||||
if domainConfig.Certificates.DataRoot == "" {
|
|
||||||
dataRoot = 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
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -293,15 +293,15 @@ 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 {
|
// 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 {
|
if config == nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
if domainConfig == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
if domainConfig.Certificates.DataRoot == "" {
|
if domainDataRoot == "" {
|
||||||
if config.Certificates.DataRoot == "" {
|
if config.Certificates.DataRoot == "" {
|
||||||
workDir, err := os.Getwd()
|
workDir, err := os.Getwd()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -311,7 +311,7 @@ func CertsDir(config *AppConfig, domainConfig *DomainConfig) string {
|
|||||||
}
|
}
|
||||||
return config.Certificates.DataRoot
|
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,}$`)
|
var fqdnRegex = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$`)
|
||||||
|
|||||||
@@ -16,9 +16,10 @@ 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/challenge/dns01"
|
||||||
"github.com/go-acme/lego/v4/lego"
|
"github.com/go-acme/lego/v4/lego"
|
||||||
"github.com/go-acme/lego/v4/providers/dns/cloudflare"
|
"github.com/go-acme/lego/v4/providers/dns/cloudflare"
|
||||||
"github.com/go-acme/lego/v4/registration"
|
"github.com/go-acme/lego/v4/registration"
|
||||||
@@ -58,6 +59,11 @@ type ACMEManager struct {
|
|||||||
Client *lego.Client
|
Client *lego.Client
|
||||||
User *fileUser
|
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
|
// root dirs
|
||||||
dataRoot string // e.g. /var/local/certman
|
dataRoot string // e.g. /var/local/certman
|
||||||
accountRoot string // e.g. /var/local/certman/accounts
|
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)
|
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)
|
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)
|
return nil, fmt.Errorf("acme registration: %w", err)
|
||||||
}
|
}
|
||||||
mgr.User.Registration = reg
|
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)
|
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.
|
// 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)
|
rcfg, err := buildDomainRuntimeConfig(config, domainConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -187,6 +198,10 @@ func (m *ACMEManager) ObtainForDomain(domainKey string, config *common.AppConfig
|
|||||||
m.MU.Lock()
|
m.MU.Lock()
|
||||||
defer m.MU.Unlock()
|
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)
|
res, err := m.Client.Certificate.Obtain(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("obtain %q: %w", domainKey, err)
|
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.
|
// 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()
|
m.MU.Lock()
|
||||||
defer m.MU.Unlock()
|
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)
|
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.
|
// RenewWithOptions is preferred in newer lego versions.
|
||||||
renewed, err := m.Client.Certificate.RenewWithOptions(*existing, &certificate.RenewOptions{
|
renewed, err := m.Client.Certificate.RenewWithOptions(*existing, &certificate.RenewOptions{
|
||||||
Bundle: true,
|
Bundle: true,
|
||||||
@@ -232,22 +253,55 @@ func (m *ACMEManager) GetCertPaths(domainKey string) (certPEM, keyPEM string) {
|
|||||||
filepath.Join(dir, base+".key")
|
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
|
// 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
|
domainName := domainConfig.Domain.DomainName
|
||||||
|
|
||||||
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.Certificates.DataRoot)
|
||||||
if domainConfig.Certificates.DataRoot == "" {
|
|
||||||
dataRoot = config.Certificates.DataRoot
|
|
||||||
} else {
|
|
||||||
dataRoot = domainConfig.Certificates.DataRoot
|
|
||||||
}
|
|
||||||
|
|
||||||
caDirURL := config.Certificates.CADirURL
|
caDirURL := config.Certificates.CADirURL
|
||||||
|
|
||||||
@@ -275,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.
|
// If a subdomain entry looks like a full FQDN already, it is used as-is.
|
||||||
func buildDomainList(baseDomain string, subs []string) []string {
|
func buildDomainList(baseDomain string, subs []string) []string {
|
||||||
seen := map[string]struct{}{}
|
seen := map[string]struct{}{}
|
||||||
|
out := make([]string, 0, len(subs)+1)
|
||||||
add := func(d string) {
|
add := func(d string) {
|
||||||
d = strings.TrimSpace(strings.ToLower(d))
|
d = strings.TrimSpace(strings.ToLower(d))
|
||||||
if d == "" {
|
if d == "" {
|
||||||
@@ -284,6 +339,7 @@ func buildDomainList(baseDomain string, subs []string) []string {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
seen[d] = struct{}{}
|
seen[d] = struct{}{}
|
||||||
|
out = append(out, d)
|
||||||
}
|
}
|
||||||
|
|
||||||
add(baseDomain)
|
add(baseDomain)
|
||||||
@@ -315,10 +371,6 @@ func buildDomainList(baseDomain string, subs []string) []string {
|
|||||||
add(s + "." + baseDomain)
|
add(s + "." + baseDomain)
|
||||||
}
|
}
|
||||||
|
|
||||||
out := make([]string, 0, len(seen))
|
|
||||||
for d := range seen {
|
|
||||||
out = append(out, d)
|
|
||||||
}
|
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -584,6 +636,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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
15
server/acme_manager_test.go
Normal file
15
server/acme_manager_test.go
Normal 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")
|
||||||
|
}
|
||||||
|
}
|
||||||
117
server/git.go
117
server/git.go
@@ -1 +1,118 @@
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.nevets.tech/Steven/certman/common"
|
||||||
|
"github.com/go-git/go-git/v5"
|
||||||
|
gitconf "github.com/go-git/go-git/v5/config"
|
||||||
|
"github.com/go-git/go-git/v5/plumbing/object"
|
||||||
|
"github.com/go-git/go-git/v5/plumbing/transport/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AddAndPushCerts(ws *common.GitWorkspace, dataRoot, repoSuffix string, config *common.AppConfig) error {
|
||||||
|
certFiles, err := os.ReadDir(dataRoot)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error reading from directory: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, entry := range certFiles {
|
||||||
|
if strings.HasSuffix(entry.Name(), ".crpt") {
|
||||||
|
file, err := ws.FS.Create(entry.Name())
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error copying file to memfs: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
certFile, err := os.ReadFile(filepath.Join(dataRoot, entry.Name()))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error reading file to memfs: %v\n", err)
|
||||||
|
file.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = file.Write(certFile)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error writing to memfs: %v\n", err)
|
||||||
|
file.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = ws.WorkTree.Add(file.Name())
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
|
||||||
|
file.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = file.Close()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error closing file: %v\n", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := ws.FS.Create("/SERVER_ID")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error creating file in memfs: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = file.Write([]byte(config.App.UUID))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error writing to memfs: %v\n", err)
|
||||||
|
file.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = ws.WorkTree.Add(file.Name())
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error adding file %v: %v\n", file.Name(), err)
|
||||||
|
file.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = file.Close()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error closing file: %v\n", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
status, err := ws.WorkTree.Status()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error getting repo status: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if status.IsClean() {
|
||||||
|
fmt.Printf("Repository is clean, skipping commit...\n")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Work Tree Status:\n" + status.String())
|
||||||
|
signature := &object.Signature{
|
||||||
|
Name: "Cert Manager",
|
||||||
|
Email: config.Certificates.Email,
|
||||||
|
When: time.Now(),
|
||||||
|
}
|
||||||
|
_, err = ws.WorkTree.Commit("Update "+ws.Domain+" @ "+time.Now().Format("Mon Jan _2 2006 15:04:05 MST"), &git.CommitOptions{Author: signature, Committer: signature})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error committing certs: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
creds := &http.BasicAuth{
|
||||||
|
Username: config.Git.Username,
|
||||||
|
Password: config.Git.APIToken,
|
||||||
|
}
|
||||||
|
err = ws.Repo.Push(&git.PushOptions{
|
||||||
|
Auth: creds,
|
||||||
|
Force: true,
|
||||||
|
RemoteName: "origin",
|
||||||
|
RefSpecs: []gitconf.RefSpec{
|
||||||
|
"refs/heads/master:refs/heads/master",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error pushing to origin: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Successfully uploaded to " + config.Git.Server + "/" + config.Git.OrgName + "/" + ws.Domain + repoSuffix + ".git")
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user