Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ui: various glue fixes #29692

Merged
merged 5 commits into from
Sep 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pkg/build/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,15 @@ func (b Info) Short() string {
b.Distribution, b.Tag, plat, b.Time, b.GoVersion)
}

// GoTime parses the utcTime string and returns a time.Time.
func (b Info) GoTime() time.Time {
val, err := time.Parse(TimeFormat, b.Time)
if err != nil {
return time.Time{}
}
return val
}

// Timestamp parses the utcTime string and returns the number of seconds since epoch.
func (b Info) Timestamp() (int64, error) {
val, err := time.Parse(TimeFormat, b.Time)
Expand Down
16 changes: 7 additions & 9 deletions pkg/server/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,19 +356,17 @@ const webSessionIDKeyStr = "webSessionID"

func (am *authenticationMux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
username, cookie, err := am.getSession(w, req)
if err != nil && !am.allowAnonymous {
if err == nil {
ctx := req.Context()
ctx = context.WithValue(ctx, webSessionUserKey{}, username)
ctx = context.WithValue(ctx, webSessionIDKey{}, cookie.ID)
req = req.WithContext(ctx)
} else if !am.allowAnonymous {
log.Infof(req.Context(), "Web session error: %s", err)
http.Error(w, "a valid authentication cookie is required", http.StatusUnauthorized)
return
}

newCtx := context.WithValue(req.Context(), webSessionUserKey{}, username)
if cookie != nil {
newCtx = context.WithValue(newCtx, webSessionIDKey{}, cookie.ID)
}
newReq := req.WithContext(newCtx)

am.inner.ServeHTTP(w, newReq)
am.inner.ServeHTTP(w, req)
}

func encodeSessionCookie(sessionCookie *serverpb.SessionCookie) (*http.Cookie, error) {
Expand Down
66 changes: 17 additions & 49 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ import (
"compress/gzip"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"html/template"
"io"
"io/ioutil"
"math"
Expand All @@ -33,7 +31,6 @@ import (
"sync/atomic"
"time"

assetfs "github.com/elazarl/go-bindata-assetfs"
raven "github.com/getsentry/raven-go"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
opentracing "github.com/opentracing/opentracing-go"
Expand All @@ -42,7 +39,6 @@ import (

"github.com/cockroachdb/cmux"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/jobs"
Expand Down Expand Up @@ -1236,17 +1232,19 @@ func (s *Server) Start(ctx context.Context) error {
// endpoints.
s.mux.Handle(debug.Endpoint, debug.NewServer(s.st))

fileServer := http.FileServer(&assetfs.AssetFS{
Asset: ui.Asset,
AssetDir: ui.AssetDir,
AssetInfo: ui.AssetInfo,
})

// Serve UI assets. This needs to be before the gRPC handlers are registered, otherwise
// the `s.mux.Handle("/", ...)` would cover all URLs, allowing anonymous access.
maybeAuthMux := newAuthenticationMuxAllowAnonymous(
s.authentication, serveUIAssets(fileServer, s.cfg),
)
s.authentication, ui.Handler(ui.Config{
ExperimentalUseLogin: s.cfg.EnableWebSessionAuthentication,
LoginEnabled: s.cfg.RequireWebSession(),
GetUser: func(ctx context.Context) *string {
if u, ok := ctx.Value(webSessionUserKey{}).(string); ok {
return &u
}
return nil
},
}))
s.mux.Handle("/", maybeAuthMux)

// Initialize grpc-gateway mux and context in order to get the /health
Expand Down Expand Up @@ -1896,6 +1894,8 @@ func (s *Server) PGServer() *pgwire.Server {
return s.pgServer
}

// TODO(benesch): Use https://github.com/NYTimes/gziphandler instead.
// gzipResponseWriter reinvents the wheel and is not as robust.
type gzipResponseWriter struct {
gz gzip.Writer
http.ResponseWriter
Expand All @@ -1918,6 +1918,11 @@ func (w *gzipResponseWriter) Reset(rw http.ResponseWriter) {
}

func (w *gzipResponseWriter) Write(b []byte) (int, error) {
// The underlying http.ResponseWriter can't sniff gzipped data properly, so we
// do our own sniffing on the uncompressed data.
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
return w.gz.Write(b)
}

Expand All @@ -1944,43 +1949,6 @@ func (w *gzipResponseWriter) Close() error {
return err
}

func serveUIAssets(fileServer http.Handler, cfg Config) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if request.URL.Path != "/" {
fileServer.ServeHTTP(writer, request)
return
}

// Construct arguments for template.
tmplArgs := ui.IndexHTMLArgs{
ExperimentalUseLogin: cfg.EnableWebSessionAuthentication,
LoginEnabled: cfg.RequireWebSession(),
Tag: build.GetInfo().Tag,
Version: build.VersionPrefix(),
}
loggedInUser, ok := request.Context().Value(webSessionUserKey{}).(string)
if ok && loggedInUser != "" {
tmplArgs.LoggedInUser = &loggedInUser
}

argsJSON, err := json.Marshal(tmplArgs)
if err != nil {
http.Error(writer, err.Error(), 500)
}

// Execute the template.
writer.Header().Add("Content-Type", "text/html")
if err := ui.IndexHTMLTemplate.Execute(writer, map[string]template.JS{
"DataFromServer": template.JS(string(argsJSON)),
}); err != nil {
wrappedErr := errors.Wrap(err, "templating index.html")
http.Error(writer, wrappedErr.Error(), 500)
log.Error(request.Context(), wrappedErr)
return
}
})
}

func init() {
tracing.RegisterTagRemapping("n", "node")
}
89 changes: 66 additions & 23 deletions pkg/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"testing"
Expand All @@ -43,6 +44,7 @@ import (
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/ui"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/httputil"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
Expand Down Expand Up @@ -858,6 +860,17 @@ func TestServeIndexHTML(t *testing.T) {
</html>
`

linkInFakeUI := func() {
ui.Asset = func(string) (_ []byte, _ error) { return }
ui.AssetDir = func(name string) (_ []string, _ error) { return }
ui.AssetInfo = func(name string) (_ os.FileInfo, _ error) { return }
}
unlinkFakeUI := func() {
ui.Asset = nil
ui.AssetDir = nil
ui.AssetInfo = nil
}

t.Run("Insecure mode", func(t *testing.T) {
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Insecure: true,
Expand All @@ -874,32 +887,62 @@ func TestServeIndexHTML(t *testing.T) {
t.Fatal(err)
}

resp, err := client.Get(s.AdminURL())
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 200 {
t.Fatalf("expected status code 200; got %d", resp.StatusCode)
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
respString := string(respBytes)
expected := fmt.Sprintf(
htmlTemplate,
fmt.Sprintf(
`{"ExperimentalUseLogin":false,"LoginEnabled":false,"LoggedInUser":null,"Tag":"%s","Version":"%s"}`,
build.GetInfo().Tag,
build.VersionPrefix(),
),
)
if respString != expected {
t.Fatalf("expected %s; got %s", expected, respString)
}
t.Run("short build", func(t *testing.T) {
resp, err := client.Get(s.AdminURL())
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 200 {
t.Fatalf("expected status code 200; got %d", resp.StatusCode)
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
respString := string(respBytes)
expected := fmt.Sprintf(`<!DOCTYPE html>
<title>CockroachDB</title>
Binary built without web UI.
<hr>
<em>%s</em>`,
build.GetInfo().Short())
if respString != expected {
t.Fatalf("expected %s; got %s", expected, respString)
}
})

t.Run("non-short build", func(t *testing.T) {
linkInFakeUI()
defer unlinkFakeUI()
resp, err := client.Get(s.AdminURL())
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 200 {
t.Fatalf("expected status code 200; got %d", resp.StatusCode)
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
respString := string(respBytes)
expected := fmt.Sprintf(
htmlTemplate,
fmt.Sprintf(
`{"ExperimentalUseLogin":false,"LoginEnabled":false,"LoggedInUser":null,"Tag":"%s","Version":"%s"}`,
build.GetInfo().Tag,
build.VersionPrefix(),
),
)
if respString != expected {
t.Fatalf("expected %s; got %s", expected, respString)
}
})
})

t.Run("Secure mode", func(t *testing.T) {
linkInFakeUI()
defer unlinkFakeUI()
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(context.TODO())
tsrv := s.(*TestServer)
Expand Down
Loading