Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tls-min-version parameter #1103

Merged
merged 8 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

* Add new parameter to specify minimum TLS version [#1103](https://github.com/elastic/package-registry/pull/1103)
mrodm marked this conversation as resolved.
Show resolved Hide resolved

### Deprecated

### Known Issues
Expand Down
51 changes: 45 additions & 6 deletions flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,68 @@
package main

import (
"crypto/tls"
"errors"
"flag"
"fmt"
"os"
"strings"
)

func parseFlags() {
parseFlagSetWithArgs(flag.CommandLine, os.Args)
var supportedTLSVersions map[string]uint16 = map[string]uint16{
"1.0": tls.VersionTLS10,
"1.1": tls.VersionTLS11,
"1.2": tls.VersionTLS12,
"1.3": tls.VersionTLS13,
}

func parseFlagSetWithArgs(flagSet *flag.FlagSet, args []string) {
flagsFromEnv(flagSet)
type tlsMinVersionValue struct {
mrodm marked this conversation as resolved.
Show resolved Hide resolved
version *string
versionCode *uint16
}

func (t tlsMinVersionValue) String() string {
if t.version != nil {
return *t.version
}
return ""
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we store only the code in the value, we could have also a map here to convert it back to string.

Suggested change
func (t tlsMinVersionValue) String() string {
if t.version != nil {
return *t.version
}
return ""
}
func (t tlsMinVersionValue) String() string {
switch tlsMinVersionValue {
case tls.VersionTLS10:
return "1.0"
case tls.VersionTLS11:
return "1.1"
case tls.VersionTLS12:
return "1.2"
case tls.VersionTLS13:
return "1.3"
default:
return ""
}
}


func (t tlsMinVersionValue) Set(s string) error {
if _, ok := supportedTLSVersions[s]; !ok {
return fmt.Errorf("unsupported TLS version: %s", s)
}
*t.version = s
*t.versionCode = supportedTLSVersions[s]
return nil
}

func parseFlags() error {
return parseFlagSetWithArgs(flag.CommandLine, os.Args)
}

func parseFlagSetWithArgs(flagSet *flag.FlagSet, args []string) error {
err := flagsFromEnv(flagSet)
if err != nil {
return err
}

// Skip args[0] as flag.Parse() does.
flagSet.Parse(args[1:])
return nil
}

func flagsFromEnv(flagSet *flag.FlagSet) {
func flagsFromEnv(flagSet *flag.FlagSet) error {
var flagErrors error
flagSet.VisitAll(func(f *flag.Flag) {
envName := flagEnvName(f.Name)
if value, found := os.LookupEnv(envName); found {
f.Value.Set(value)
if err := f.Value.Set(value); err != nil {
flagErrors = errors.Join(flagErrors, fmt.Errorf("failed to set -%s: %v", f.Name, err))
}
Comment on lines +68 to +70
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously, a wrong value set in an Environment variable was not raising an error
For instance, this was not failing:

 $ EPR_FEATURE_STORAGE_INDEXER=aaddb ./package-registry`

And now, that same command would raise an error:

 $ EPR_FEATURE_STORAGE_INDEXER=aaddb ./package-registry 
2023/10/25 18:29:20 failed to set -feature-storage-indexer: parse error

}
})
return flagErrors
}

const flagEnvPrefix = "EPR_"
Expand Down
3 changes: 2 additions & 1 deletion flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ func TestFlagsPrecedence(t *testing.T) {
require.Equal(t, "default", dummyFlag)

args := []string{"test", "-test-precedence-dummy=" + expected}
parseFlagSetWithArgs(flagSet, args)
err := parseFlagSetWithArgs(flagSet, args)
require.NoError(t, err)
require.Equal(t, expected, dummyFlag)
}

Expand Down
23 changes: 21 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package main

import (
"context"
"crypto/tls"
"flag"
"fmt"
"log"
Expand Down Expand Up @@ -53,6 +54,9 @@ var (
tlsCertFile string
tlsKeyFile string

tlsMinVersion string
tlsMinVersionCode uint16
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep two values to be easier to compare if it is set or not this parameter.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Umm, why not using a tls value directly here? We would also have the members for further uses.

Suggested change
tlsMinVersion string
tlsMinVersionCode uint16
tlsMinVersion *tlsMinVersionValue

It could implement an IsZero() bool method to make it easy to check if it is set or not 🙂


dryRun bool
configPath string

Expand Down Expand Up @@ -83,6 +87,7 @@ func init() {
flag.StringVar(&logType, "log-type", util.DefaultLoggerType, "log type (ecs, dev)")
flag.StringVar(&tlsCertFile, "tls-cert", "", "Path of the TLS certificate.")
flag.StringVar(&tlsKeyFile, "tls-key", "", "Path of the TLS key.")
flag.Var(&tlsMinVersionValue{version: &tlsMinVersion, versionCode: &tlsMinVersionCode}, "tls-min-version", "Minimum version TLS supported.")
flag.StringVar(&configPath, "config", "config.yml", "Path to the configuration file.")
flag.StringVar(&httpProfAddress, "httpprof", "", "Enable HTTP profiler listening on the given address.")
// This flag is experimental and might be removed in the future or renamed
Expand All @@ -108,7 +113,16 @@ type Config struct {
}

func main() {
parseFlags()
err := parseFlags()
if err != nil {
log.Fatal(err)
}

if tlsMinVersion != "" {
if tlsCertFile == "" || tlsKeyFile == "" {
log.Fatalf("-tls-min-version set but missing TLS cert and key files (-tls-cert and -tls-key)")
}
}

if printVersionInfo {
fmt.Printf("Elastic Package Registry version %v\n", version)
Expand Down Expand Up @@ -241,7 +255,12 @@ func initServer(logger *zap.Logger, apmTracer *apm.Tracer, config *Config) *http
router := mustLoadRouter(logger, config, indexer)
apmgorilla.Instrument(router, apmgorilla.WithTracer(apmTracer))

return &http.Server{Addr: address, Handler: router}
if tlsMinVersion == "" {
return &http.Server{Addr: address, Handler: router}
}

TLSConfig := &tls.Config{MinVersion: tlsMinVersionCode}
return &http.Server{Addr: address, Handler: router, TLSConfig: TLSConfig}
mrodm marked this conversation as resolved.
Show resolved Hide resolved
mrodm marked this conversation as resolved.
Show resolved Hide resolved
}

func runServer(server *http.Server) error {
Expand Down