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

Custom jwt http ACL policy #114

Closed
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
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,9 @@ require (
)

require (
github.com/MicahParks/keyfunc/v2 v2.1.0
github.com/bndr/gotabulate v1.1.2
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/hashicorp/go-version v1.6.0
golang.org/x/exp v0.0.0-20230811145659-89c5cff77bcb
modernc.org/sqlite v1.20.3
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ github.com/HdrHistogram/hdrhistogram-go v0.9.0/go.mod h1:nxrse8/Tzg2tg3DZcZjm6qE
github.com/Masterminds/glide v0.13.2/go.mod h1:STyF5vcenH/rUqTEv+/hBXlSTo7KYwg2oc2f4tzPWic=
github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
github.com/Masterminds/vcs v1.13.0/go.mod h1:N09YCmOQr6RLxC6UNHzuVwAdodYbbnycGHSmwVJjcKA=
github.com/MicahParks/keyfunc/v2 v2.1.0 h1:6ZXKb9Rp6qp1bDbJefnG7cTH8yMN1IC/4nf+GVjO99k=
github.com/MicahParks/keyfunc/v2 v2.1.0/go.mod h1:rW42fi+xgLJ2FRRXAfNx9ZA8WpD4OeE/yHVMteCkw9k=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/PuerkitoBio/goquery v1.5.1 h1:PSPBGne8NIUWw+/7vFBV+kG2J/5MOjbzc7154OaKCSE=
github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
Expand Down Expand Up @@ -281,6 +283,8 @@ github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7a
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
Expand Down
232 changes: 232 additions & 0 deletions go/acl/shopify_jwt_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
/*
Copyright 2023 The Vitess Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package acl

import (
"bytes"
"context"
b64 "encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"

keyfunc "github.com/MicahParks/keyfunc/v2"
jwt "github.com/golang-jwt/jwt/v5"
)

const (
SHOPIFY_JWT = "shopify_jwt"
SHOPIFY_JWT_HEADER_ENV = "SHOPIFY_JWT_HEADER"
SHOPIFY_JWKS_URL_ENV = "SHOPIFY_JWKS_URL"
SHOPIFY_USER_ID_HEADER_ENV = "SHOPIFY_USER_ID_HEADER"
SHOPIFY_AUTHZ_URL_ENV = "SHOPIFY_AUTHZ_URL"
SHOPIFY_AUTHZ_GROUPS_ENV = "SHOPIFY_AUTHZ_GROUPS"
SHOPIFY_AUTHZ_USERNAME_ENV = "SHOPIFY_AUTHZ_USERNAME"
SHOPIFY_AUTHZ_PASSWORD_ENV = "SHOPIFY_AUTHZ_PASSWORD"
)

var errDenyShopifyJwt = errors.New("not allowed: shopify_jwt security_policy enforced")

type membership struct {
Group string
Member bool
}

type shopifyAuthzData struct {
Memberships []membership
}

type shopifyAuthzResponse struct {
Data shopifyAuthzData
}

func jwksRequestFactory(ctx context.Context, url string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, bytes.NewReader(nil))

if err != nil {
return nil, err
}

req.Header.Set("Accept", "application/json")
return req, nil
}

type shopifyJwt struct{}

func validateJWT(tokenString string, jwksURL string) (bool, error) {
// Fetch the JWKS from the provided URL
jwks, err := keyfunc.Get(jwksURL, keyfunc.Options{
RequestFactory: jwksRequestFactory,
})

defer jwks.EndBackground()

if err != nil {
return false, err
}

// Parse and validate the JWT token
token, err := jwt.Parse(tokenString, jwks.Keyfunc)
if err != nil {
return false, fmt.Errorf("failed to parse JWT token: %v", err)
}

if token.Valid {
return true, nil
}

return false, nil
}

func buildAuth(username string, password string) string {
return fmt.Sprintf("Basic %s", b64.URLEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))))
}

func authorizeUser(userId int) (bool, error) {
url := os.Getenv(SHOPIFY_AUTHZ_URL_ENV)

var groups string

for _, group := range strings.Split(os.Getenv(SHOPIFY_AUTHZ_GROUPS_ENV), ",") {
groups += fmt.Sprintf("\"%s\",", group)
}

query := map[string]string{
"query": fmt.Sprintf(`
{
memberships(
userEmployeeId: %d
groups: [%s]
) {
member
group
}
}
`, userId, groups),
}

queryJson, err := json.Marshal(query)

if err != nil {
return false, err
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(queryJson))

if err != nil {
return false, err
}

req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", buildAuth(os.Getenv(SHOPIFY_AUTHZ_USERNAME_ENV), os.Getenv(SHOPIFY_AUTHZ_PASSWORD_ENV)))

client := &http.Client{}
res, err := client.Do(req)

if err != nil {
return false, err
}

defer res.Body.Close()

if res.StatusCode != http.StatusOK {
return false, fmt.Errorf("failed to authorize user. status: %s", res.Status)
}

var jsonRes shopifyAuthzResponse
err = json.NewDecoder(res.Body).Decode(&jsonRes)
if err != nil {
return false, err
}

for _, membership := range jsonRes.Data.Memberships {
if membership.Member {
return true, nil
}
}

return false, fmt.Errorf("user is not a member of any authorized groups")
}

// CheckAccessActor disallows actor access not verified by shopifyJwt
func (shopifyJwt) CheckAccessActor(actor, role string) error {
switch role {
case SHOPIFY_JWT:
return nil
default:
return errDenyShopifyJwt
}
}

// CheckAccessHTTP disallows HTTP access not verified by shopifyJwt
func (shopifyJwt) CheckAccessHTTP(req *http.Request, role string) error {
switch role {
case SHOPIFY_JWT:
jwtToken := req.Header.Get(os.Getenv(SHOPIFY_JWT_HEADER_ENV))

if len(jwtToken) < 1 {
log.Println("failed to get jwt token from header")
return errDenyShopifyJwt
}

_, err := validateJWT(jwtToken, os.Getenv(SHOPIFY_JWKS_URL_ENV))

if err != nil {
log.Printf("invalid JWT token provided: %s", err)
return err
}

userId := req.Header.Get(os.Getenv(SHOPIFY_USER_ID_HEADER_ENV))

if len(userId) < 1 {
log.Println("failed to get user id from header")
return errDenyShopifyJwt
}

userIdInt, err := strconv.Atoi(userId)

if err != nil {
log.Printf("failed to convert user id to int: %s", err)
return err
}

authorized, err := authorizeUser(userIdInt)

if err != nil {
log.Printf("failed to authorize user ID: %s, %v", userId, err)
return err
}

if !authorized {
log.Printf("user ID %s is not authorized", userId)
return err
}

return nil
default:
return errDenyShopifyJwt
}
}

func init() {
RegisterPolicy(SHOPIFY_JWT, shopifyJwt{})
}
2 changes: 1 addition & 1 deletion go/streamlog/streamlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ func (logger *StreamLogger) Name() string {
// It is safe to register multiple URLs for the same StreamLogger.
func (logger *StreamLogger) ServeLogs(url string, logf LogFormatter) {
http.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
6 changes: 3 additions & 3 deletions go/vt/servenv/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ func (sp *statusPage) addStatusSection(banner string, f func() string) {
}

func (sp *statusPage) statusHandler(w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down Expand Up @@ -250,7 +250,7 @@ func (sp *statusPage) reparse(sections []section) (*template.Template, error) {
// Toggle the block profile rate to/from 100%, unless specific rate is passed in
func registerDebugBlockProfileRate() {
http.HandleFunc("/debug/blockprofilerate", func(w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down Expand Up @@ -280,7 +280,7 @@ func registerDebugBlockProfileRate() {
// Toggle the mutex profiling fraction to/from 100%, unless specific fraction is passed in
func registerDebugMutexProfileFraction() {
http.HandleFunc("/debug/mutexprofilefraction", func(w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vtctld/debug_health.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (
// RegisterDebugHealthHandler register a debug health http endpoint for a vtcld server
func RegisterDebugHealthHandler(ts *topo.Server) {
http.HandleFunc("/debug/health", func(w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.MONITORING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vtgate/debugenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ type envValue struct {
}

func debugEnvHandler(vtg *VTGate, w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vtgate/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -1104,7 +1104,7 @@ func (e *Executor) debugCacheEntries() (items []cacheItem) {

// ServeHTTP shows the current plans in the query cache.
func (e *Executor) ServeHTTP(response http.ResponseWriter, request *http.Request) {
if err := acl.CheckAccessHTTP(request, acl.DEBUGGING); err != nil {
if err := acl.CheckAccessHTTP(request, acl.SHOPIFY_JWT); err != nil {
acl.SendError(response, err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vtgate/querylogz.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ var (
// querylogzHandler serves a human readable snapshot of the
// current query log.
func querylogzHandler(ch chan any, w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vtgate/queryz.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (s *queryzSorter) Swap(i, j int) { s.rows[i], s.rows[j] = s.rows[j], s
func (s *queryzSorter) Less(i, j int) bool { return s.less(s.rows[i], s.rows[j]) }

func queryzHandler(e *Executor, w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vtgate/vtgate.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ func (vtg *VTGate) registerDebugEnvHandler() {

func (vtg *VTGate) registerDebugHealthHandler() {
http.HandleFunc("/debug/health", func(w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.MONITORING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vttablet/tabletserver/debugenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func addVar[T any](vars []envValue, name string, f func() T) []envValue {
}

func debugEnvHandler(tsv *TabletServer, w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vttablet/tabletserver/livequeryz.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ var (
)

func livequeryzHandler(queryLists []*QueryList, w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
if err := acl.CheckAccessHTTP(r, acl.SHOPIFY_JWT); err != nil {
acl.SendError(w, err)
return
}
Expand Down
Loading
Loading