Files
certman/main.go
2023-06-02 03:20:08 -04:00

295 lines
7.4 KiB
Go

package main
import (
"bufio"
"code.gitea.io/sdk/gitea"
"fmt"
"git.nevets.tech/Steven/ezconf"
"github.com/go-git/go-git/v5/plumbing/object"
"io"
"os/exec"
"strings"
"time"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/memory"
"os"
)
var config *ezconf.Configuration
var giteaClient *gitea.Client
var domain string
var legoBaseArgs []string
var storage *memory.Storage
var fs billy.Filesystem
var workTree *git.Worktree
var creds *http.BasicAuth
var repo *git.Repository
func main() {
var err error
args := os.Args
// -c
hasConfig, configIndex := contains(args, "-c")
if hasConfig {
config = ezconf.NewConfiguration(args[configIndex+1])
} else {
fmt.Printf("Error, no config passed. Please add '-c /path/to/config.ini' to the command\n")
os.Exit(1)
}
// -d
hasDomain, domainIndex := contains(args, "-d")
if hasDomain {
domain = args[domainIndex+1]
} else {
fmt.Printf("Error, no domain passed. Please add '-d domain.tld' to the command\n")
os.Exit(1)
}
hasDns, dnsIndex := contains(args, "--dns")
legoBaseArgs = []string{
"-a",
"--dns",
"cloudflare",
"--email=" + config.GetAsString("Cloudflare.cf_email"),
"--domains=" + domain,
"--domains=*." + domain,
"--path=" + config.GetAsString("Certificates.certs_path"),
}
legoNewSiteArgs := append(legoBaseArgs, "run")
legoRenewSiteArgs := append(legoBaseArgs, "renew", "--days", "90")
subdomains := config.GetAsStrings("Certificates.subdomains")
if subdomains != nil {
for i, subdomain := range subdomains {
legoBaseArgs = insert(legoBaseArgs, 5+i, "--domains=*."+subdomain+"."+domain)
}
}
if hasDns {
legoBaseArgs = insert(legoBaseArgs, 3, "--dns.resolvers="+args[dnsIndex+1])
}
creds = &http.BasicAuth{
Username: config.GetAsString("Git.username"),
Password: config.GetAsString("Git.api_token"),
}
giteaClient, err = gitea.NewClient(config.GetAsString("Git.server"), gitea.SetToken(config.GetAsString("Git.api_token")))
if err != nil {
fmt.Printf("Error connecting to gitea instance: %v\n", err)
os.Exit(1)
}
storage = memory.NewStorage()
fs = memfs.New()
var cmd *exec.Cmd
switch args[len(args)-1] {
case "gen":
{
url := createGiteaRepo()
cloneRepo(url)
fixUpdateSh()
cmd = exec.Command("lego", legoNewSiteArgs...)
}
case "renew":
{
cloneRepo(config.GetAsString("Git.server") + "/" + config.GetAsString("Git.org_name") + "/" + domain + "-certificates.git")
cmd = exec.Command("lego", legoRenewSiteArgs...)
}
case "gen-cert-only":
{
cmd = exec.Command("lego", legoNewSiteArgs...)
}
case "renew-cert-only":
{
cmd = exec.Command("lego", legoRenewSiteArgs...)
}
case "git":
{
url := createGiteaRepo()
cloneRepo(url)
fixUpdateSh()
addAndPushCerts()
os.Exit(0)
}
default:
{
fmt.Println("Missing arguments: conclude command with 'gen' or 'renew'")
os.Exit(1)
}
}
cmd.Env = append(cmd.Environ(),
"CLOUDFLARE_DNS_API_TOKEN="+config.GetAsString("Cloudflare.cf_api_token"),
"CLOUDFLARE_ZONE_API_TOKEN"+config.GetAsString("Cloudflare.cf_api_token"),
"CLOUDFLARE_EMAIL="+config.GetAsString("Cloudflare.cf_email"),
)
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Printf("Error getting stdout from lego process: %v", err)
os.Exit(1)
}
err = cmd.Start()
if err != nil {
fmt.Printf("Error creating certs with lego: %v", err)
os.Exit(1)
}
scanner := bufio.NewScanner(stdout)
go func() {
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}()
err = cmd.Wait()
if err != nil {
fmt.Printf("Error waiting for lego command to finish: %v", err)
os.Exit(1)
}
addAndPushCerts()
}
func createGiteaRepo() string {
options := gitea.CreateRepoFromTemplateOption{
Avatar: true,
Description: "Certificates storage for " + domain,
GitContent: true,
GitHooks: true,
Labels: true,
Name: domain + "-certificates",
Owner: config.GetAsString("Git.org_name"),
Private: true,
Topics: true,
Webhooks: true,
}
giteaRepo, _, err := giteaClient.CreateRepoFromTemplate(config.GetAsString("Git.org_name"), config.GetAsString("Git.template_name"), options)
if err != nil {
fmt.Printf("Error creating repo: %v\n", err)
os.Exit(1)
}
return giteaRepo.CloneURL
}
func cloneRepo(url string) {
var err error
repo, err = git.Clone(storage, fs, &git.CloneOptions{URL: url, Auth: creds})
if err != nil {
fmt.Printf("Error clone git repo: %v\n", err)
os.Exit(1)
}
workTree, err = repo.Worktree()
if err != nil {
fmt.Printf("Error getting worktree from repo: %v\n", err)
os.Exit(1)
}
}
func fixUpdateSh() {
oldUpdateSh, err := fs.Open("update.sh")
if err != nil {
fmt.Printf("Error opening update.sh: %v", err)
os.Exit(1)
}
contentBytes, err := io.ReadAll(oldUpdateSh)
if err != nil {
fmt.Printf("Error reading update.sh: %v", err)
os.Exit(1)
}
content := string(contentBytes)
strings.ReplaceAll(content, "<>", domain)
updateSh, err := fs.Create("update.sh")
_, err = updateSh.Write([]byte(content))
err = updateSh.Close()
if err != nil {
fmt.Printf("Error writing update.sh: %v", err)
os.Exit(1)
}
_, err = workTree.Add("update.sh")
if err != nil {
fmt.Printf("Error adding update.sh: %v", err)
os.Exit(1)
}
}
func addAndPushCerts() {
//TODO integrate SOPS api when stable release
certs, err := os.ReadDir(config.GetAsString("Certificates.certs_path") + "/certificates")
if err != nil {
fmt.Printf("Error reading from directory: %v\n", err)
os.Exit(1)
}
for _, cert := range certs {
if strings.HasPrefix(cert.Name(), domain) {
file, err := fs.Create(cert.Name())
if err != nil {
fmt.Printf("Error copying cert to memfs: %v\n", err)
os.Exit(1)
}
certFile, err := os.ReadFile(config.GetAsString("Certificates.certs_path") + "/certificates/" + cert.Name())
_, err = file.Write(certFile)
err = file.Close()
if err != nil {
fmt.Printf("Error writing to memfs: %v\n", err)
os.Exit(1)
}
_, err = workTree.Add(cert.Name())
if err != nil {
fmt.Printf("Error adding certificate %v: %v", cert.Name(), err)
os.Exit(1)
}
}
}
status, err := workTree.Status()
if err != nil {
fmt.Printf("Error getting repo status: %v\n", err)
os.Exit(1)
}
fmt.Println("Work Tree Status:\n" + status.String())
signature := &object.Signature{
Name: "Cert Manager",
Email: "certs@nevets.tech",
When: time.Now(),
}
_, err = 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)
os.Exit(1)
}
err = repo.Push(&git.PushOptions{Auth: creds, Force: true, RemoteName: "origin"})
if err != nil {
fmt.Printf("Error pushing to origin: %v\n", err)
os.Exit(1)
}
fmt.Println("Successfully uploaded to " + config.GetAsString("Git.server") + "/" + config.GetAsString("Git.org_name") + "/" + domain + "-certificates.git")
}
func contains(slice []string, value string) (sliceHas bool, index int) {
for i, entry := range slice {
if entry == value {
return true, i
}
}
return false, -1
}
func insert(a []string, index int, value string) []string {
last := len(a) - 1
a = append(a, a[last])
copy(a[index+1:], a[index:last])
a[index] = value
return a
}