diff --git a/.gitignore b/.gitignore index 9e2506e..d94d697 100644 --- a/.gitignore +++ b/.gitignore @@ -25,7 +25,7 @@ bin/ examples/testing/ -*.toml -!examples/*.toml +*.yaml +!examples/*.yaml test/ diff --git a/LICENSE b/LICENSE index 0d4ef8b..40ed8f3 100644 --- a/LICENSE +++ b/LICENSE @@ -1 +1,9 @@ -Copyright © 2024 Laura Kalb \ No newline at end of file +MIT License + +Copyright © 2024 Adora Laura Kalb + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1d4a493 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# certwarden-deploy +This is a tool to deploy certificates from a [CertWarden](https://www.certwarden.com/) instance. diff --git a/cmd/certwarden-deploy/root.go b/cmd/certwarden-deploy/root.go index 2aa523b..b1c5a60 100644 --- a/cmd/certwarden-deploy/root.go +++ b/cmd/certwarden-deploy/root.go @@ -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.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().BoolVarP(&configuration.Force, "force", "f", false, "Force overwriting and execution action to occur, regardless if certificate already exists") } diff --git a/config.yaml b/config.yaml deleted file mode 100644 index 194bb99..0000000 --- a/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -base_path: "https://certs.lauka-home.net" -disable_certificate_validation: true - - -certificates: - - name: test.laura.ovh - api_key: CiwnqR3rF1KZhGCRMsydSHkKksdeeFPA - action: "" diff --git a/examples/config.yaml b/examples/config.yaml new file mode 100644 index 0000000..2b38238 --- /dev/null +++ b/examples/config.yaml @@ -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" diff --git a/internal/certificates/certificates.go b/internal/certificates/certificates.go index 9575485..d98526f 100644 --- a/internal/certificates/certificates.go +++ b/internal/certificates/certificates.go @@ -11,6 +11,8 @@ import ( "log/slog" "net/http" "os" + "os/exec" + "strings" "time" "code.lila.network/adoralaura/certwarden-deploy/internal/configuration" @@ -38,25 +40,51 @@ func HandleCertificates(logger *slog.Logger, config *configuration.ConfigFileDat 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) if err != nil { logger.Error("failed to handle certificate", "cert-id", cert.Name, "error", err) 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) + } } -func checkCertIsDifferent(logger *slog.Logger, path string, data []byte) (bool, error) { +func getCertFromFile(path string) ([]byte, error) { 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 errors.Is(err, fs.ErrNotExist) { return true, nil } 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 } + +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 +} diff --git a/internal/certificates/certificates_test.go b/internal/certificates/certificates_test.go new file mode 100644 index 0000000..1f9bfc3 --- /dev/null +++ b/internal/certificates/certificates_test.go @@ -0,0 +1 @@ +package certificates diff --git a/internal/cli/root.go b/internal/cli/root.go index b626b2a..6bdca6f 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -37,5 +37,7 @@ func handleRootCmd(cmd *cobra.Command, args []string) { slog.Error("failed to initialize sentry", "error", err) } + configuration.ValidateConfig(log, *config) + certificates.HandleCertificates(log, config) } diff --git a/internal/configuration/models.go b/internal/configuration/models.go index 9c3b5e5..cbd5bae 100644 --- a/internal/configuration/models.go +++ b/internal/configuration/models.go @@ -1,14 +1,24 @@ package configuration -import "log/slog" - +// Config file gets read into here var Config *ConfigFileData + +// ConfigFile contains the path to the config file on disk var ConfigFile string -var Logger *slog.Logger + +// Flag to show that the user wants a dry run var DryRun bool + +// Flag to show that the user wants quiet logging var QuietLogging bool + +// Flag to show that the user wants verbose logging 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 { BaseURL string `yaml:"base_url"` DisableCertificateValidation bool `yaml:"disable_certificate_validation"` @@ -16,6 +26,7 @@ type ConfigFileData struct { Certificates []CertificateData `yaml:"certificates"` } +// Struct that holds the details of a single managed certificate type CertificateData struct { Name string `yaml:"name"` ApiKey string `yaml:"api_key"` diff --git a/internal/configuration/validation.go b/internal/configuration/validation.go new file mode 100644 index 0000000..f743f54 --- /dev/null +++ b/internal/configuration/validation.go @@ -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) + } +} diff --git a/internal/constants/constants.go b/internal/constants/constants.go index 445f1c4..d888ac0 100644 --- a/internal/constants/constants.go +++ b/internal/constants/constants.go @@ -1,6 +1,6 @@ package constants -const Version = "0.0.1" +const Version = "0.1.0" const CertificateApiPath = "/certwarden/api/v1/download/certificates/" 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" diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 4767184..74cb48a 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -10,9 +10,11 @@ import ( func InitializeLogger() *slog.Logger { logLevel := slog.LevelInfo + sourceLogging := false if configuration.VerboseLogging { logLevel = slog.LevelDebug + sourceLogging = true } if configuration.QuietLogging { logLevel = slog.LevelError @@ -22,7 +24,8 @@ func InitializeLogger() *slog.Logger { } opts := &slog.HandlerOptions{ - Level: logLevel, + Level: logLevel, + AddSource: sourceLogging, } handler := slog.NewTextHandler(os.Stdout, opts)