2015-03-13 18:13:33 +00:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
2015-03-15 23:52:19 +00:00
|
|
|
"fmt"
|
2015-03-13 18:13:33 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2015-03-31 06:30:30 +00:00
|
|
|
"net/http/cookiejar"
|
2015-03-13 18:13:33 +00:00
|
|
|
"testing"
|
2015-03-29 23:14:54 +00:00
|
|
|
"time"
|
2015-03-13 18:13:33 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/vault/vault"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestServer(t *testing.T, core *vault.Core) (net.Listener, string) {
|
2015-03-15 23:52:19 +00:00
|
|
|
fail := func(format string, args ...interface{}) {
|
|
|
|
panic(fmt.Sprintf(format, args...))
|
|
|
|
}
|
|
|
|
if t != nil {
|
|
|
|
fail = t.Fatalf
|
|
|
|
}
|
|
|
|
|
2015-03-13 18:13:33 +00:00
|
|
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
|
|
|
if err != nil {
|
2015-03-15 23:52:19 +00:00
|
|
|
fail("err: %s", err)
|
2015-03-13 18:13:33 +00:00
|
|
|
}
|
|
|
|
addr := "http://" + ln.Addr().String()
|
|
|
|
|
2015-03-29 23:14:54 +00:00
|
|
|
// Create a muxer to handle our requests so that we can authenticate
|
|
|
|
// for tests.
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.Handle("/_test/auth", http.HandlerFunc(testHandleAuth))
|
|
|
|
mux.Handle("/", Handler(core))
|
|
|
|
|
2015-03-13 18:13:33 +00:00
|
|
|
server := &http.Server{
|
|
|
|
Addr: ln.Addr().String(),
|
2015-03-29 23:14:54 +00:00
|
|
|
Handler: mux,
|
2015-03-13 18:13:33 +00:00
|
|
|
}
|
|
|
|
go server.Serve(ln)
|
|
|
|
|
|
|
|
return ln, addr
|
|
|
|
}
|
2015-03-29 23:14:54 +00:00
|
|
|
|
|
|
|
func TestServerAuth(t *testing.T, addr string, token string) {
|
2015-03-31 06:30:30 +00:00
|
|
|
// If no cookie jar is set on the default HTTP client, then setup the jar
|
|
|
|
if http.DefaultClient.Jar == nil {
|
|
|
|
jar, err := cookiejar.New(&cookiejar.Options{})
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
http.DefaultClient.Jar = jar
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the internal path so that we set the cookie
|
2015-03-29 23:14:54 +00:00
|
|
|
if _, err := http.Get(addr + "/_test/auth?token=" + token); err != nil {
|
|
|
|
t.Fatalf("error authenticating: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func testHandleAuth(w http.ResponseWriter, req *http.Request) {
|
|
|
|
token := req.URL.Query().Get("token")
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
|
|
Name: AuthCookieName,
|
|
|
|
Value: token,
|
|
|
|
Path: "/",
|
|
|
|
Expires: time.Now().UTC().Add(1 * time.Hour),
|
|
|
|
})
|
|
|
|
|
|
|
|
respondOk(w, nil)
|
|
|
|
}
|