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

Refactor auth for modularity #158

Merged
merged 1 commit into from
Jun 23, 2022
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
6 changes: 1 addition & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@
__debug_bin
ui-server

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
.vscode/*.log

# Output of code generation tools
third_party/OpenAPI/temporal
Expand Down
80 changes: 5 additions & 75 deletions server/api/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ import (
"github.com/labstack/echo/v4"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"

"github.com/temporalio/ui-server/server/auth"
"github.com/temporalio/ui-server/server/config"
"github.com/temporalio/ui-server/server/generated/api/workflowservice/v1"
"github.com/temporalio/ui-server/server/rpc"
Expand Down Expand Up @@ -62,7 +62,7 @@ type SettingsResponse struct {

func TemporalAPIHandler(cfgProvider *config.ConfigProviderWithRefresh, apiMiddleware []Middleware) echo.HandlerFunc {
return func(c echo.Context) error {
err := validateAuth(c, cfgProvider)
err := auth.ValidateAuth(c, cfgProvider)
if err != nil {
return err
}
Expand All @@ -89,25 +89,6 @@ func TemporalAPIHandler(cfgProvider *config.ConfigProviderWithRefresh, apiMiddle
}
}

func GetCurrentUser(c echo.Context) error {
sess, _ := session.Get("auth", c)
email := sess.Values["email"]
name := sess.Values["name"]
picture := sess.Values["picture"]

if email == nil {
return c.JSON(http.StatusOK, nil)
}

user := struct {
Email string
Name string
Picture string
}{email.(string), name.(string), picture.(string)}

return c.JSON(http.StatusOK, user)
}

func GetSettings(cfgProvier *config.ConfigProviderWithRefresh) func(echo.Context) error {
return func(c echo.Context) error {
cfg, err := cfgProvier.GetConfig()
Expand All @@ -127,9 +108,9 @@ func GetSettings(cfgProvier *config.ConfigProviderWithRefresh) func(echo.Context
Endpoint: cfg.Codec.Endpoint,
}
if cfg.Codec.PassAccessToken {
sess, _ := session.Get("auth", c)
sess, _ := session.Get(auth.AuthCookie, c)
if sess != nil {
token := sess.Values["access-token"]
token := sess.Values[auth.AccessTokenKey]
if token != nil {
codec.AccessToken = token.(string)
}
Expand Down Expand Up @@ -163,7 +144,7 @@ func getTemporalClientMux(c echo.Context, temporalConn *grpc.ClientConn, apiMidd
tMux := runtime.NewServeMux(
append(muxOpts,
withMarshaler(),
withAuth(c),
auth.WithAuth(c),
version.WithVersionHeader(c),
// This is necessary to get error details properly
// marshalled in unary requests.
Expand All @@ -186,54 +167,3 @@ func withMarshaler() runtime.ServeMuxOption {

return runtime.WithMarshalerOption(runtime.MIMEWildcard, jsonpb)
}

func withAuth(c echo.Context) runtime.ServeMuxOption {
return runtime.WithMetadata(
func(ctx context.Context, req *http.Request) metadata.MD {
md := metadata.MD{}

sess, _ := session.Get("auth", c)

if sess == nil {
return md
}

token := sess.Values["access-token"]
if token != nil {
md.Append("authorization", "Bearer "+token.(string))
}

extras := sess.Values["authorization-extras"]
if extras != nil {
// ex. ID Token
md.Append("authorization-extras", extras.(string))
}

return md
},
)
}

func validateAuth(c echo.Context, cfgProvider *config.ConfigProviderWithRefresh) error {
cfg, err := cfgProvider.GetConfig()
if err != nil {
return err
}

isEnabled := cfg.Auth.Enabled
if !isEnabled {
return nil
}

sess, _ := session.Get("auth", c)
if sess == nil {
return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized")
}

token := sess.Values["access-token"]
if token == nil {
return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized")
}

return nil
}
143 changes: 143 additions & 0 deletions server/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// The MIT License
//
// Copyright (c) 2022 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package auth

import (
"context"
"net/http"
"time"

"github.com/gorilla/sessions"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/temporalio/ui-server/server/config"
"google.golang.org/grpc/metadata"
)

const (
AuthCookie = "auth"
AccessTokenKey = "access-token"
AuthorizationExtrasKey = "authorization-extras"
EmailKey = "email"
NameKey = "name"
PictureKey = "picture"
)

func GetCurrentUser(c echo.Context) error {
sess, _ := session.Get(AuthCookie, c)
email := sess.Values[EmailKey]
name := sess.Values[NameKey]
picture := sess.Values[PictureKey]

if email == nil {
return c.JSON(http.StatusOK, nil)
}

user := struct {
Email string
Name string
Picture string
}{email.(string), name.(string), picture.(string)}

return c.JSON(http.StatusOK, user)
}

func SetUser(c echo.Context, user *User) error {
sess, err := session.Get(AuthCookie, c)
if err != nil {
return err
}

sess.Options = &sessions.Options{
Path: "/",
MaxAge: 7 * 24 * int(time.Hour.Seconds()),
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Secure: true,
}
sess.Values[AccessTokenKey] = &user.OAuth2Token.AccessToken
sess.Values[EmailKey] = &user.IDToken.Email
sess.Values[PictureKey] = &user.IDToken.Picture
sess.Values[NameKey] = &user.IDToken.Name

err = sess.Save(c.Request(), c.Response())
if err != nil {
return err
}

return nil
}

func ValidateAuth(c echo.Context, cfgProvider *config.ConfigProviderWithRefresh) error {
cfg, err := cfgProvider.GetConfig()
if err != nil {
return err
}

isEnabled := cfg.Auth.Enabled
if !isEnabled {
return nil
}

sess, _ := session.Get(AuthCookie, c)
if sess == nil {
return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized")
}

token := sess.Values[AccessTokenKey]
if token == nil {
return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized")
}

return nil
}

func WithAuth(c echo.Context) runtime.ServeMuxOption {
return runtime.WithMetadata(
func(ctx context.Context, req *http.Request) metadata.MD {
md := metadata.MD{}

sess, _ := session.Get(AuthCookie, c)

if sess == nil {
return md
}

token := sess.Values[AccessTokenKey]
if token != nil {
md.Append(echo.HeaderAuthorization, "Bearer "+token.(string))
}

extras := sess.Values[AuthorizationExtrasKey]
if extras != nil {
// ex. ID Token
md.Append(AuthorizationExtrasKey, extras.(string))
}

return md
},
)
}
95 changes: 95 additions & 0 deletions server/auth/oidc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// The MIT License
//
// Copyright (c) 2022 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package auth

import (
"context"
"net/http"

"github.com/coreos/go-oidc/v3/oidc"
"github.com/labstack/echo/v4"
"golang.org/x/oauth2"
)

type User struct {
OAuth2Token *oauth2.Token
IDToken *Claims
}

type Claims struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Picture string `json:"picture"`
}

func ExchangeCode(ctx context.Context, r *http.Request, config *oauth2.Config, provider *oidc.Provider) (*User, error) {
state, err := r.Cookie("state")
if err != nil {
return nil, echo.NewHTTPError(http.StatusBadRequest, "State cookie is not set in request")
}
if r.URL.Query().Get("state") != state.Value {
return nil, echo.NewHTTPError(http.StatusBadRequest, "State cookie did not match")
}

oauth2Token, err := config.Exchange(ctx, r.URL.Query().Get("code"))
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Unable to exchange token: "+err.Error())
}

rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
return nil, echo.NewHTTPError(http.StatusInternalServerError, "No id_token field in oauth2 token.")
}
oidcConfig := &oidc.Config{
ClientID: config.ClientID,
}
verifier := provider.Verifier(oidcConfig)
idToken, err := verifier.Verify(ctx, rawIDToken)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Unable to verify ID Token: "+err.Error())
}

nonce, err := r.Cookie("nonce")
if err != nil {
return nil, echo.NewHTTPError(http.StatusBadRequest, "Nonce is not provided")
}
if idToken.Nonce != nonce.Value {
return nil, echo.NewHTTPError(http.StatusBadRequest, "Nonce did not match")
}

var claims Claims

if err := idToken.Claims(&claims); err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}

user := User{
OAuth2Token: oauth2Token,
IDToken: &claims,
}

return &user, nil
}
3 changes: 2 additions & 1 deletion server/routes/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ import (
"github.com/labstack/echo/v4"

"github.com/temporalio/ui-server/server/api"
"github.com/temporalio/ui-server/server/auth"
"github.com/temporalio/ui-server/server/config"
)

// SetAPIRoutes sets api routes
func SetAPIRoutes(e *echo.Echo, cfgProvider *config.ConfigProviderWithRefresh, apiMiddleware []api.Middleware) error {
route := e.Group("/api")
route.GET("/v1/me", api.GetCurrentUser)
route.GET("/v1/me", auth.GetCurrentUser)
route.GET("/v1/settings", api.GetSettings(cfgProvider))
route.Match([]string{"GET", "POST", "PUT", "PATCH", "DELETE"}, "/*", api.TemporalAPIHandler(cfgProvider, apiMiddleware))
return nil
Expand Down
Loading