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

Setup generic functionality #8

Merged
merged 5 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
54 changes: 54 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,57 @@
module github.com/bank-vaults/secret-init

go 1.21

require github.com/bank-vaults/vault-sdk v0.9.0

require (
github.com/samber/lo v1.38.1 // indirect
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect
)

require (
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
cloud.google.com/go v0.78.0 // indirect
emperror.dev/errors v0.8.1 // indirect
github.com/aws/aws-sdk-go v1.44.248 // indirect
github.com/cenkalti/backoff/v3 v3.0.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/googleapis/gax-go/v2 v2.0.5 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-retryablehttp v0.6.6 // indirect
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
github.com/hashicorp/go-secure-stdlib/parseutil v0.1.6 // indirect
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
github.com/hashicorp/go-sockaddr v1.0.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/vault/api v1.9.1 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/leosayous21/go-azure-msi v0.0.0-20210509193526-19353bedcfc8 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/ryanuber/go-glob v1.0.0 // indirect
github.com/samber/slog-multi v1.0.2
github.com/samber/slog-syslog v1.0.0
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/spf13/cast v1.5.1
go.opencensus.io v0.22.5 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1 // indirect
google.golang.org/api v0.40.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20210224155714-063164c882e6 // indirect
google.golang.org/grpc v1.41.0 // indirect
google.golang.org/protobuf v1.26.0 // indirect
gopkg.in/square/go-jose.v2 v2.5.1 // indirect
)
584 changes: 584 additions & 0 deletions go.sum

Large diffs are not rendered by default.

59 changes: 59 additions & 0 deletions logger/client_logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright © 2023 Bank-Vaults Maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package logger

import (
"log/slog"

"github.com/bank-vaults/vault-sdk/vault"
)

var _ vault.Logger = &clientLogger{}

type clientLogger struct {
logger *slog.Logger
}

func (l clientLogger) Trace(msg string, args ...map[string]interface{}) {
l.Debug(msg, args...)
}

func (l clientLogger) Debug(msg string, args ...map[string]interface{}) {
l.logger.Debug(msg, l.argsToAttrs(args...)...)
}

func (l clientLogger) Info(msg string, args ...map[string]interface{}) {
l.logger.Info(msg, l.argsToAttrs(args...)...)
}

func (l clientLogger) Warn(msg string, args ...map[string]interface{}) {
l.logger.Warn(msg, l.argsToAttrs(args...)...)
}

func (l clientLogger) Error(msg string, args ...map[string]interface{}) {
l.logger.Error(msg, l.argsToAttrs(args...)...)
}

func (clientLogger) argsToAttrs(args ...map[string]interface{}) []any {
var attrs []any

for _, arg := range args {
for key, value := range arg {
attrs = append(attrs, slog.Any(key, value))
}
}

return attrs
}
89 changes: 89 additions & 0 deletions logger/slog_logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright © 2018 Banzai Cloud
// Copyright © 2023 Bank-Vaults Maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package logger

import (
"context"
"log/slog"
"net"
"os"
"slices"

slogmulti "github.com/samber/slog-multi"
slogsyslog "github.com/samber/slog-syslog"
"github.com/spf13/cast"
)

var logger *slog.Logger
csatib02 marked this conversation as resolved.
Show resolved Hide resolved

func SetupSlog() *slog.Logger {
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
var level slog.Level

err := level.UnmarshalText([]byte(os.Getenv("VAULT_LOG_LEVEL")))
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
if err != nil { // Silently fall back to info level
level = slog.LevelInfo
}

levelFilter := func(levels ...slog.Level) func(ctx context.Context, r slog.Record) bool {
return func(ctx context.Context, r slog.Record) bool {
return slices.Contains(levels, r.Level)
}
}

router := slogmulti.Router()

if cast.ToBool(os.Getenv("VAULT_JSON_LOG")) {
// Send logs with level higher than warning to stderr
router = router.Add(
slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}),
levelFilter(slog.LevelWarn, slog.LevelError),
)

// Send info and debug logs to stdout
router = router.Add(
slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}),
levelFilter(slog.LevelDebug, slog.LevelInfo),
)
} else {
// Send logs with level higher than warning to stderr
router = router.Add(
slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}),
levelFilter(slog.LevelWarn, slog.LevelError),
)

// Send info and debug logs to stdout
router = router.Add(
slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}),
levelFilter(slog.LevelDebug, slog.LevelInfo),
)
}

if logServerAddr := os.Getenv("VAULT_ENV_LOG_SERVER"); logServerAddr != "" {
writer, err := net.Dial("udp", logServerAddr)

// We silently ignore syslog connection errors for the lack of a better solution
if err == nil {
router = router.Add(slogsyslog.Option{Level: slog.LevelInfo, Writer: writer}.NewSyslogHandler())
}
}

// TODO: add level filter handler
logger = slog.New(router.Handler())
logger = logger.With(slog.String("app", "vault-env"))

slog.SetDefault(logger)
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
return logger
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
}
134 changes: 133 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,138 @@

package main

import (
"errors"
"fmt"
"log/slog"
"os"
"os/exec"
"os/signal"
"syscall"
"time"

"github.com/spf13/cast"

"github.com/bank-vaults/secret-init/logger"
"github.com/bank-vaults/secret-init/providers"
"github.com/bank-vaults/secret-init/providers/vault"
)

var providersMap = map[string]providers.Provider{
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
// "aws": aws.NewAWSProvider(),
// "gcp": gcp.NewGCPProvider(),
"vault": vault.NewVaultProvider(),
}

func main() {
println("hello world")
logger := logger.SetupSlog()

var providerName string
if len(os.Args) >= 3 && os.Args[1] == "-p" {
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
providerName = os.Args[2]

// Remove the "-p {provider name}" argument from the command-line arguments
os.Args = append(os.Args[:1], os.Args[3:]...)
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
}
csatib02 marked this conversation as resolved.
Show resolved Hide resolved

provider, found := providersMap[providerName]
if !found {
logger.Error("invalid provider specified.", slog.String("provider name", providerName))

os.Exit(1)
}

if len(os.Args) == 1 {
logger.Error("no command is given, vault-env can't determine the entrypoint (command), please specify it explicitly or let the webhook query it (see documentation)")

os.Exit(1)
}

daemonMode := cast.ToBool(os.Getenv("VAULT_ENV_DAEMON"))
delayExec := cast.ToDuration(os.Getenv("VAULT_ENV_DELAY"))
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
sigs := make(chan os.Signal, 1)

csatib02 marked this conversation as resolved.
Show resolved Hide resolved
entrypointCmd := os.Args[1:]

binary, err := exec.LookPath(entrypointCmd[0])
if err != nil {
logger.Error("binary not found", slog.String("binary", entrypointCmd[0]))

os.Exit(1)
}

var envs []string
envs, err = provider.RetrieveSecrets(os.Environ())
if err != nil {
logger.Error("could not retrieve secrets from the provider.", err)

os.Exit(1)
}

if delayExec > 0 {
logger.Info(fmt.Sprintf("sleeping for %s...", delayExec))
time.Sleep(delayExec)
}

logger.Info("spawning process", slog.String("entrypoint", fmt.Sprint(entrypointCmd)))

if daemonMode {
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
logger.Info("in daemon mode...")
cmd := exec.Command(binary, entrypointCmd[1:]...)
cmd.Env = append(os.Environ(), envs...)
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout

signal.Notify(sigs)

err = cmd.Start()
if err != nil {
logger.Error(fmt.Errorf("failed to start process: %w", err).Error(), slog.String("entrypoint", fmt.Sprint(entrypointCmd)))

os.Exit(1)
}

go func() {
for sig := range sigs {
// We don't want to signal a non-running process.
if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
break
}

err := cmd.Process.Signal(sig)
if err != nil {
logger.Warn(fmt.Errorf("failed to signal process: %w", err).Error(), slog.String("signal", sig.String()))
} else {
logger.Info("received signal", slog.String("signal", sig.String()))
}
}
}()

err = cmd.Wait()

close(sigs)

if err != nil {
exitCode := -1
// try to get the original exit code if possible
var exitError *exec.ExitError
if errors.As(err, &exitError) {
exitCode = exitError.ExitCode()
}

logger.Error(fmt.Errorf("failed to exec process: %w", err).Error(), slog.String("entrypoint", fmt.Sprint(entrypointCmd)))

os.Exit(exitCode)
}

os.Exit(cmd.ProcessState.ExitCode())
} else { //nolint:revive
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
err = syscall.Exec(binary, entrypointCmd, envs)
if err != nil {
logger.Error(fmt.Errorf("failed to exec process: %w", err).Error(), slog.String("entrypoint", fmt.Sprint(entrypointCmd)))

os.Exit(1)
}
}
}
23 changes: 23 additions & 0 deletions providers/provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright © 2018 Banzai Cloud
// Copyright © 2023 Bank-Vaults Maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package providers
csatib02 marked this conversation as resolved.
Show resolved Hide resolved

type Provider interface {
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
RetrieveSecrets(envVars []string) ([]string, error)
csatib02 marked this conversation as resolved.
Show resolved Hide resolved

//Future implementation.
//RenewSecret()
csatib02 marked this conversation as resolved.
Show resolved Hide resolved
}
Loading