diff --git a/conf/config.yml b/conf/config.yml index 5fca87d..1a9f8f8 100644 --- a/conf/config.yml +++ b/conf/config.yml @@ -37,5 +37,17 @@ rqlite: AutoVacInterval: 12h JoinAs: default +backup: + Enabled: true + Num: 10 + Version: 1 + Type: "file" + Interval: "2m" + ClearIntervalDays: 7 + Timestamp: true + Sub: + Dir: "app/data/backups/rqlite" + Name: "backup.sqlite.gz" + metricsAutodiscovery: enable: true \ No newline at end of file diff --git a/service/rqlite/config_flags.go b/service/rqlite/config_flags.go new file mode 100644 index 0000000..ffb602e --- /dev/null +++ b/service/rqlite/config_flags.go @@ -0,0 +1,486 @@ +// nolint +package rqlite + +import ( + "bytes" + "fmt" + "io" + "net" + "os" + "path/filepath" + "reflect" + "strconv" + "strings" + "time" + + "github.com/pkg/errors" +) + +// Config represents the configuration as set by command-line flags. +// All variables will be set, unless explicit noted. +type Config struct { + // DataPath is path to node data. Always set. + DataPath string + + // ExtensionPaths is a comma-delimited list of path to SQLite extensions to be loaded. + // Each element may be a directory path, zipfile, or tar.gz file. May not be set. + ExtensionPaths StringSliceValue + + // HTTPAddr is the bind network address for the HTTP Server. + // It never includes a trailing HTTP or HTTPS. + HTTPAddr string + + // HTTPAdv is the advertised HTTP server network. + HTTPAdv string + + // HTTPAllowOrigin is the value to set for Access-Control-Allow-Origin HTTP header. + HTTPAllowOrigin string + + // AuthFile is the path to the authentication file. May not be set. + AuthFile string `filepath:"true"` + + // AutoBackupFile is the path to the auto-backup file. May not be set. + AutoBackupFile string `filepath:"true"` + + // AutoRestoreFile is the path to the auto-restore file. May not be set. + AutoRestoreFile string `filepath:"true"` + + // HTTPx509CACert is the path to the CA certificate file for when this node verifies + // other certificates for any HTTP communications. May not be set. + HTTPx509CACert string `filepath:"true"` + + // HTTPx509Cert is the path to the X509 cert for the HTTP server. May not be set. + HTTPx509Cert string `filepath:"true"` + + // HTTPx509Key is the path to the private key for the HTTP server. May not be set. + HTTPx509Key string `filepath:"true"` + + // HTTPVerifyClient indicates whether the HTTP server should verify client certificates. + HTTPVerifyClient bool + + // NodeX509CACert is the path to the CA certificate file for when this node verifies + // other certificates for any inter-node communications. May not be set. + NodeX509CACert string `filepath:"true"` + + // NodeX509Cert is the path to the X509 cert for the Raft server. May not be set. + NodeX509Cert string `filepath:"true"` + + // NodeX509Key is the path to the X509 key for the Raft server. May not be set. + NodeX509Key string `filepath:"true"` + + // NoNodeVerify disables checking other nodes' Node X509 certs for validity. + NoNodeVerify bool + + // NodeVerifyClient enable mutual TLS for node-to-node communication. + NodeVerifyClient bool + + // NodeVerifyServerName is the hostname to verify on the certificates returned by nodes. + // If NoNodeVerify is true this field is ignored. + NodeVerifyServerName string + + // NodeID is the Raft ID for the node. + NodeID string + + // RaftAddr is the bind network address for the Raft server. + RaftAddr string + + // RaftAdv is the advertised Raft server address. + RaftAdv string + + // JoinAddrs is the list of Raft addresses to use for a join attempt. + JoinAddrs string + + // JoinAttempts is the number of times a node should attempt to join using a + // given address. + JoinAttempts int + + // JoinInterval is the time between retrying failed join operations. + JoinInterval time.Duration + + // JoinAs sets the user join attempts should be performed as. May not be set. + JoinAs string + + // BootstrapExpect is the minimum number of nodes required for a bootstrap. + BootstrapExpect int + + // BootstrapExpectTimeout is the maximum time a bootstrap operation can take. + BootstrapExpectTimeout time.Duration + + // DiscoMode sets the discovery mode. May not be set. + DiscoMode string + + // DiscoKey sets the discovery prefix key. + DiscoKey string + + // DiscoConfig sets the path to any discovery configuration file. May not be set. + DiscoConfig string + + // OnDiskPath sets the path to the SQLite file. May not be set. + OnDiskPath string + + // FKConstraints enables SQLite foreign key constraints. + FKConstraints bool + + // AutoVacInterval sets the automatic VACUUM interval. Use 0s to disable. + AutoVacInterval time.Duration + + // AutoOptimizeInterval sets the automatic optimization interval. Use 0s to disable. + AutoOptimizeInterval time.Duration + + // RaftLogLevel sets the minimum logging level for the Raft subsystem. + RaftLogLevel string + + // RaftNonVoter controls whether this node is a voting, read-only node. + RaftNonVoter bool + + // RaftSnapThreshold is the number of outstanding log entries that trigger snapshot. + RaftSnapThreshold uint64 + + // RaftSnapThreshold is the size of a SQLite WAL file which will trigger a snapshot. + RaftSnapThresholdWALSize uint64 + + // RaftSnapInterval sets the threshold check interval. + RaftSnapInterval time.Duration + + // RaftLeaderLeaseTimeout sets the leader lease timeout. + RaftLeaderLeaseTimeout time.Duration + + // RaftHeartbeatTimeout specifies the time in follower state without contact + // from a Leader before the node attempts an election. + RaftHeartbeatTimeout time.Duration + + // RaftElectionTimeout specifies the time in candidate state without contact + // from a Leader before the node attempts an election. + RaftElectionTimeout time.Duration + + // RaftApplyTimeout sets the Log-apply timeout. + RaftApplyTimeout time.Duration + + // RaftShutdownOnRemove sets whether Raft should be shutdown if the node is removed + RaftShutdownOnRemove bool + + // RaftClusterRemoveOnShutdown sets whether the node should remove itself from the cluster on shutdown + RaftClusterRemoveOnShutdown bool + + // RaftStepdownOnShutdown sets whether Leadership should be relinquished on shutdown + RaftStepdownOnShutdown bool + + // RaftReapNodeTimeout sets the duration after which a non-reachable voting node is + // reaped i.e. removed from the cluster. + RaftReapNodeTimeout time.Duration + + // RaftReapReadOnlyNodeTimeout sets the duration after which a non-reachable non-voting node is + // reaped i.e. removed from the cluster. + RaftReapReadOnlyNodeTimeout time.Duration + + // ClusterConnectTimeout sets the timeout when initially connecting to another node in + // the cluster, for non-Raft communications. + ClusterConnectTimeout time.Duration + + // WriteQueueCap is the default capacity of Execute queues + WriteQueueCap int + + // WriteQueueBatchSz is the default batch size for Execute queues + WriteQueueBatchSz int + + // WriteQueueTimeout is the default time after which any data will be sent on + // Execute queues, if a batch size has not been reached. + WriteQueueTimeout time.Duration + + // WriteQueueTx controls whether writes from the queue are done within a transaction. + WriteQueueTx bool + + // CPUProfile enables CPU profiling. + CPUProfile string + + // MemProfile enables memory profiling. + MemProfile string + + // TraceProfile enables trace profiling. + TraceProfile string +} + +type Backup struct { + Enabled bool + Amount int + Version int + Type string + Interval string + ClearIntervalDays int + Timestamp bool + Vacuum bool + Sub Sub +} + +type Sub struct { + Dir string + Name string +} + +// Validate checks the configuration for internal consistency, and activates +// important rqlite policies. It must be called at least once on a Config +// object before the Config object is used. It is OK to call more than +// once. +func (c *Config) Validate() error { + dataPath, err := filepath.Abs(c.DataPath) + if err != nil { + return errors.Errorf("failed to determine absolute data path: %s", err.Error()) + } + c.DataPath = dataPath + + err = c.CheckFilePaths() + if err != nil { + return err + } + + err = c.CheckDirPaths() + if err != nil { + return err + } + + if len(c.ExtensionPaths) > 0 { + for _, p := range c.ExtensionPaths { + if !fileExists(p) { + return errors.Errorf("extension path does not exist: %s", p) + } + } + } + + if !bothUnsetSet(c.HTTPx509Cert, c.HTTPx509Key) { + return errors.Errorf("either both -%s and -%s must be set, or neither", HTTPx509CertFlag, HTTPx509KeyFlag) + } + if !bothUnsetSet(c.NodeX509Cert, c.NodeX509Key) { + return errors.Errorf("either both -%s and -%s must be set, or neither", NodeX509CertFlag, NodeX509KeyFlag) + + } + + if c.RaftAddr == c.HTTPAddr { + return errors.New("HTTP and Raft addresses must differ") + } + + // Enforce policies regarding addresses + if c.RaftAdv == "" { + c.RaftAdv = c.RaftAddr + } + if c.HTTPAdv == "" { + c.HTTPAdv = c.HTTPAddr + } + + // Node ID policy + if c.NodeID == "" { + c.NodeID = c.RaftAdv + } + + // Perform some address validity checks. + if strings.HasPrefix(strings.ToLower(c.HTTPAddr), "http") || + strings.HasPrefix(strings.ToLower(c.HTTPAdv), "http") { + return errors.New("HTTP options should not include protocol (http:// or https://)") + } + if _, _, err := net.SplitHostPort(c.HTTPAddr); err != nil { + return errors.New("HTTP bind address not valid") + } + + hadv, _, err := net.SplitHostPort(c.HTTPAdv) + if err != nil { + return errors.New("HTTP advertised HTTP address not valid") + } + if addr := net.ParseIP(hadv); addr != nil && addr.IsUnspecified() { + return errors.Errorf("advertised HTTP address is not routable (%s), specify it via -%s or -%s", + hadv, HTTPAddrFlag, HTTPAdvAddrFlag) + } + + if _, rp, err := net.SplitHostPort(c.RaftAddr); err != nil { + return errors.New("raft bind address not valid") + } else if _, err := strconv.Atoi(rp); err != nil { + return errors.New("raft bind port not valid") + } + + radv, rp, err := net.SplitHostPort(c.RaftAdv) + if err != nil { + return errors.New("raft advertised address not valid") + } + if addr := net.ParseIP(radv); addr != nil && addr.IsUnspecified() { + return errors.Errorf("advertised Raft address is not routable (%s), specify it via -%s or -%s", + radv, RaftAddrFlag, RaftAdvAddrFlag) + } + if _, err := strconv.Atoi(rp); err != nil { + return errors.New("raft advertised port is not valid") + } + + if c.RaftAdv == c.HTTPAdv { + return errors.New("advertised HTTP and Raft addresses must differ") + } + + // Enforce bootstrapping policies + if c.BootstrapExpect > 0 && c.RaftNonVoter { + return errors.New("bootstrapping only applicable to voting nodes") + } + + // Join parameters OK? + if c.JoinAddrs != "" { + addrs := strings.Split(c.JoinAddrs, ",") + for i := range addrs { + if _, _, err := net.SplitHostPort(addrs[i]); err != nil { + return errors.Errorf("%s is an invalid join address", addrs[i]) + } + + if c.BootstrapExpect == 0 { + if addrs[i] == c.RaftAdv || addrs[i] == c.RaftAddr { + return errors.New("node cannot join with itself unless bootstrapping") + } + if c.AutoRestoreFile != "" { + return errors.New("auto-restoring cannot be used when joining a cluster") + } + } + } + + if c.DiscoMode != "" { + return errors.New("disco mode cannot be used when also explicitly joining a cluster") + } + } + + // Valid disco mode? + switch c.DiscoMode { + case "": + case DiscoModeEtcdKV, DiscoModeConsulKV: + if c.BootstrapExpect > 0 { + return errors.Errorf("bootstrapping not applicable when using %s", c.DiscoMode) + } + case DiscoModeDNS, DiscoModeDNSSRV: + if c.BootstrapExpect == 0 && !c.RaftNonVoter { + return errors.Errorf("bootstrap-expect value required when using %s with a voting node", c.DiscoMode) + } + default: + return errors.Errorf("disco mode must be one of %s, %s, %s, or %s", + DiscoModeConsulKV, DiscoModeEtcdKV, DiscoModeDNS, DiscoModeDNSSRV) + } + + return nil +} + +// JoinAddresses returns the join addresses set at the command line. Returns nil +// if no join addresses were set. +func (c *Config) JoinAddresses() []string { + if c.JoinAddrs == "" { + return nil + } + return strings.Split(c.JoinAddrs, ",") +} + +// HTTPURL returns the fully-formed, advertised HTTP API address for this config, including +// protocol, host and port. +func (c *Config) HTTPURL() string { + apiProto := "http" + if c.HTTPx509Cert != "" { + apiProto = "https" + } + return fmt.Sprintf("%s://%s", apiProto, c.HTTPAdv) +} + +// RaftPort returns the port on which the Raft system is listening. Validate must +// have been called before calling this method. +func (c *Config) RaftPort() int { + _, port, err := net.SplitHostPort(c.RaftAddr) + if err != nil { + panic("RaftAddr not valid") + } + p, err := strconv.Atoi(port) + if err != nil { + panic("RaftAddr port not valid") + } + return p +} + +// DiscoConfigReader returns a ReadCloser providing access to the Disco config. +// The caller must call close on the ReadCloser when finished with it. If no +// config was supplied, it returns nil. +func (c *Config) DiscoConfigReader() io.ReadCloser { + var rc io.ReadCloser + if c.DiscoConfig == "" { + return nil + } + + // Open config file. If opening fails, assume string is the literal config. + cfgFile, err := os.Open(c.DiscoConfig) + if err != nil { + rc = io.NopCloser(bytes.NewReader([]byte(c.DiscoConfig))) + } else { + rc = cfgFile + } + return rc +} + +// CheckFilePaths checks that all file paths in the config exist. +// Empty filepaths are ignored. +func (c *Config) CheckFilePaths() error { + v := reflect.ValueOf(c).Elem() + + // Iterate through the fields of the struct + for i := 0; i < v.NumField(); i++ { + field := v.Type().Field(i) + fieldValue := v.Field(i) + + if fieldValue.Kind() != reflect.String { + continue + } + + if tagValue, ok := field.Tag.Lookup("filepath"); ok && tagValue == "true" { + filePath := fieldValue.String() + if filePath == "" { + continue + } + if !fileExists(filePath) { + return errors.Errorf("%s does not exist", filePath) + } + } + } + return nil +} + +// CheckDirPaths checks that all directory paths in the config exist and are directories. +// Empty directory paths are ignored. +func (c *Config) CheckDirPaths() error { + v := reflect.ValueOf(c).Elem() + + // Iterate through the fields of the struct + for i := 0; i < v.NumField(); i++ { + field := v.Type().Field(i) + fieldValue := v.Field(i) + + if fieldValue.Kind() != reflect.String { + continue + } + + if tagValue, ok := field.Tag.Lookup("dirpath"); ok && tagValue == "true" { + dirPath := fieldValue.String() + if dirPath == "" { + continue + } + if !fileExists(dirPath) { + return errors.Errorf("%s does not exist", dirPath) + } + if !isDir(dirPath) { + return errors.Errorf("%s is not a directory", dirPath) + } + } + } + return nil +} + +// bothUnsetSet returns true if both a and b are unset, or both are set. +func bothUnsetSet(a, b string) bool { + return (a == "" && b == "") || (a != "" && b != "") +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +func isDir(path string) bool { + fi, err := os.Stat(path) + if err != nil { + return false + } + return fi.IsDir() +} diff --git a/service/rqlite/credentials.go b/service/rqlite/credentials.go index ccef6a9..729f845 100644 --- a/service/rqlite/credentials.go +++ b/service/rqlite/credentials.go @@ -4,7 +4,7 @@ import ( "bytes" "github.com/pkg/errors" - "github.com/rqlite/rqlite/v8/auth" + "github.com/rqlite/rqlite/v9/auth" "github.com/txix-open/isp-kit/json" ) diff --git a/service/rqlite/flags.go b/service/rqlite/flags.go index 425accf..1b01650 100644 --- a/service/rqlite/flags.go +++ b/service/rqlite/flags.go @@ -2,17 +2,10 @@ package rqlite import ( - "bytes" - "errors" "flag" "fmt" - "io" - "net" "os" - "path/filepath" - "reflect" "runtime" - "strconv" "strings" "time" ) @@ -56,440 +49,6 @@ func (s *StringSliceValue) Set(value string) error { return nil } -// Config represents the configuration as set by command-line flags. -// All variables will be set, unless explicit noted. -type Config struct { - // DataPath is path to node data. Always set. - DataPath string - - // ExtensionPaths is a comma-delimited list of path to SQLite extensions to be loaded. - // Each element may be a directory path, zipfile, or tar.gz file. May not be set. - ExtensionPaths StringSliceValue - - // HTTPAddr is the bind network address for the HTTP Server. - // It never includes a trailing HTTP or HTTPS. - HTTPAddr string - - // HTTPAdv is the advertised HTTP server network. - HTTPAdv string - - // HTTPAllowOrigin is the value to set for Access-Control-Allow-Origin HTTP header. - HTTPAllowOrigin string - - // AuthFile is the path to the authentication file. May not be set. - AuthFile string `filepath:"true"` - - // AutoBackupFile is the path to the auto-backup file. May not be set. - AutoBackupFile string `filepath:"true"` - - // AutoRestoreFile is the path to the auto-restore file. May not be set. - AutoRestoreFile string `filepath:"true"` - - // HTTPx509CACert is the path to the CA certificate file for when this node verifies - // other certificates for any HTTP communications. May not be set. - HTTPx509CACert string `filepath:"true"` - - // HTTPx509Cert is the path to the X509 cert for the HTTP server. May not be set. - HTTPx509Cert string `filepath:"true"` - - // HTTPx509Key is the path to the private key for the HTTP server. May not be set. - HTTPx509Key string `filepath:"true"` - - // HTTPVerifyClient indicates whether the HTTP server should verify client certificates. - HTTPVerifyClient bool - - // NodeX509CACert is the path to the CA certificate file for when this node verifies - // other certificates for any inter-node communications. May not be set. - NodeX509CACert string `filepath:"true"` - - // NodeX509Cert is the path to the X509 cert for the Raft server. May not be set. - NodeX509Cert string `filepath:"true"` - - // NodeX509Key is the path to the X509 key for the Raft server. May not be set. - NodeX509Key string `filepath:"true"` - - // NoNodeVerify disables checking other nodes' Node X509 certs for validity. - NoNodeVerify bool - - // NodeVerifyClient enable mutual TLS for node-to-node communication. - NodeVerifyClient bool - - // NodeVerifyServerName is the hostname to verify on the certificates returned by nodes. - // If NoNodeVerify is true this field is ignored. - NodeVerifyServerName string - - // NodeID is the Raft ID for the node. - NodeID string - - // RaftAddr is the bind network address for the Raft server. - RaftAddr string - - // RaftAdv is the advertised Raft server address. - RaftAdv string - - // JoinAddrs is the list of Raft addresses to use for a join attempt. - JoinAddrs string - - // JoinAttempts is the number of times a node should attempt to join using a - // given address. - JoinAttempts int - - // JoinInterval is the time between retrying failed join operations. - JoinInterval time.Duration - - // JoinAs sets the user join attempts should be performed as. May not be set. - JoinAs string - - // BootstrapExpect is the minimum number of nodes required for a bootstrap. - BootstrapExpect int - - // BootstrapExpectTimeout is the maximum time a bootstrap operation can take. - BootstrapExpectTimeout time.Duration - - // DiscoMode sets the discovery mode. May not be set. - DiscoMode string - - // DiscoKey sets the discovery prefix key. - DiscoKey string - - // DiscoConfig sets the path to any discovery configuration file. May not be set. - DiscoConfig string - - // OnDiskPath sets the path to the SQLite file. May not be set. - OnDiskPath string - - // FKConstraints enables SQLite foreign key constraints. - FKConstraints bool - - // AutoVacInterval sets the automatic VACUUM interval. Use 0s to disable. - AutoVacInterval time.Duration - - // AutoOptimizeInterval sets the automatic optimization interval. Use 0s to disable. - AutoOptimizeInterval time.Duration - - // RaftLogLevel sets the minimum logging level for the Raft subsystem. - RaftLogLevel string - - // RaftNonVoter controls whether this node is a voting, read-only node. - RaftNonVoter bool - - // RaftSnapThreshold is the number of outstanding log entries that trigger snapshot. - RaftSnapThreshold uint64 - - // RaftSnapThreshold is the size of a SQLite WAL file which will trigger a snapshot. - RaftSnapThresholdWALSize uint64 - - // RaftSnapInterval sets the threshold check interval. - RaftSnapInterval time.Duration - - // RaftLeaderLeaseTimeout sets the leader lease timeout. - RaftLeaderLeaseTimeout time.Duration - - // RaftHeartbeatTimeout specifies the time in follower state without contact - // from a Leader before the node attempts an election. - RaftHeartbeatTimeout time.Duration - - // RaftElectionTimeout specifies the time in candidate state without contact - // from a Leader before the node attempts an election. - RaftElectionTimeout time.Duration - - // RaftApplyTimeout sets the Log-apply timeout. - RaftApplyTimeout time.Duration - - // RaftShutdownOnRemove sets whether Raft should be shutdown if the node is removed - RaftShutdownOnRemove bool - - // RaftClusterRemoveOnShutdown sets whether the node should remove itself from the cluster on shutdown - RaftClusterRemoveOnShutdown bool - - // RaftStepdownOnShutdown sets whether Leadership should be relinquished on shutdown - RaftStepdownOnShutdown bool - - // RaftReapNodeTimeout sets the duration after which a non-reachable voting node is - // reaped i.e. removed from the cluster. - RaftReapNodeTimeout time.Duration - - // RaftReapReadOnlyNodeTimeout sets the duration after which a non-reachable non-voting node is - // reaped i.e. removed from the cluster. - RaftReapReadOnlyNodeTimeout time.Duration - - // ClusterConnectTimeout sets the timeout when initially connecting to another node in - // the cluster, for non-Raft communications. - ClusterConnectTimeout time.Duration - - // WriteQueueCap is the default capacity of Execute queues - WriteQueueCap int - - // WriteQueueBatchSz is the default batch size for Execute queues - WriteQueueBatchSz int - - // WriteQueueTimeout is the default time after which any data will be sent on - // Execute queues, if a batch size has not been reached. - WriteQueueTimeout time.Duration - - // WriteQueueTx controls whether writes from the queue are done within a transaction. - WriteQueueTx bool - - // CPUProfile enables CPU profiling. - CPUProfile string - - // MemProfile enables memory profiling. - MemProfile string - - // TraceProfile enables trace profiling. - TraceProfile string -} - -// Validate checks the configuration for internal consistency, and activates -// important rqlite policies. It must be called at least once on a Config -// object before the Config object is used. It is OK to call more than -// once. -func (c *Config) Validate() error { - dataPath, err := filepath.Abs(c.DataPath) - if err != nil { - return fmt.Errorf("failed to determine absolute data path: %s", err.Error()) - } - c.DataPath = dataPath - - err = c.CheckFilePaths() - if err != nil { - return err - } - - err = c.CheckDirPaths() - if err != nil { - return err - } - - if len(c.ExtensionPaths) > 0 { - for _, p := range c.ExtensionPaths { - if !fileExists(p) { - return fmt.Errorf("extension path does not exist: %s", p) - } - } - } - - if !bothUnsetSet(c.HTTPx509Cert, c.HTTPx509Key) { - return fmt.Errorf("either both -%s and -%s must be set, or neither", HTTPx509CertFlag, HTTPx509KeyFlag) - } - if !bothUnsetSet(c.NodeX509Cert, c.NodeX509Key) { - return fmt.Errorf("either both -%s and -%s must be set, or neither", NodeX509CertFlag, NodeX509KeyFlag) - - } - - if c.RaftAddr == c.HTTPAddr { - return errors.New("HTTP and Raft addresses must differ") - } - - // Enforce policies regarding addresses - if c.RaftAdv == "" { - c.RaftAdv = c.RaftAddr - } - if c.HTTPAdv == "" { - c.HTTPAdv = c.HTTPAddr - } - - // Node ID policy - if c.NodeID == "" { - c.NodeID = c.RaftAdv - } - - // Perform some address validity checks. - if strings.HasPrefix(strings.ToLower(c.HTTPAddr), "http") || - strings.HasPrefix(strings.ToLower(c.HTTPAdv), "http") { - return errors.New("HTTP options should not include protocol (http:// or https://)") - } - if _, _, err := net.SplitHostPort(c.HTTPAddr); err != nil { - return errors.New("HTTP bind address not valid") - } - - hadv, _, err := net.SplitHostPort(c.HTTPAdv) - if err != nil { - return errors.New("HTTP advertised HTTP address not valid") - } - if addr := net.ParseIP(hadv); addr != nil && addr.IsUnspecified() { - return fmt.Errorf("advertised HTTP address is not routable (%s), specify it via -%s or -%s", - hadv, HTTPAddrFlag, HTTPAdvAddrFlag) - } - - if _, rp, err := net.SplitHostPort(c.RaftAddr); err != nil { - return errors.New("raft bind address not valid") - } else if _, err := strconv.Atoi(rp); err != nil { - return errors.New("raft bind port not valid") - } - - radv, rp, err := net.SplitHostPort(c.RaftAdv) - if err != nil { - return errors.New("raft advertised address not valid") - } - if addr := net.ParseIP(radv); addr != nil && addr.IsUnspecified() { - return fmt.Errorf("advertised Raft address is not routable (%s), specify it via -%s or -%s", - radv, RaftAddrFlag, RaftAdvAddrFlag) - } - if _, err := strconv.Atoi(rp); err != nil { - return errors.New("raft advertised port is not valid") - } - - if c.RaftAdv == c.HTTPAdv { - return errors.New("advertised HTTP and Raft addresses must differ") - } - - // Enforce bootstrapping policies - if c.BootstrapExpect > 0 && c.RaftNonVoter { - return errors.New("bootstrapping only applicable to voting nodes") - } - - // Join parameters OK? - if c.JoinAddrs != "" { - addrs := strings.Split(c.JoinAddrs, ",") - for i := range addrs { - if _, _, err := net.SplitHostPort(addrs[i]); err != nil { - return fmt.Errorf("%s is an invalid join address", addrs[i]) - } - - if c.BootstrapExpect == 0 { - if addrs[i] == c.RaftAdv || addrs[i] == c.RaftAddr { - return errors.New("node cannot join with itself unless bootstrapping") - } - if c.AutoRestoreFile != "" { - return errors.New("auto-restoring cannot be used when joining a cluster") - } - } - } - - if c.DiscoMode != "" { - return errors.New("disco mode cannot be used when also explicitly joining a cluster") - } - } - - // Valid disco mode? - switch c.DiscoMode { - case "": - case DiscoModeEtcdKV, DiscoModeConsulKV: - if c.BootstrapExpect > 0 { - return fmt.Errorf("bootstrapping not applicable when using %s", c.DiscoMode) - } - case DiscoModeDNS, DiscoModeDNSSRV: - if c.BootstrapExpect == 0 && !c.RaftNonVoter { - return fmt.Errorf("bootstrap-expect value required when using %s with a voting node", c.DiscoMode) - } - default: - return fmt.Errorf("disco mode must be one of %s, %s, %s, or %s", - DiscoModeConsulKV, DiscoModeEtcdKV, DiscoModeDNS, DiscoModeDNSSRV) - } - - return nil -} - -// JoinAddresses returns the join addresses set at the command line. Returns nil -// if no join addresses were set. -func (c *Config) JoinAddresses() []string { - if c.JoinAddrs == "" { - return nil - } - return strings.Split(c.JoinAddrs, ",") -} - -// HTTPURL returns the fully-formed, advertised HTTP API address for this config, including -// protocol, host and port. -func (c *Config) HTTPURL() string { - apiProto := "http" - if c.HTTPx509Cert != "" { - apiProto = "https" - } - return fmt.Sprintf("%s://%s", apiProto, c.HTTPAdv) -} - -// RaftPort returns the port on which the Raft system is listening. Validate must -// have been called before calling this method. -func (c *Config) RaftPort() int { - _, port, err := net.SplitHostPort(c.RaftAddr) - if err != nil { - panic("RaftAddr not valid") - } - p, err := strconv.Atoi(port) - if err != nil { - panic("RaftAddr port not valid") - } - return p -} - -// DiscoConfigReader returns a ReadCloser providing access to the Disco config. -// The caller must call close on the ReadCloser when finished with it. If no -// config was supplied, it returns nil. -func (c *Config) DiscoConfigReader() io.ReadCloser { - var rc io.ReadCloser - if c.DiscoConfig == "" { - return nil - } - - // Open config file. If opening fails, assume string is the literal config. - cfgFile, err := os.Open(c.DiscoConfig) - if err != nil { - rc = io.NopCloser(bytes.NewReader([]byte(c.DiscoConfig))) - } else { - rc = cfgFile - } - return rc -} - -// CheckFilePaths checks that all file paths in the config exist. -// Empty filepaths are ignored. -func (c *Config) CheckFilePaths() error { - v := reflect.ValueOf(c).Elem() - - // Iterate through the fields of the struct - for i := 0; i < v.NumField(); i++ { - field := v.Type().Field(i) - fieldValue := v.Field(i) - - if fieldValue.Kind() != reflect.String { - continue - } - - if tagValue, ok := field.Tag.Lookup("filepath"); ok && tagValue == "true" { - filePath := fieldValue.String() - if filePath == "" { - continue - } - if !fileExists(filePath) { - return fmt.Errorf("%s does not exist", filePath) - } - } - } - return nil -} - -// CheckDirPaths checks that all directory paths in the config exist and are directories. -// Empty directory paths are ignored. -func (c *Config) CheckDirPaths() error { - v := reflect.ValueOf(c).Elem() - - // Iterate through the fields of the struct - for i := 0; i < v.NumField(); i++ { - field := v.Type().Field(i) - fieldValue := v.Field(i) - - if fieldValue.Kind() != reflect.String { - continue - } - - if tagValue, ok := field.Tag.Lookup("dirpath"); ok && tagValue == "true" { - dirPath := fieldValue.String() - if dirPath == "" { - continue - } - if !fileExists(dirPath) { - return fmt.Errorf("%s does not exist", dirPath) - } - if !isDir(dirPath) { - return fmt.Errorf("%s is not a directory", dirPath) - } - } - } - return nil -} - // BuildInfo is build information for display at command line. type BuildInfo struct { Version string @@ -601,24 +160,6 @@ func errorExit(code int, msg string) { os.Exit(code) } -// bothUnsetSet returns true if both a and b are unset, or both are set. -func bothUnsetSet(a, b string) bool { - return (a == "" && b == "") || (a != "" && b != "") -} - -func fileExists(path string) bool { - _, err := os.Stat(path) - return err == nil -} - -func isDir(path string) bool { - fi, err := os.Stat(path) - if err != nil { - return false - } - return fi.IsDir() -} - func mustParseDuration(d string) time.Duration { td, err := time.ParseDuration(d) if err != nil { diff --git a/service/rqlite/goose_store/store.go b/service/rqlite/goose_store/store.go index fe24607..5095a9c 100644 --- a/service/rqlite/goose_store/store.go +++ b/service/rqlite/goose_store/store.go @@ -3,7 +3,6 @@ package goose_store import ( "context" "database/sql" - "fmt" "isp-config-service/repository" @@ -33,7 +32,7 @@ func (s Store) CreateVersionTable(ctx context.Context, db database.DBTxConn) err q := s.querier.CreateTable(s.tablename) _, err := s.db.ExecContext(ctx, q) if err != nil { - return fmt.Errorf("failed to create version table %q: %w", s.tablename, err) + return errors.WithMessagef(err, "failed to create version table %q", s.tablename) } return nil } @@ -42,7 +41,7 @@ func (s Store) Insert(ctx context.Context, db database.DBTxConn, req database.In q := s.querier.InsertVersion(s.tablename) _, err := s.db.ExecContext(ctx, q, req.Version, true) if err != nil { - return fmt.Errorf("failed to insert version %d: %w", req.Version, err) + return errors.WithMessagef(err, "failed to insert version %d", req.Version) } return nil } @@ -51,7 +50,7 @@ func (s Store) Delete(ctx context.Context, db database.DBTxConn, version int64) q := s.querier.DeleteVersion(s.tablename) _, err := s.db.ExecContext(ctx, q, version) if err != nil { - return fmt.Errorf("failed to delete version %d: %w", version, err) + return errors.WithMessagef(err, "failed to delete version %d", version) } return nil } @@ -63,10 +62,10 @@ func (s Store) GetMigration(ctx context.Context, db database.DBTxConn, version i isApplied := float64(0) err := s.db.QueryRowContext(ctx, q, version).Scan(&result.Timestamp, &isApplied) if errors.Is(err, sql.ErrNoRows) { - return nil, fmt.Errorf("%w: %d", database.ErrVersionNotFound, version) + return nil, errors.WithMessagef(database.ErrVersionNotFound, "%d", version) } if err != nil { - return nil, fmt.Errorf("failed to get migration %d: %w", version, err) + return nil, errors.WithMessagef(err, "failed to get migration %d", version) } result.IsApplied = isApplied == 0 return &result, nil @@ -80,7 +79,7 @@ func (s Store) ListMigrations(ctx context.Context, db database.DBTxConn) ([]*dat q := s.querier.ListMigrations(s.tablename) rows, err := s.db.QueryContext(ctx, q) if err != nil { - return nil, fmt.Errorf("failed to list migrations: %w", err) + return nil, errors.WithMessage(err, "failed to list migrations") } defer rows.Close() @@ -91,7 +90,7 @@ func (s Store) ListMigrations(ctx context.Context, db database.DBTxConn) ([]*dat version := float64(0) err = rows.Scan(&version, &isApplied) if err != nil { - return nil, fmt.Errorf("failed to scan list migrations result: %w", err) + return nil, errors.WithMessage(err, "failed to scan list migrations result") } result.IsApplied = isApplied == 0 result.Version = int64(version) diff --git a/service/rqlite/internal/rarchive/gzip.go b/service/rqlite/internal/rarchive/gzip.go new file mode 100644 index 0000000..b68bf4f --- /dev/null +++ b/service/rqlite/internal/rarchive/gzip.go @@ -0,0 +1,65 @@ +// nolint +package rarchive + +import ( + "compress/gzip" + "io" + "os" +) + +// Gzip compresses the given file and returns the path to the +// compressed file. It is the caller's responsibility to remove +// the compressed file when it is no longer needed. +func Gzip(file string) (string, error) { + f, err := os.Open(file) + if err != nil { + return "", err + } + defer f.Close() + + tmpFd, err := os.CreateTemp("", "gzip") + if err != nil { + return "", err + } + + gz := gzip.NewWriter(tmpFd) + _, err = io.Copy(gz, f) + if err != nil { + return "", err + } + + err = gz.Close() + if err != nil { + return "", err + } + return tmpFd.Name(), nil +} + +// Gunzip decompresses the given GZIP file and returns the +// path to the decompressed file. It is the caller's responsibility +// to remove the decompressed file when it is no longer needed. +func Gunzip(file string) (string, error) { + f, err := os.Open(file) + if err != nil { + return "", err + } + defer f.Close() + + gz, err := gzip.NewReader(f) + if err != nil { + return "", err + } + defer gz.Close() + + tmpFd, err := os.CreateTemp("", "gunzip") + if err != nil { + return "", err + } + defer tmpFd.Close() + + _, err = io.Copy(tmpFd, gz) + if err != nil { + return "", err + } + return tmpFd.Name(), nil +} diff --git a/service/rqlite/internal/rarchive/targz.go b/service/rqlite/internal/rarchive/targz.go new file mode 100644 index 0000000..a8b4ebf --- /dev/null +++ b/service/rqlite/internal/rarchive/targz.go @@ -0,0 +1,137 @@ +// nolint +package rarchive + +import ( + "archive/tar" + "compress/gzip" + "errors" + "io" + "os" + "path/filepath" + "strings" +) + +// IsTarGzipFile checks if the file at the given path is a gzipped tarball +// by attempting to open it as such. +func IsTarGzipFile(path string) bool { + f, err := os.Open(path) + if err != nil { + return false + } + defer f.Close() + + // Attempt to create a gzip reader + gzr, err := gzip.NewReader(f) + if err != nil { + return false + } + defer gzr.Close() + + return true +} + +// TarGzipHasSubdirectories checks if the gzipped tarball contains any entries that +// represent subdirectories or files within subdirectories. +func TarGzipHasSubdirectories(path string) (bool, error) { + // Open the tar.gz file + file, err := os.Open(path) + if err != nil { + return false, err + } + defer file.Close() + + gzr, err := gzip.NewReader(file) + if err != nil { + return false, err + } + defer gzr.Close() + + tr := tar.NewReader(gzr) + + // Iterate through each file in the tar archive + for { + header, err := tr.Next() + if err == io.EOF { + break // End of tar archive + } + if err != nil { + return false, err + } + + // Check if the file is a directory or if the file path includes a subdirectory + if header.Typeflag == tar.TypeDir || + strings.Contains(header.Name, "/") || strings.Contains(header.Name, "\\") { + return true, nil + } + } + return false, nil +} + +// UntarGzipToDir decompresses the gzipped tarball at the given path into the specified directory. +func UntarGzipToDir(path, dir string) error { + // Open the tar.gz file + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + gzr, err := gzip.NewReader(file) + if err != nil { + return err + } + defer gzr.Close() + + tr := tar.NewReader(gzr) + + // Ensure the output directory exists + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + + // Iterate through each file in the tar archive + for { + header, err := tr.Next() + if err == io.EOF { + break // End of tar archive + } + if err != nil { + return err + } + + // Construct the full path for the file + fpath := filepath.Join(dir, header.Name) + + // Check for directory traversal vulnerability + if !strings.HasPrefix(fpath, filepath.Clean(dir)+string(os.PathSeparator)) { + return errors.New("invalid file path") + } + + if header.Typeflag == tar.TypeDir { + // Create the directory + if err := os.MkdirAll(fpath, os.FileMode(header.Mode)); err != nil { + return err + } + } else { + // Create the file + if err := os.MkdirAll(filepath.Dir(fpath), os.FileMode(header.Mode)); err != nil { + return err + } + + outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode)) + if err != nil { + return err + } + + // Copy the file content to the destination + if _, err := io.Copy(outFile, tr); err != nil { + outFile.Close() + return err + } + + outFile.Close() + } + } + + return nil +} diff --git a/service/rqlite/internal/rarchive/zip.go b/service/rqlite/internal/rarchive/zip.go new file mode 100644 index 0000000..51b613b --- /dev/null +++ b/service/rqlite/internal/rarchive/zip.go @@ -0,0 +1,113 @@ +// nolint +package rarchive + +import ( + "archive/zip" + "bytes" + "errors" + "io" + "os" + "path/filepath" + "strings" +) + +// IsZipFile checks if the file at the given path is a ZIP file +// by verifying the magic number (the first few bytes of the file). +func IsZipFile(path string) bool { + f, err := os.Open(path) + if err != nil { + return false + } + defer f.Close() + + // Read the first 4 bytes of the file to check the magic number + buf := make([]byte, 4) + _, err = f.Read(buf) + if err != nil { + return false + } + + // ZIP files start with "PK\x03\x04" + return bytes.Equal(buf, []byte("PK\x03\x04")) +} + +// ZipHasSubdirectories checks if the ZIP file contains any entries that +// represent subdirectories or files within subdirectories. +func ZipHasSubdirectories(path string) (bool, error) { + // Open the ZIP file + r, err := zip.OpenReader(path) + if err != nil { + return false, err + } + defer r.Close() + + // Iterate through each file in the ZIP archive + for _, f := range r.File { + if f.FileInfo().IsDir() || + len(f.Name) > 0 && (f.Name[len(f.Name)-1] == '/' || + len(f.Name) > 0 && f.Name != filepath.Base(f.Name)) { + return true, nil + } + } + return false, nil +} + +// UnzipToDir decompresses the ZIP file at the given path into the specified directory. +func UnzipToDir(path, dir string) error { + // Open the ZIP file + r, err := zip.OpenReader(path) + if err != nil { + return err + } + defer r.Close() + + // Ensure the output directory exists + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + + // Iterate through each file in the ZIP archive + for _, f := range r.File { + // Construct the full path for the file + fpath := filepath.Join(dir, f.Name) + + // Check for directory traversal vulnerability + if !strings.HasPrefix(fpath, filepath.Clean(dir)+string(os.PathSeparator)) { + return errors.New("invalid file path") + } + + if f.FileInfo().IsDir() { + // Create the directory + if err := os.MkdirAll(fpath, f.Mode()); err != nil { + return err + } + } else { + // Create the file + if err := os.MkdirAll(filepath.Dir(fpath), f.Mode()); err != nil { + return err + } + + outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) + if err != nil { + return err + } + + rc, err := f.Open() + if err != nil { + return err + } + + _, err = io.Copy(outFile, rc) + + // Close the file handles + outFile.Close() + rc.Close() + + if err != nil { + return err + } + } + } + + return nil +} diff --git a/service/rqlite/internal/rtls/certs.go b/service/rqlite/internal/rtls/certs.go new file mode 100644 index 0000000..80bee43 --- /dev/null +++ b/service/rqlite/internal/rtls/certs.go @@ -0,0 +1,196 @@ +// nolint +package rtls + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net" + "time" +) + +// GenerateCACert generates a new CA certificate and returns the cert and key as PEM-encoded bytes. +func GenerateCACert(subject pkix.Name, validFor time.Duration, keySize int) ([]byte, []byte, error) { + // generate a new private key + key, err := rsa.GenerateKey(rand.Reader, keySize) + if err != nil { + return nil, nil, err + } + + // generate a new certificate + template := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: subject, + NotBefore: time.Now(), + NotAfter: time.Now().Add(validFor), + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, + IsCA: true, + BasicConstraintsValid: true, + } + + // generate a new certificate + cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) + if err != nil { + return nil, nil, err + } + + // encode the certificate and private key + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) + + return certPEM, keyPEM, nil +} + +// GenerateCert generates a new x509 certificate and returns the cert and key as PEM-encoded bytes. +// The function should take in a subject, a validity period, and a key size. It should optionally +// take in a parent certificate and key. If a parent certificate and key are provided, the new +// certificate should be signed by the parent. If no parent certificate and key are provided, +// the new certificate should be self-signed. +func GenerateCert(subject pkix.Name, validFor time.Duration, keySize int, parent *x509.Certificate, parentKey any) ([]byte, []byte, error) { + // generate a new private key + key, err := rsa.GenerateKey(rand.Reader, keySize) + if err != nil { + return nil, nil, err + } + + // generate a new certificate + template := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: subject, + NotBefore: time.Now(), + NotAfter: time.Now().Add(validFor), + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, + } + + signerCert := parent + signerKey := parentKey + if signerCert == nil { + signerCert = &template + signerKey = key + } + cert, err := x509.CreateCertificate(rand.Reader, &template, signerCert, &key.PublicKey, signerKey) + if err != nil { + return nil, nil, err + } + + // encode the certificate and private key + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) + + return certPEM, keyPEM, nil +} + +func GenerateCertIPSAN(subject pkix.Name, validFor time.Duration, keySize int, parent *x509.Certificate, parentKey any, san net.IP) ([]byte, []byte, error) { + // generate a new private key + key, err := rsa.GenerateKey(rand.Reader, keySize) + if err != nil { + return nil, nil, err + } + + // generate a new certificate + template := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: subject, + NotBefore: time.Now(), + NotAfter: time.Now().Add(validFor), + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, + } + + // generate cert template for new certificate suitable for client verification + + // Add IP SAN to the certificate + template.IPAddresses = append(template.IPAddresses, san) + + signerCert := parent + signerKey := parentKey + if signerCert == nil { + signerCert = &template + signerKey = key + } + cert, err := x509.CreateCertificate(rand.Reader, &template, signerCert, &key.PublicKey, signerKey) + if err != nil { + return nil, nil, err + } + + // encode the certificate and private key + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) + + return certPEM, keyPEM, nil +} + +// GenerateSelfSignedCert generates a new self-signed certificate and +// returns the cert and key as PEM-encoded bytes. +func GenerateSelfSignedCert(subject pkix.Name, validFor time.Duration, keySize int) ([]byte, []byte, error) { + // generate a new private key + key, err := rsa.GenerateKey(rand.Reader, keySize) + if err != nil { + return nil, nil, err + } + + // generate a new certificate + template := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: subject, + NotBefore: time.Now(), + NotAfter: time.Now().Add(validFor), + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + IsCA: true, + BasicConstraintsValid: true, + } + + // Add IP SAN to the certificate + //template.IPAddresses = append(template.IPAddresses, net.ParseIP("127.0.0.1")) + + cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) + if err != nil { + return nil, nil, err + } + + // encode the certificate and private key + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) + + return certPEM, keyPEM, nil +} + +// GenerateSelfSignedCertIPSAN generates a new self-signed certificate and +// returns the cert and key as PEM-encoded bytes. +func GenerateSelfSignedCertIPSAN(subject pkix.Name, validFor time.Duration, keySize int, san net.IP) ([]byte, []byte, error) { + // generate a new private key + key, err := rsa.GenerateKey(rand.Reader, keySize) + if err != nil { + return nil, nil, err + } + + // generate a new certificate + template := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: subject, + NotBefore: time.Now(), + NotAfter: time.Now().Add(validFor), + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + IsCA: true, + BasicConstraintsValid: true, + } + template.IPAddresses = append(template.IPAddresses, san) + + cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) + if err != nil { + return nil, nil, err + } + + // encode the certificate and private key + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) + + return certPEM, keyPEM, nil +} diff --git a/service/rqlite/internal/rtls/config.go b/service/rqlite/internal/rtls/config.go new file mode 100644 index 0000000..5a27ea7 --- /dev/null +++ b/service/rqlite/internal/rtls/config.go @@ -0,0 +1,139 @@ +// rtls is for creating TLS configurations for use by servers and clients. +// nolint +package rtls + +import ( + "crypto/tls" + "crypto/x509" + "os" + + "github.com/pkg/errors" +) + +const ( + NoCACert = "" + NoServerName = "" +) + +// MTLSState indicates whether mutual TLS is enabled or disabled. +type MTLSState tls.ClientAuthType + +const ( + MTLSStateDisabled MTLSState = MTLSState(tls.NoClientCert) + MTLSStateEnabled MTLSState = MTLSState(tls.RequireAndVerifyClientCert) +) + +// CreateClientConfig creates a new tls.Config for use by a client. The certFile and keyFile +// parameters are the paths to the client's certificate and key files, which will be used to +// authenticate the client to the server if mutual TLS is active. The caCertFile parameter +// is the path to the CA certificate file, which the client will use to verify any certificate +// presented by the server. serverName can also be set, informing the client which hostname +// should appear in the returned certificate. If noverify is true, the client will not verify +// the server's certificate. +func CreateClientConfig(certFile, keyFile, caCertFile, serverName string, noverify bool) (*tls.Config, error) { + var err error + + config := createBaseTLSConfig(serverName, noverify) + if certFile != "" && keyFile != "" { + config.Certificates = make([]tls.Certificate, 1) + config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, err + } + } + if caCertFile != "" { + if err := setCertPool(caCertFile, &config.RootCAs); err != nil { + return nil, err + } + } + return config, nil +} + +// CreateClientConfigWithFunc creates a new tls.Config for use by a client. The certFunc +// parameter is a function that returns the client's certificate and key. The caCertFile +// parameter is the path to the CA certificate file, which the client will use to verify +// any certificate presented by the server. serverName can also be set, informing the client +// which hostname should appear in the returned certificate. If noverify is true, the client +// will not verify the server's certificate. +func CreateClientConfigWithFunc(certFunc func() (*tls.Certificate, error), caCertFile, serverName string, noverify bool) (*tls.Config, error) { + config := createBaseTLSConfig(serverName, noverify) + if certFunc != nil { + config.GetClientCertificate = func(hello *tls.CertificateRequestInfo) (*tls.Certificate, error) { + return certFunc() + } + } + if caCertFile != "" { + if err := setCertPool(caCertFile, &config.RootCAs); err != nil { + return nil, err + } + } + return config, nil +} + +// CreateServerConfig creates a new tls.Config for use by a server. The certFile and keyFile +// parameters are the paths to the server's certificate and key files, which will be used to +// authenticate the server to the client. The caCertFile parameter is the path to the CA +// certificate file, which the server will use to verify any certificate presented by the +// client. If mtls is MTLSStateEnabled, the server will require the client to present a +// valid certificate. +func CreateServerConfig(certFile, keyFile, caCertFile string, mtls MTLSState) (*tls.Config, error) { + var err error + + config := createBaseTLSConfig(NoServerName, false) + config.Certificates = make([]tls.Certificate, 1) + config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, err + } + if caCertFile != "" { + if err := setCertPool(caCertFile, &config.ClientCAs); err != nil { + return nil, err + } + } + config.ClientAuth = tls.ClientAuthType(mtls) + return config, nil +} + +// CreateServerConfigWithFunc creates a new tls.Config for use by a server. The certFunc +// parameter is a function that returns the server's certificate and key. The caCertFile +// parameter is the path to the CA certificate file, which the server will use to verify +// any certificate presented by the client. If mtls is MTLSStateEnabled, the server will +// require the client to present a valid certificate. +func CreateServerConfigWithFunc(certFunc func() (*tls.Certificate, error), caCertFile string, mtls MTLSState) (*tls.Config, error) { + config := createBaseTLSConfig(NoServerName, false) + config.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { + return certFunc() + } + if caCertFile != "" { + if err := setCertPool(caCertFile, &config.ClientCAs); err != nil { + return nil, err + } + } + config.ClientAuth = tls.ClientAuthType(mtls) + return config, nil +} + +func createBaseTLSConfig(serverName string, noverify bool) *tls.Config { + return &tls.Config{ + ServerName: serverName, + InsecureSkipVerify: noverify, + NextProtos: []string{"h2", "http/1.1"}, + MinVersion: uint16(tls.VersionTLS12), + } +} + +// setCertPool sets the CA certificate pool for the given file. It reads the file and +// appends the certificates to the pool. If the file cannot be read or the certificates +// cannot be appended, it returns an error. +func setCertPool(caCertFile string, pool **x509.CertPool) error { + asn1Data, err := os.ReadFile(caCertFile) + if err != nil { + return err + } + *pool = x509.NewCertPool() + ok := (*pool).AppendCertsFromPEM(asn1Data) + if !ok { + return errors.Errorf("failed to load CA certificate(s) for verification in %q", caCertFile) + } + return nil +} diff --git a/service/rqlite/internal/rtls/reloader.go b/service/rqlite/internal/rtls/reloader.go new file mode 100644 index 0000000..7e17049 --- /dev/null +++ b/service/rqlite/internal/rtls/reloader.go @@ -0,0 +1,110 @@ +// nolint +package rtls + +import ( + "crypto/tls" + "log" + "os" + "sync" + "time" +) + +// CertReloader is a simple TLS certificate reloader. It loads the certificate +// and key files from the specified paths and reloads them if they have been +// modified since the last load. +type CertReloader struct { + certPath, keyPath string + modTime time.Time + logger *log.Logger + + mu sync.RWMutex + cert *tls.Certificate +} + +// NewCertReloader creates a new CertReloader instance. +func NewCertReloader(cert, key string) (*CertReloader, error) { + cr := &CertReloader{ + certPath: cert, + keyPath: key, + logger: log.New(os.Stderr, "[cert-reloader] ", log.LstdFlags), + } + pair, err := loadKeyPair(cr.certPath, cr.keyPath) + if err != nil { + return nil, err + } + cr.cert = &pair + latestTime, err := latestModTime(cr.certPath, cr.keyPath) + if err != nil { + return nil, err + } + cr.modTime = latestTime + return cr, nil +} + +// GetCertificate returns the current certificate. It reloads the certificate +// if it has been modified since the last load. GetCertificate is thread-safe +// and if the cert has not changed this function will execute concurrently with +// other GetCertificate calls. +func (cr *CertReloader) GetCertificate() (*tls.Certificate, error) { + cr.mu.RLock() + latestTime, err := latestModTime(cr.certPath, cr.keyPath) + if err != nil || !latestTime.After(cr.modTime) { + defer cr.mu.RUnlock() + if err != nil { + cr.logger.Printf("failed to get latest modification time (%s), returning prior cert", err) + } + return cr.cert, nil + } + + // The certificate or key file has changed, we need to reload. First we release + // the read lock, then we acquire a write lock to reload the certificate. + cr.mu.RUnlock() + cr.mu.Lock() + defer cr.mu.Unlock() + + // Now that we have the write lock, we check again if the certificate has actually + // been updated by another concurrent call to this function. + latestTime, err = latestModTime(cr.certPath, cr.keyPath) + if err != nil || !latestTime.After(cr.modTime) { + if err != nil { + cr.logger.Printf("failed to get latest modification time (%s), returning prior cert", err) + } + return cr.cert, nil + } + + pair, err := loadKeyPair(cr.certPath, cr.keyPath) + if err != nil { + cr.logger.Printf("failed to reload certificate (%s), returning prior cert", err) + return cr.cert, nil + } + cr.logger.Printf("reloading certificate at %s and key at %s", cr.certPath, cr.keyPath) + cr.cert = &pair + cr.modTime = latestTime + return cr.cert, nil +} + +// loadKeyPair loads a TLS certificate and key pair from the given files. +// It simply wraps tls.LoadX509KeyPair, ensuring that the rest of the code +// uses the same function to load the key pair. +func loadKeyPair(certFile, keyFile string) (tls.Certificate, error) { + return tls.LoadX509KeyPair(certFile, keyFile) +} + +// latestModTime returns the latest modification time of the given files. +// It returns os.ErrNotExist if no files are provided. +func latestModTime(file ...string) (time.Time, error) { + if len(file) == 0 { + return time.Time{}, os.ErrNotExist + } + var latest time.Time + for _, f := range file { + info, err := os.Stat(f) + if err != nil { + return time.Time{}, err + } + if info.ModTime().After(latest) { + latest = info.ModTime() + } + } + return latest, nil +} diff --git a/service/rqlite/main.go b/service/rqlite/main.go index d31557b..f6537f4 100644 --- a/service/rqlite/main.go +++ b/service/rqlite/main.go @@ -16,21 +16,22 @@ import ( "strings" "time" + "isp-config-service/service/rqlite/internal/rarchive" + "isp-config-service/service/rqlite/internal/rtls" + "github.com/pkg/errors" "github.com/rqlite/rqlite-disco-clients/dns" "github.com/rqlite/rqlite-disco-clients/dnssrv" + "github.com/rqlite/rqlite/v9/auth" + "github.com/rqlite/rqlite/v9/auto/backup" + "github.com/rqlite/rqlite/v9/cluster" + "github.com/rqlite/rqlite/v9/cmd" + "github.com/rqlite/rqlite/v9/db" + "github.com/rqlite/rqlite/v9/db/extensions" + httpd "github.com/rqlite/rqlite/v9/http" + "github.com/rqlite/rqlite/v9/store" + "github.com/rqlite/rqlite/v9/tcp" "github.com/txix-open/isp-kit/config" - - "github.com/rqlite/rqlite/v8/auth" - "github.com/rqlite/rqlite/v8/cluster" - "github.com/rqlite/rqlite/v8/cmd" - "github.com/rqlite/rqlite/v8/db" - "github.com/rqlite/rqlite/v8/extensions" - httpd "github.com/rqlite/rqlite/v8/http" - "github.com/rqlite/rqlite/v8/rarchive" - "github.com/rqlite/rqlite/v8/rtls" - "github.com/rqlite/rqlite/v8/store" - "github.com/rqlite/rqlite/v8/tcp" ) const name = `rqlite` @@ -47,6 +48,7 @@ func init() { type localConfig struct { Rqlite *Config + Backup *Backup } func main(ctx context.Context, r *Rqlite) error { @@ -186,6 +188,15 @@ func main(ctx context.Context, r *Rqlite) error { h, p, _ := net.SplitHostPort(cfg.HTTPAdv) log.Printf("connect using the command-line tool via 'rqlite -H %s -p %s'", h, p) + // Start any requested auto-backups + backupSrv, err := startAutoBackups(mainCtx, localCfg.Backup, str) + if err != nil { + log.Fatalf("failed to start auto-backups: %s", err.Error()) + } + if backupSrv != nil { + httpServ.RegisterStatus("auto_backups", backupSrv) + } + // Block until done. <-mainCtx.Done() @@ -210,7 +221,7 @@ func main(ctx context.Context, r *Rqlite) error { log.Printf("stepping down as Leader before shutdown") } // Perform a stepdown, ignore any errors. - str.Stepdown(true) + str.Stepdown(true, "") } muxLn.Close() @@ -222,6 +233,26 @@ func main(ctx context.Context, r *Rqlite) error { return nil } +func startAutoBackups(ctx context.Context, cfg *Backup, str *store.Store) (*backup.Uploader, error) { + if !cfg.Enabled { + return nil, nil + } + + b, err := json.Marshal(cfg) + if err != nil { + return nil, errors.Errorf("failed to marshal auto-backup settings: %s", err.Error()) + } + + uCfg, sc, err := backup.NewStorageClient(b) + if err != nil { + return nil, errors.Errorf("failed to parse auto-backup file: %s", err.Error()) + } + provider := store.NewProvider(str, uCfg.Vacuum, !uCfg.NoCompress) + u := backup.NewUploader(sc, provider, time.Duration(uCfg.Interval)) + u.Start(ctx, str.IsLeader) + return u, nil +} + func evaluateAdvAddresses(cfg *config.Config) error { httpAdv := cfg.Optional().String("rqlite.HTTPAdv", "") shouldEvalHttp := strings.Contains(httpAdv, "$HOSTNAME") @@ -290,11 +321,11 @@ func createStore(cfg *Config, ln *tcp.Layer, extensions []string) (*store.Store, dbConf.FKConstraints = cfg.FKConstraints dbConf.Extensions = extensions - str := store.New(ln, &store.Config{ + str := store.New(&store.Config{ DBConf: dbConf, Dir: cfg.DataPath, ID: cfg.NodeID, - }) + }, ln) // Set optional parameters on store. str.RaftLogLevel = cfg.RaftLogLevel @@ -363,17 +394,17 @@ func startNodeMux(cfg *Config, ln net.Listener) (*tcp.Mux, error) { } if cfg.NodeVerifyClient { b.WriteString(", mutual TLS enabled") + mux, err = tcp.NewMutualTLSMux(ln, adv, cfg.NodeX509Cert, cfg.NodeX509Key, cfg.NodeX509CACert) } else { b.WriteString(", mutual TLS disabled") + mux, err = tcp.NewTLSMux(ln, adv, cfg.NodeX509Cert, cfg.NodeX509Key) } log.Println(b.String()) - mux, err = tcp.NewTLSMux(ln, adv, cfg.NodeX509Cert, cfg.NodeX509Key, cfg.NodeX509CACert, - cfg.NoNodeVerify, cfg.NodeVerifyClient) } else { mux, err = tcp.NewMux(ln, adv) } if err != nil { - return nil, fmt.Errorf("failed to create node-to-node mux: %s", err.Error()) + return nil, errors.Errorf("failed to create node-to-node mux: %s", err.Error()) } go mux.Serve() return mux, nil @@ -403,13 +434,13 @@ func createClusterClient(cfg *Config, clstr *cluster.Service) (*cluster.Client, dialerTLSConfig, err = rtls.CreateClientConfig(cfg.NodeX509Cert, cfg.NodeX509Key, cfg.NodeX509CACert, cfg.NodeVerifyServerName, cfg.NoNodeVerify) if err != nil { - return nil, fmt.Errorf("failed to create TLS config for cluster dialer: %s", err.Error()) + return nil, errors.Errorf("failed to create TLS config for cluster dialer: %s", err.Error()) } } clstrDialer := tcp.NewDialer(cluster.MuxClusterHeader, dialerTLSConfig) clstrClient := cluster.NewClient(clstrDialer, cfg.ClusterConnectTimeout) if err := clstrClient.SetLocal(cfg.RaftAdv, clstr); err != nil { - return nil, fmt.Errorf("failed to set cluster client local parameters: %s", err.Error()) + return nil, errors.Errorf("failed to set cluster client local parameters: %s", err.Error()) } return clstrClient, nil } @@ -422,13 +453,13 @@ func createCluster(ctx context.Context, cfg *Config, hasPeers bool, client *clus } if joins == nil && cfg.DiscoMode == "" && !hasPeers { if cfg.RaftNonVoter { - return fmt.Errorf("cannot create a new non-voting node without joining it to an existing cluster") + return errors.Errorf("cannot create a new non-voting node without joining it to an existing cluster") } // Brand new node, told to bootstrap itself. So do it. log.Println("bootstrapping single new node") if err := str.Bootstrap(store.NewServer(str.ID(), cfg.RaftAdv, true)); err != nil { - return fmt.Errorf("failed to bootstrap single new node: %s", err.Error()) + return errors.Errorf("failed to bootstrap single new node: %s", err.Error()) } return nil } @@ -446,7 +477,7 @@ func createCluster(ctx context.Context, cfg *Config, hasPeers bool, client *clus // Explicit join operation requested, so do it. j, err := joiner.Do(ctx, joins, str.ID(), cfg.RaftAdv, clusterSuf) if err != nil { - return fmt.Errorf("failed to join cluster: %s", err.Error()) + return errors.Errorf("failed to join cluster: %s", err.Error()) } log.Println("successfully joined cluster at", j) return nil @@ -485,14 +516,14 @@ func createCluster(ctx context.Context, cfg *Config, hasPeers bool, client *clus if cfg.DiscoMode == DiscoModeDNS { dnsCfg, err := dns.NewConfigFromReader(rc) if err != nil { - return fmt.Errorf("error reading DNS configuration: %s", err.Error()) + return errors.Errorf("error reading DNS configuration: %s", err.Error()) } provider = dns.NewWithPort(dnsCfg, cfg.RaftPort()) } else { dnssrvCfg, err := dnssrv.NewConfigFromReader(rc) if err != nil { - return fmt.Errorf("error reading DNS configuration: %s", err.Error()) + return errors.Errorf("error reading DNS configuration: %s", err.Error()) } provider = dnssrv.New(dnssrvCfg) } @@ -502,7 +533,7 @@ func createCluster(ctx context.Context, cfg *Config, hasPeers bool, client *clus httpServ.RegisterStatus("disco", provider) return bs.Boot(ctx, str.ID(), cfg.RaftAdv, clusterSuf, bootDoneFn, cfg.BootstrapExpectTimeout) default: - return fmt.Errorf("invalid disco mode %s", cfg.DiscoMode) + return errors.Errorf("invalid disco mode %s", cfg.DiscoMode) } } @@ -510,7 +541,7 @@ func networkCheckJoinAddrs(joinAddrs []string) error { if len(joinAddrs) > 0 { log.Println("checking that supplied join addresses don't serve HTTP(S)") if addr, ok := httpd.AnyServingHTTP(joinAddrs); ok { - return fmt.Errorf("join address %s appears to be serving HTTP when it should be Raft", addr) + return errors.Errorf("join address %s appears to be serving HTTP when it should be Raft", addr) } } return nil diff --git a/service/rqlite/runner.go b/service/rqlite/runner.go index 04935b1..033bc30 100644 --- a/service/rqlite/runner.go +++ b/service/rqlite/runner.go @@ -6,12 +6,12 @@ import ( "fmt" "time" - "github.com/rqlite/rqlite/v8/auth" + "github.com/rqlite/rqlite/v9/auth" "github.com/txix-open/isp-kit/http/httpcli" "github.com/pkg/errors" _ "github.com/rqlite/gorqlite/stdlib" - "github.com/rqlite/rqlite/v8/store" + "github.com/rqlite/rqlite/v9/store" "github.com/txix-open/isp-kit/config" ) diff --git a/service/startup/service.go b/service/startup/service.go index d184fba..02f4624 100644 --- a/service/startup/service.go +++ b/service/startup/service.go @@ -5,6 +5,13 @@ import ( "fmt" "time" + "isp-config-service/assembly" + "isp-config-service/conf" + "isp-config-service/middlewares" + "isp-config-service/service/rqlite" + "isp-config-service/service/rqlite/db" + "isp-config-service/service/rqlite/goose_store" + "github.com/pkg/errors" "github.com/pressly/goose/v3" "github.com/txix-open/isp-kit/app" @@ -17,12 +24,6 @@ import ( "github.com/txix-open/isp-kit/http/httpclix" "github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/observability/sentry" - "isp-config-service/assembly" - "isp-config-service/conf" - "isp-config-service/middlewares" - "isp-config-service/service/rqlite" - "isp-config-service/service/rqlite/db" - "isp-config-service/service/rqlite/goose_store" ) const ( @@ -35,7 +36,7 @@ type Service struct { rqlite *rqlite.Rqlite grpcSrv *grpc.Server httpSrv *http.Server - clusterCli *cluster.Client + clusterCli bootstrap.ClusterClient logger log.Logger // initialized in Run @@ -138,6 +139,10 @@ func (s *Service) Run(ctx context.Context) error { s.locatorConfig.CleanEventWorker.Run(ctx) s.locatorConfig.CleanPhantomBackendWorker.Run(ctx) + if cfg.Local.Backup.Enabled { + s.locatorConfig.CleanBackupsWorker.Run(ctx) + } + go func() { s.logger.Debug(ctx, fmt.Sprintf("starting grpc server on %s", s.boot.BindingAddress)) err := s.grpcSrv.ListenAndServe(s.boot.BindingAddress)