Skip to content

Commit

Permalink
use latest credhub client
Browse files Browse the repository at this point in the history
  • Loading branch information
ArthurHlt committed May 5, 2018
1 parent bed043f commit 8e0c40c
Show file tree
Hide file tree
Showing 672 changed files with 95,686 additions and 6,606 deletions.
2 changes: 1 addition & 1 deletion cli/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type ServerApp struct {
func NewApp() *ServerApp {
app := &ServerApp{cli.NewApp()}
app.Name = "terraform-secure-backend"
app.Version = "1.0.0"
app.Version = "1.1.0"
app.Usage = "An http server to store terraform state file securely"
app.ErrWriter = os.Stderr
app.Flags = []cli.Flag{
Expand Down
17 changes: 14 additions & 3 deletions server/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"io/ioutil"
"net/http"
"strings"
"github.com/cloudfoundry-incubator/credhub-cli/credhub"
)

type ApiController struct {
Expand Down Expand Up @@ -45,12 +46,13 @@ func (c ApiController) Store(w http.ResponseWriter, req *http.Request) {
entry.Error(err)
panic(err)
}
_, err = c.credhubClient.SetJSON(c.CredhubName(req), values.JSON(dataJson), true)
_, err = c.credhubClient.SetJSON(c.CredhubName(req), values.JSON(dataJson), credhub.Overwrite)
if err != nil {
entry.Error(err)
panic(err)
}
}

func (c ApiController) Retrieve(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
entry := logrus.WithField("action", "retrieve").WithField("name", c.RequestName(req))
Expand All @@ -65,7 +67,8 @@ func (c ApiController) Retrieve(w http.ResponseWriter, req *http.Request) {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(cred.Value)
b, _ := json.Marshal(cred.Value)
w.Write(b)
}

func (c ApiController) Delete(w http.ResponseWriter, req *http.Request) {
Expand All @@ -84,6 +87,7 @@ func (c ApiController) Delete(w http.ResponseWriter, req *http.Request) {
panic(err)
}
}

func (c ApiController) Lock(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
var info *state.LockInfo
Expand Down Expand Up @@ -115,16 +119,20 @@ func (c ApiController) Lock(w http.ResponseWriter, req *http.Request) {
panic(err)
}
}

func (c ApiController) Path() string {
return fmt.Sprintf("%s/%s", CREDHUB_PREFIX, c.name)
}

func (c ApiController) CredhubName(req *http.Request) string {
return fmt.Sprintf("%s/%s", c.Path(), c.RequestName(req))
}

func (c ApiController) RequestName(req *http.Request) string {
vars := mux.Vars(req)
return vars["name"]
}

func (c ApiController) UnLock(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
var info *state.LockInfo
Expand Down Expand Up @@ -155,13 +163,15 @@ func (c ApiController) UnLock(w http.ResponseWriter, req *http.Request) {
panic(err)
}
}

func (c ApiController) List(w http.ResponseWriter, req *http.Request) {
entry := logrus.WithField("action", "list")
creds, err := c.credhubClient.FindByPath(c.Path())
result, err := c.credhubClient.FindByPath(c.Path())
if err != nil {
entry.Error(err)
panic(err)
}
creds := result.Credentials
backendCreds := make([]CredModel, 0)
for _, cred := range creds {
name := cred.Name
Expand All @@ -185,6 +195,7 @@ func (c ApiController) List(w http.ResponseWriter, req *http.Request) {
b, _ := json.MarshalIndent(backendCreds, "", "\t")
w.Write(b)
}

func ParseTfName(credhubName string) string {
splited := strings.Split(credhubName, "/")
return splited[len(splited)-1]
Expand Down
20 changes: 14 additions & 6 deletions server/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,24 @@ var _ = Describe("Api", func() {
})
Context("Retrieve", func() {
It("should giving data from credhub when exists", func() {
data := `{"key": "value"}`
data := values.JSON{
"key": "value",
}
fakeClient.GetLatestJSONReturns(credentials.JSON{
Value: json.RawMessage([]byte(data)),
Value: data,
}, nil)

apiController.Retrieve(responseRecorder, httptest.NewRequest("GET", "http://fakeurl.com", nil))

Expect(fakeClient.GetLatestJSONCallCount()).Should(Equal(1))
Expect(responseRecorder.Code).Should(Equal(http.StatusOK))
Expect(responseRecorder.Body.String()).Should(Equal(data))

var resultData map[string]interface{}
err := json.Unmarshal(responseRecorder.Body.Bytes(), &resultData)
Expect(err).ToNot(HaveOccurred())

Expect(resultData).Should(HaveKey("key"))
Expect(resultData["key"]).Should(Equal("value"))
})
It("should answer with http code status no content when there is no data in credhub", func() {

Expand Down Expand Up @@ -208,7 +216,7 @@ var _ = Describe("Api", func() {
Context("List", func() {
It("should give a list credentials", func() {
req := httptest.NewRequest("GET", "http://fakeurl.com", bytes.NewBufferString(""))
fakeClient.FindByPathReturns([]credentials.Base{
fakeClient.FindByPathReturns(credentials.FindResults{[]credentials.Base{
{
Name: apiController.CredhubName(req) + "data1",
VersionCreatedAt: "now",
Expand All @@ -221,7 +229,7 @@ var _ = Describe("Api", func() {
Name: apiController.CredhubName(req) + LOCK_SUFFIX,
VersionCreatedAt: "now",
},
}, nil)
}}, nil)
fakeClient.GetLatestValueReturnsOnCall(0, credentials.Value{}, errors.New("does not exist"))
fakeClient.GetLatestValueReturnsOnCall(1, credentials.Value{
Value: values.Value("id"),
Expand All @@ -243,7 +251,7 @@ var _ = Describe("Api", func() {
Expect(creds[1].CurrentLockId).Should(Equal("id"))
})
It("should panic if find was in error", func() {
fakeClient.FindByPathReturns([]credentials.Base{}, errors.New("a fake error"))
fakeClient.FindByPathReturns(credentials.FindResults{[]credentials.Base{}}, errors.New("a fake error"))
req := httptest.NewRequest("GET", "http://fakeurl.com", nil)
Expect(func() {
apiController.List(responseRecorder, req)
Expand Down
7 changes: 4 additions & 3 deletions server/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package server
import (
"github.com/cloudfoundry-incubator/credhub-cli/credhub/credentials"
"github.com/cloudfoundry-incubator/credhub-cli/credhub/credentials/values"
"github.com/cloudfoundry-incubator/credhub-cli/credhub"
)

type CredhubClient interface {
GetLatestJSON(name string) (credentials.JSON, error)
Delete(name string) error
SetJSON(name string, value values.JSON, overwrite bool) (credentials.JSON, error)
FindByPath(path string) ([]credentials.Base, error)
SetValue(name string, value values.Value, overwrite bool) (credentials.Value, error)
SetJSON(name string, value values.JSON, overwrite credhub.Mode) (credentials.JSON, error)
FindByPath(path string) (credentials.FindResults, error)
SetValue(name string, value values.Value, overwrite credhub.Mode) (credentials.Value, error)
GetLatestValue(name string) (credentials.Value, error)
}
7 changes: 6 additions & 1 deletion server/lockstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/cloudfoundry-incubator/credhub-cli/credhub/credentials/values"
"github.com/hashicorp/terraform/state"
"strings"
"github.com/cloudfoundry-incubator/credhub-cli/credhub"
)

type LockStore struct {
Expand All @@ -13,16 +14,19 @@ type LockStore struct {
func NewLockStore(credhubClient CredhubClient) *LockStore {
return &LockStore{credhubClient}
}

func (s LockStore) Lock(name string, info *state.LockInfo) error {
return s.toggleLock(name, info, true)
}

func (s LockStore) toggleLock(name string, info *state.LockInfo, lockState bool) error {
if !lockState {
return s.DeleteLock(name)
}
_, err := s.credhubClient.SetValue(name+LOCK_SUFFIX, values.Value(info.ID), true)
_, err := s.credhubClient.SetValue(name+LOCK_SUFFIX, values.Value(info.ID), credhub.Overwrite)
return err
}

func (s LockStore) UnLock(name string, info *state.LockInfo) error {
return s.toggleLock(name, info, false)
}
Expand All @@ -36,6 +40,7 @@ func (s LockStore) IsLocked(name string) (*state.LockInfo, bool) {
ID: string(cred.Value),
}, true
}

func (s LockStore) DeleteLock(name string) error {
err := s.credhubClient.Delete(name + LOCK_SUFFIX)
if err != nil && strings.Contains(err.Error(), "does not exist") {
Expand Down
10 changes: 9 additions & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func NewServer(config *ServerConfig) (*Server, error) {
}
return server, nil
}

func NewCloudServer() (*Server, error) {
config := &ServerConfig{}
err := gautocloud.Inject(config)
Expand All @@ -71,6 +72,7 @@ func NewCloudServer() (*Server, error) {
log.Info("Loading config from cloud environment")
return NewServer(config)
}

func (s Server) loadLogConfig() {
if s.config.LogJson {
log.SetFormatter(&log.JSONFormatter{})
Expand Down Expand Up @@ -101,6 +103,7 @@ func (s Server) loadLogConfig() {
}
return
}

func (s *Server) Load() error {
s.loadLogConfig()
if s.config.Port == 0 {
Expand Down Expand Up @@ -136,6 +139,7 @@ func (s *Server) Load() error {
}
return nil
}

func (s Server) loadHandler() error {
credhubClient, err := s.CreateCredhubCli()
if err != nil {
Expand All @@ -145,7 +149,6 @@ func (s Server) loadHandler() error {
controller := NewApiController(s.config.Name, credhubClient, store)
rtr := mux.NewRouter()
apiRtr := rtr.PathPrefix("/states").Subrouter()
apiRtr.HandleFunc("/{name}", controller.Store).Methods("POST")
apiRtr.HandleFunc("/{name}", controller.Retrieve).Methods("GET")
apiRtr.HandleFunc("/{name}", controller.Delete).Methods("DELETE")
apiRtr.HandleFunc("/{name}", controller.Lock).Methods("LOCK")
Expand All @@ -158,6 +161,7 @@ func (s Server) loadHandler() error {
}
return nil
}

func (s Server) runTls(servAddr string, handler http.Handler) (bool, error) {
if s.config.Cert == "" || s.config.Key == "" {
return false, fmt.Errorf("No certificate or key provided")
Expand All @@ -168,6 +172,7 @@ func (s Server) runTls(servAddr string, handler http.Handler) (bool, error) {
}
return true, nil
}

func (s Server) Run() error {
finalHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer s.panicRecover(w)
Expand All @@ -192,6 +197,7 @@ func (s Server) Run() error {
log.Infof("Serving an insecure server in http on address '%s'", servAddr)
return http.ListenAndServe(servAddr, finalHandler)
}

func (s Server) getTlsFilePath(tlsConf string) (string, error) {
if tlsConf == "" {
return "", nil
Expand All @@ -211,6 +217,7 @@ func (s Server) getTlsFilePath(tlsConf string) (string, error) {
f.WriteString(tlsConf)
return f.Name(), nil
}

func (s Server) CreateCredhubCli() (*credhub.CredHub, error) {
apiEndpoint := strings.TrimPrefix(s.config.CredhubServer, "http://")
if !strings.HasPrefix(apiEndpoint, "https://") {
Expand Down Expand Up @@ -241,6 +248,7 @@ func (s Server) CreateCredhubCli() (*credhub.CredHub, error) {
}
return credhub.New(apiEndpoint, options...)
}

func (s Server) panicRecover(w http.ResponseWriter) {
err := recover()
if err == nil {
Expand Down
Loading

0 comments on commit 8e0c40c

Please sign in to comment.