Skip to content

Commit

Permalink
feat: implement exec-with-secret command
Browse files Browse the repository at this point in the history
  • Loading branch information
nomeaning777 committed Feb 26, 2020
1 parent 8dbcaff commit 7460288
Show file tree
Hide file tree
Showing 7 changed files with 381 additions and 0 deletions.
8 changes: 8 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Copyright 2020 nomeaning777

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.

14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# exec-with-secret

Run commands with secrets from GCP Secret Manager.
This program resolves environment variables that starts with `secretmanager://`.

## Usage

```shell
$ NON_SECRET=not_secret SECRET=secretmanager://<PROJECT_NAME>/<SECRET_NAME>/<VERSION> ./exec-with-secret sh -c 'echo $NON_SECRET $SECRET'
not_secret very_important_secret
```

## License
MIT
12 changes: 12 additions & 0 deletions auto/auto.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package auto

import (
"github.com/nomeaning777/exec-with-secret"
"log"
)

func init() {
if err := secret.InjectSecretToEnvironment(); err != nil {
log.Fatal(err)
}
}
24 changes: 24 additions & 0 deletions cmd/exec-with-secret/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package main

import (
"fmt"
_ "github.com/nomeaning777/exec-with-secret/auto"
"os"
"os/exec"
"path/filepath"
"syscall"
)

func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: %s <command> <arguments>\n", filepath.Base(os.Args[0]))
os.Exit(1)
}
binary, err := exec.LookPath(os.Args[1])
if err != nil {
panic(err)
}
if err := syscall.Exec(binary, os.Args[1:], os.Environ()); err != nil {
panic(err)
}
}
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module github.com/nomeaning777/exec-with-secret

go 1.13

require (
cloud.google.com/go v0.53.0
google.golang.org/genproto v0.0.0-20200225123651-fc8f55426688
)
230 changes: 230 additions & 0 deletions go.sum

Large diffs are not rendered by default.

85 changes: 85 additions & 0 deletions secret_env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package secret

import (
secretmanager "cloud.google.com/go/secretmanager/apiv1beta1"
"context"
"fmt"
secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1"
"net/url"
"os"
"strings"
)

type secretPath struct {
Project string
Secret string
Version string
}

func getSecret(client *secretmanager.Client, path secretPath) (string, error) {
req := &secretmanagerpb.AccessSecretVersionRequest{
Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", path.Project, path.Secret, path.Version),
}
resp, err := client.AccessSecretVersion(context.Background(), req)
if err != nil {
return "", fmt.Errorf("failed to access secret version: %w", err)
}
return string(resp.Payload.Data), nil
}

func parseSecretUrl(key string) (secretPath, error) {
secretUrl, err := url.Parse(key)
if err != nil {
return secretPath{}, fmt.Errorf("failed to parse secretUrl: %w", err)
}
projectName := secretUrl.Host
secretName := secretUrl.Path[1:]
version := "latest"
if strings.Contains(secretName, "/") {
splitSecretName := strings.SplitN(secretName, "/", 2)
secretName = splitSecretName[0]
version = splitSecretName[1]
}
return secretPath{
Project: projectName,
Secret: secretName,
Version: version,
}, nil
}

func isSecretUrl(value string) bool {
return strings.HasPrefix(value, "secretmanager://")
}

func InjectSecretToEnvironment() error {
client, err := secretmanager.NewClient(context.Background())
if err != nil {
return fmt.Errorf("failed to create secret manager client: %w", err)
}

for _, env := range os.Environ() {
pair := strings.SplitN(env, "=", 2)
if len(pair) != 2 {
continue
}

if !isSecretUrl(pair[1]) {
continue
}

path, err := parseSecretUrl(pair[1])
if err != nil {
return fmt.Errorf("parse failed to environment variable %s: %w", pair[0], err)
}

secret, err := getSecret(client, path)
if err != nil {
return fmt.Errorf("get secret failed to environemnt variable %s: %w", pair[0], err)
}

if err := os.Setenv(pair[0], secret); err != nil {
return fmt.Errorf("failed to setenv to %s: %+v", pair[0], err)
}
}
return nil
}

0 comments on commit 7460288

Please sign in to comment.