0.1.0, add examples, add license

This commit is contained in:
Adora Laura Kalb 2024-07-03 11:56:04 +02:00
parent 523485f307
commit 1b1f24ef60
Signed by: adoralaura
SSH key fingerprint: SHA256:3XrkbR8ikAZJVtYfaUliX1MhmJYVAe/ocIb/MiDHBJ8
13 changed files with 156 additions and 20 deletions

4
.gitignore vendored
View file

@ -25,7 +25,7 @@ bin/
examples/testing/ examples/testing/
*.toml *.yaml
!examples/*.toml !examples/*.yaml
test/ test/

10
LICENSE
View file

@ -1 +1,9 @@
Copyright © 2024 Laura Kalb <dev@lauka.net> MIT License
Copyright © 2024 Adora Laura Kalb <dev@lauka.net>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

2
README.md Normal file
View file

@ -0,0 +1,2 @@
# certwarden-deploy
This is a tool to deploy certificates from a [CertWarden](https://www.certwarden.com/) instance.

View file

@ -29,5 +29,6 @@ func init() {
cli.RootCmd.PersistentFlags().BoolVarP(&configuration.DryRun, "dry-run", "d", false, "Just show the would-be changes without changing the file system (turns on verbose logging)") cli.RootCmd.PersistentFlags().BoolVarP(&configuration.DryRun, "dry-run", "d", false, "Just show the would-be changes without changing the file system (turns on verbose logging)")
cli.RootCmd.PersistentFlags().BoolVarP(&configuration.QuietLogging, "quiet", "q", false, "Disable any logging (if both -q and -v are set, quiet wins)") cli.RootCmd.PersistentFlags().BoolVarP(&configuration.QuietLogging, "quiet", "q", false, "Disable any logging (if both -q and -v are set, quiet wins)")
cli.RootCmd.PersistentFlags().StringVarP(&configuration.ConfigFile, "config", "c", "/etc/certwarden-deploy/config.yaml", "Path to config file (default is /etc/certwarden-deploy/config.yaml)") cli.RootCmd.PersistentFlags().StringVarP(&configuration.ConfigFile, "config", "c", "/etc/certwarden-deploy/config.yaml", "Path to config file (default is /etc/certwarden-deploy/config.yaml)")
cli.RootCmd.PersistentFlags().BoolVarP(&configuration.Force, "force", "f", false, "Force overwriting and execution action to occur, regardless if certificate already exists")
} }

View file

@ -1,8 +0,0 @@
base_path: "https://certs.lauka-home.net"
disable_certificate_validation: true
certificates:
- name: test.laura.ovh
api_key: CiwnqR3rF1KZhGCRMsydSHkKksdeeFPA
action: ""

28
examples/config.yaml Normal file
View file

@ -0,0 +1,28 @@
# Base URL of the CertWarden instance
# required
base_url: "https://certwarden.example.com"
# Set this to true if your CertWarden instance does not have a publicly trusted
# TLS certificate (e.g. it has a self signed one)
# default is false
disable_certificate_validation: false
# define all managed certificates here
certificates:
# name is a unique identifier that must start and end with an alphanumeric character,
# and can contain the following characters: a-zA-Z0-9._-
# required
- name: test-certificate.example.com
# Contains the API-Key to fetch the certificate from the server
# required
api_key: examplekey_notvalid_hrzjGDDw8z
# action to run when certificate was updated or --force is on
action: "/usr/bin/systemd reload caddy"
# path where to save the certificate
# required
file_path: "/path/to/test-certificate.example.com-cert.pem"

View file

@ -11,6 +11,8 @@ import (
"log/slog" "log/slog"
"net/http" "net/http"
"os" "os"
"os/exec"
"strings"
"time" "time"
"code.lila.network/adoralaura/certwarden-deploy/internal/configuration" "code.lila.network/adoralaura/certwarden-deploy/internal/configuration"
@ -38,25 +40,51 @@ func HandleCertificates(logger *slog.Logger, config *configuration.ConfigFileDat
return return
} }
if certIsDifferent { if certIsDifferent || configuration.Force {
if configuration.Force {
logger.Info("Forcing file system change due to --force", "cert-id", cert.Name)
}
err = updateCertOnFS(logger, cert.FilePath, certBytes) err = updateCertOnFS(logger, cert.FilePath, certBytes)
if err != nil { if err != nil {
logger.Error("failed to handle certificate", "cert-id", cert.Name, "error", err) logger.Error("failed to handle certificate", "cert-id", cert.Name, "error", err)
return return
} }
if configuration.Force {
logger.Info("Forcing file system change due to --force", "cert-id", cert.Name)
}
err = handleCertificateAction(cert)
if err != nil {
logger.Error("post certificate change command failed", "cert-id", cert.Name, "error", err)
}
} }
logger.Info("Certificate updated successfully", "cert-id", cert.Name) logger.Info("Certificate updated successfully", "cert-id", cert.Name)
} }
} }
func checkCertIsDifferent(logger *slog.Logger, path string, data []byte) (bool, error) { func getCertFromFile(path string) ([]byte, error) {
filebytes, err := os.ReadFile(path) filebytes, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return []byte{}, err
} else {
return []byte{}, fmt.Errorf("failed to read certificate file on disk: %w", err)
}
}
return filebytes, nil
}
func checkCertIsDifferent(logger *slog.Logger, path string, data []byte) (bool, error) {
filebytes, err := getCertFromFile(path)
if err != nil { if err != nil {
if errors.Is(err, fs.ErrNotExist) { if errors.Is(err, fs.ErrNotExist) {
return true, nil return true, nil
} else { } else {
return false, fmt.Errorf("failed to read certificate file on disk: %w", err) return false, fmt.Errorf("failed to compare certificates: %w", err)
} }
} }
@ -159,3 +187,18 @@ func getCertFromServer(logger *slog.Logger, certName string, certKey string, bas
return body, nil return body, nil
} }
func handleCertificateAction(cert configuration.CertificateData) error {
if cert.Action == "" {
return nil
}
action := strings.ReplaceAll(cert.Action, "{name}", cert.Name)
action = strings.ReplaceAll(action, "{path}", cert.FilePath)
sargs := strings.Split(action, " ")
cmd := exec.Command(sargs[0], sargs...)
err := cmd.Run()
return err
}

View file

@ -0,0 +1 @@
package certificates

View file

@ -37,5 +37,7 @@ func handleRootCmd(cmd *cobra.Command, args []string) {
slog.Error("failed to initialize sentry", "error", err) slog.Error("failed to initialize sentry", "error", err)
} }
configuration.ValidateConfig(log, *config)
certificates.HandleCertificates(log, config) certificates.HandleCertificates(log, config)
} }

View file

@ -1,14 +1,24 @@
package configuration package configuration
import "log/slog" // Config file gets read into here
var Config *ConfigFileData var Config *ConfigFileData
// ConfigFile contains the path to the config file on disk
var ConfigFile string var ConfigFile string
var Logger *slog.Logger
// Flag to show that the user wants a dry run
var DryRun bool var DryRun bool
// Flag to show that the user wants quiet logging
var QuietLogging bool var QuietLogging bool
// Flag to show that the user wants verbose logging
var VerboseLogging bool var VerboseLogging bool
// Flag to show that the user wants to force certificate update
var Force bool
// Struct to read the config file into when reading from disk
type ConfigFileData struct { type ConfigFileData struct {
BaseURL string `yaml:"base_url"` BaseURL string `yaml:"base_url"`
DisableCertificateValidation bool `yaml:"disable_certificate_validation"` DisableCertificateValidation bool `yaml:"disable_certificate_validation"`
@ -16,6 +26,7 @@ type ConfigFileData struct {
Certificates []CertificateData `yaml:"certificates"` Certificates []CertificateData `yaml:"certificates"`
} }
// Struct that holds the details of a single managed certificate
type CertificateData struct { type CertificateData struct {
Name string `yaml:"name"` Name string `yaml:"name"`
ApiKey string `yaml:"api_key"` ApiKey string `yaml:"api_key"`

View file

@ -0,0 +1,45 @@
package configuration
import (
"log/slog"
"os"
"regexp"
)
func ValidateConfig(logger *slog.Logger, config ConfigFileData) {
validationFailed := false
if config.BaseURL == "" {
logger.Error(`Field 'base_url' in config file is required!`)
validationFailed = true
}
for _, cert := range config.Certificates {
if cert.Name == "" {
cert.Name = "unnamed_certificate"
logger.Error(`Field 'name' for certificates cannot be blank!`)
validationFailed = true
}
if cert.ApiKey == "" {
logger.Error(`Field 'api_key' for certificate ` + cert.Name + " cannot be blank!")
validationFailed = true
}
if cert.FilePath == "" {
logger.Error(`Field 'file_path' for certificate ` + cert.Name + " cannot be blank!")
validationFailed = true
}
re := regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
if !re.MatchString(cert.Name) {
logger.Error(`Field 'name' for certificate may only contain -_. and alphanumeric characters!`)
validationFailed = true
}
}
if validationFailed {
logger.Error("Config file has errors! Please fix errors above! Exiting...", "config-path", ConfigFile)
os.Exit(1)
}
}

View file

@ -1,6 +1,6 @@
package constants package constants
const Version = "0.0.1" const Version = "0.1.0"
const CertificateApiPath = "/certwarden/api/v1/download/certificates/" const CertificateApiPath = "/certwarden/api/v1/download/certificates/"
const ApiKeyHeaderName = "X-API-Key" const ApiKeyHeaderName = "X-API-Key"
const UserAgent = "certwarden-deploy/" + Version + " +code.lila.network/adoralaura/certwarden-deploy" const UserAgent = "certwarden-deploy/" + Version + " +https://code.lila.network/adoralaura/certwarden-deploy"

View file

@ -10,9 +10,11 @@ import (
func InitializeLogger() *slog.Logger { func InitializeLogger() *slog.Logger {
logLevel := slog.LevelInfo logLevel := slog.LevelInfo
sourceLogging := false
if configuration.VerboseLogging { if configuration.VerboseLogging {
logLevel = slog.LevelDebug logLevel = slog.LevelDebug
sourceLogging = true
} }
if configuration.QuietLogging { if configuration.QuietLogging {
logLevel = slog.LevelError logLevel = slog.LevelError
@ -22,7 +24,8 @@ func InitializeLogger() *slog.Logger {
} }
opts := &slog.HandlerOptions{ opts := &slog.HandlerOptions{
Level: logLevel, Level: logLevel,
AddSource: sourceLogging,
} }
handler := slog.NewTextHandler(os.Stdout, opts) handler := slog.NewTextHandler(os.Stdout, opts)