command/write: can write arbitrary data from stdin

This commit is contained in:
Mitchell Hashimoto 2015-03-15 20:40:12 -07:00
parent 1d07df9db6
commit 602281213e
2 changed files with 67 additions and 1 deletions

View File

@ -1,7 +1,10 @@
package command
import (
"encoding/json"
"fmt"
"io"
"os"
"strings"
)
@ -11,6 +14,9 @@ const DefaultDataKey = "value"
// WriteCommand is a Command that puts data into the Vault.
type WriteCommand struct {
Meta
// The fields below can be overwritten for tests
testStdin io.Reader
}
func (c *WriteCommand) Run(args []string) int {
@ -31,7 +37,22 @@ func (c *WriteCommand) Run(args []string) int {
if path[0] == '/' {
path = path[1:]
}
data := map[string]interface{}{DefaultDataKey: args[1]}
var data map[string]interface{}
if args[1] == "-" {
var stdin io.Reader = os.Stdin
if c.testStdin != nil {
stdin = c.testStdin
}
dec := json.NewDecoder(stdin)
if err := dec.Decode(&data); err != nil {
c.Ui.Error(fmt.Sprintf(
"Error decoding JSON of stdin: %s", err))
return 1
}
} else {
data = map[string]interface{}{DefaultDataKey: args[1]}
}
client, err := c.Client()
if err != nil {

View File

@ -1,6 +1,7 @@
package command
import (
"io"
"testing"
"github.com/hashicorp/vault/http"
@ -43,3 +44,47 @@ func TestWrite(t *testing.T) {
t.Fatalf("bad: %#v", resp)
}
}
func TestWrite_arbitrary(t *testing.T) {
core, _ := vault.TestCoreUnsealed(t)
ln, addr := http.TestServer(t, core)
defer ln.Close()
stdinR, stdinW := io.Pipe()
ui := new(cli.MockUi)
c := &WriteCommand{
Meta: Meta{
Ui: ui,
},
testStdin: stdinR,
}
go func() {
stdinW.Write([]byte(`{"foo":"bar"}`))
stdinW.Close()
}()
args := []string{
"-address", addr,
"secret/foo",
"-",
}
if code := c.Run(args); code != 0 {
t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
}
client, err := c.Client()
if err != nil {
t.Fatalf("err: %s", err)
}
resp, err := client.Logical().Read("secret/foo")
if err != nil {
t.Fatalf("err: %s", err)
}
if resp.Data["foo"] != "bar" {
t.Fatalf("bad: %#v", resp)
}
}