Skip to content

Commit

Permalink
github-events: fix secrets parsing (#671)
Browse files Browse the repository at this point in the history
1. os.Environ returns a list of `key=value`, not a list of keys
2. Use append instead of overwriting secrets list each time.
  • Loading branch information
wlynch authored Dec 17, 2024
1 parent 87c4bc4 commit 15ad036
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 7 deletions.
9 changes: 2 additions & 7 deletions modules/github-events/cmd/trampoline/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ import (
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"

"github.com/chainguard-dev/clog"
_ "github.com/chainguard-dev/clog/gcp/init"
"github.com/chainguard-dev/terraform-infra-common/modules/github-events/internal/secrets"
"github.com/chainguard-dev/terraform-infra-common/modules/github-events/internal/trampoline"
"github.com/chainguard-dev/terraform-infra-common/pkg/httpmetrics"
mce "github.com/chainguard-dev/terraform-infra-common/pkg/httpmetrics/cloudevents"
Expand All @@ -35,12 +35,7 @@ func main() {
defer cancel()

// Get all secrets from the environment.
var secrets [][]byte
for _, e := range os.Environ() {
if strings.HasPrefix(e, "WEBHOOK_SECRET") {
secrets = [][]byte{[]byte(os.Getenv(e))}
}
}
secrets := secrets.LoadFromEnv(ctx)

go httpmetrics.ServeMetrics()
defer httpmetrics.SetupTracer(ctx)()
Expand Down
30 changes: 30 additions & 0 deletions modules/github-events/internal/secrets/secrets.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
Copyright 2024 Chainguard, Inc.
SPDX-License-Identifier: Apache-2.0
*/

package secrets

import (
"context"
"os"
"strings"

"github.com/chainguard-dev/clog"
)

func LoadFromEnv(ctx context.Context) [][]byte {
var secrets [][]byte
for _, e := range os.Environ() {
k, v, ok := strings.Cut(e, "=")
if !ok {
continue
}

if strings.HasPrefix(k, "WEBHOOK_SECRET") {
clog.InfoContextf(ctx, "loading secret: %q", k)
secrets = append(secrets, []byte(v))
}
}
return secrets
}
28 changes: 28 additions & 0 deletions modules/github-events/internal/secrets/secrets_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
Copyright 2024 Chainguard, Inc.
SPDX-License-Identifier: Apache-2.0
*/

package secrets

import (
"testing"

"github.com/chainguard-dev/clog/slogtest"
"github.com/google/go-cmp/cmp"
)

func TestLoadFromEnv(t *testing.T) {
// Set up the environment variables for testing.
t.Setenv("WEBHOOK_SECRET", "foo")
t.Setenv("WEBHOOK_SECRET_2", "bar")

ctx := slogtest.Context(t)
got := LoadFromEnv(ctx)

want := [][]byte{[]byte("foo"), []byte("bar")}

if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("LoadFromEnv() mismatch (-want +got):\n%s", diff)
}
}

0 comments on commit 15ad036

Please sign in to comment.