open-vault/http/handler.go

73 lines
1.9 KiB
Go
Raw Normal View History

2015-03-12 06:05:16 +00:00
package http
import (
"encoding/json"
"net/http"
2015-03-29 23:14:54 +00:00
"github.com/hashicorp/vault/logical"
2015-03-12 06:05:16 +00:00
"github.com/hashicorp/vault/vault"
)
2015-03-29 23:14:54 +00:00
// AuthCookieName is the name of the cookie containing the token.
const AuthCookieName = "token"
2015-03-12 06:05:16 +00:00
// Handler returns an http.Handler for the API. This can be used on
// its own to mount the Vault API within another web server.
func Handler(core *vault.Core) http.Handler {
mux := http.NewServeMux()
2015-03-12 19:37:41 +00:00
mux.Handle("/v1/sys/init", handleSysInit(core))
2015-03-12 17:47:31 +00:00
mux.Handle("/v1/sys/seal-status", handleSysSealStatus(core))
mux.Handle("/v1/sys/seal", handleSysSeal(core))
mux.Handle("/v1/sys/unseal", handleSysUnseal(core))
2015-03-16 17:51:13 +00:00
mux.Handle("/v1/sys/mounts/", handleSysMounts(core))
2015-04-01 02:21:02 +00:00
mux.Handle("/v1/sys/revoke/", handleSysRevoke(core))
2015-04-01 02:23:32 +00:00
mux.Handle("/v1/sys/revoke-prefix/", handleSysRevokePrefix(core))
mux.Handle("/v1/", handleLogical(core))
2015-03-12 06:05:16 +00:00
return mux
}
func parseRequest(r *http.Request, out interface{}) error {
dec := json.NewDecoder(r.Body)
return dec.Decode(out)
}
2015-03-29 23:14:54 +00:00
// requestAuth adds the token to the logical.Request if it exists.
func requestAuth(r *http.Request, req *logical.Request) *logical.Request {
// Attach the cookie value as the token if we have it
2015-03-29 23:14:54 +00:00
cookie, err := r.Cookie(AuthCookieName)
if err == nil {
req.ClientToken = cookie.Value
}
return req
}
2015-03-12 06:05:16 +00:00
func respondError(w http.ResponseWriter, status int, err error) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
resp := &ErrorResponse{Errors: make([]string, 0, 1)}
if err != nil {
resp.Errors = append(resp.Errors, err.Error())
}
enc := json.NewEncoder(w)
enc.Encode(resp)
}
func respondOk(w http.ResponseWriter, body interface{}) {
w.Header().Add("Content-Type", "application/json")
if body == nil {
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
enc.Encode(body)
}
}
type ErrorResponse struct {
Errors []string `json:"errors"`
}