Repository: supabase/gotrue
Pull request #662 (2022-09-04 21:41:57)

refactor: pass `GrantParams` object to `issueRefreshToken`
Passes an empty `models.GrantParams` object to `issueRefreshToken` as this is going to be used by SAML / MFA.


Patch:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 2d08ff59..ff3464a3 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,12 +1,15 @@
 name: Build and Release on Push to Master
 
 on:
+  workflow_dispatch:
+
   workflow_run:
     workflows: [Test]
     types: [completed]
     branches:
       - master
       - mfa
+      - zerosessionidfix
 
 jobs:
   release:
diff --git a/.releaserc b/.releaserc
index 9a1cc36c..9e263fff 100644
--- a/.releaserc
+++ b/.releaserc
@@ -4,6 +4,10 @@
     {
         "name": "mfa",
         "prerelease": true
+    },
+    {
+        "name": "zerosessionidfix",
+        "prerelease": true
     }
   ],
   "plugins": [
diff --git a/api/auth.go b/api/auth.go
index 6c42066c..797bc6fb 100644
--- a/api/auth.go
+++ b/api/auth.go
@@ -15,7 +15,7 @@ import (
 
 // requireAuthentication checks incoming requests for tokens presented using the Authorization header
 func (a *API) requireAuthentication(w http.ResponseWriter, r *http.Request) (context.Context, error) {
-	token, err := a.extractBearerToken(w, r)
+	token, err := a.extractBearerToken(r)
 	config := a.config
 	if err != nil {
 		a.clearCookieTokens(config, w)
@@ -53,7 +53,7 @@ func (a *API) requireAdmin(ctx context.Context, w http.ResponseWriter, r *http.R
 	return nil, unauthorizedError("User not allowed")
 }
 
-func (a *API) extractBearerToken(w http.ResponseWriter, r *http.Request) (string, error) {
+func (a *API) extractBearerToken(r *http.Request) (string, error) {
 	authHeader := r.Header.Get("Authorization")
 	matches := bearerRegexp.FindStringSubmatch(authHeader)
 	if len(matches) != 2 {
@@ -103,13 +103,13 @@ func (a *API) maybeLoadUserOrSession(ctx context.Context) (context.Context, erro
 	}
 
 	var session *models.Session
-	if claims.SessionId != "" {
+	if claims.SessionId != "" && claims.SessionId != uuid.Nil.String() {
 		sessionId, err := uuid.FromString(claims.SessionId)
 		if err != nil {
 			return ctx, err
 		}
 		session, err = models.FindSessionById(a.db, sessionId)
-		if err != nil {
+		if err != nil && !models.IsNotFoundError(err) {
 			return ctx, err
 		}
 		ctx = withSession(ctx, session)
diff --git a/api/context.go b/api/context.go
index 394e701e..f4d1737f 100644
--- a/api/context.go
+++ b/api/context.go
@@ -73,6 +73,9 @@ func withUser(ctx context.Context, u *models.User) context.Context {
 
 // getUser reads the user from the context.
 func getUser(ctx context.Context) *models.User {
+	if ctx == nil {
+		return nil
+	}
 	obj := ctx.Value(userKey)
 	if obj == nil {
 		return nil
@@ -87,6 +90,9 @@ func withSession(ctx context.Context, s *models.Session) context.Context {
 
 // getSession reads the session from the context.
 func getSession(ctx context.Context) *models.Session {
+	if ctx == nil {
+		return nil
+	}
 	obj := ctx.Value(sessionKey)
 	if obj == nil {
 		return nil
diff --git a/api/external.go b/api/external.go
index e005fb4e..5fa3b0a9 100644
--- a/api/external.go
+++ b/api/external.go
@@ -110,7 +110,9 @@ func (a *API) internalExternalProviderCallback(w http.ResponseWriter, r *http.Re
 	providerType := getExternalProviderType(ctx)
 	var userData *provider.UserProvidedData
 	var providerAccessToken string
-	var providerRefreshToken string = ""
+	var providerRefreshToken string
+	var grantParams models.GrantParams
+
 	if providerType == "twitter" {
 		// future OAuth1.0 providers will use this method
 		oAuthResponseData, err := a.oAuth1Callback(ctx, r, providerType)
@@ -275,7 +277,7 @@ func (a *API) internalExternalProviderCallback(w http.ResponseWriter, r *http.Re
 			}
 		}
 
-		token, terr = a.issueRefreshToken(ctx, tx, user)
+		token, terr = a.issueRefreshToken(ctx, tx, user, grantParams)
 		if terr != nil {
 			return oauthError("server_error", terr.Error())
 		}
diff --git a/api/magic_link.go b/api/magic_link.go
index 01d28ac3..8e743f00 100644
--- a/api/magic_link.go
+++ b/api/magic_link.go
@@ -15,8 +15,8 @@ import (
 
 // MagicLinkParams holds the parameters for a magic link request
 type MagicLinkParams struct {
-	Email    string                 `json:"email"`
-	Metadata map[string]interface{} `json:"metadata"`
+	Email string                 `json:"email"`
+	Data  map[string]interface{} `json:"metadata"`
 }
 
 // MagicLink sends a recovery email
@@ -35,8 +35,8 @@ func (a *API) MagicLink(w http.ResponseWriter, r *http.Request) error {
 		return badRequestError("Could not read verification params: %v", err)
 	}
 
-	if params.Metadata == nil {
-		params.Metadata = make(map[string]interface{})
+	if params.Data == nil {
+		params.Data = make(map[string]interface{})
 	}
 
 	if params.Email == "" {
@@ -59,7 +59,7 @@ func (a *API) MagicLink(w http.ResponseWriter, r *http.Request) error {
 			signUpParams := &SignupParams{
 				Email:    params.Email,
 				Password: password,
-				Data:     params.Metadata,
+				Data:     params.Data,
 			}
 			newBodyContent, err := json.Marshal(signUpParams)
 			if err != nil {
@@ -76,7 +76,7 @@ func (a *API) MagicLink(w http.ResponseWriter, r *http.Request) error {
 				}
 				newBodyContent := &SignupParams{
 					Email: params.Email,
-					Data:  params.Metadata,
+					Data:  params.Data,
 				}
 				metadata, err := json.Marshal(newBodyContent)
 				if err != nil {
diff --git a/api/middleware.go b/api/middleware.go
index 69c76701..ff604d96 100644
--- a/api/middleware.go
+++ b/api/middleware.go
@@ -97,7 +97,7 @@ func (a *API) limitEmailSentHandler() middlewareHandler {
 }
 
 func (a *API) requireAdminCredentials(w http.ResponseWriter, req *http.Request) (context.Context, error) {
-	t, err := a.extractBearerToken(w, req)
+	t, err := a.extractBearerToken(req)
 	if err != nil || t == "" {
 		return nil, err
 	}
diff --git a/api/otp.go b/api/otp.go
index da626f5d..6aa4c84e 100644
--- a/api/otp.go
+++ b/api/otp.go
@@ -17,13 +17,13 @@ type OtpParams struct {
 	Email      string                 `json:"email"`
 	Phone      string                 `json:"phone"`
 	CreateUser bool                   `json:"create_user"`
-	Metadata   map[string]interface{} `json:"metadata"`
+	Data       map[string]interface{} `json:"data"`
 }
 
 // SmsParams contains the request body params for sms otp
 type SmsParams struct {
-	Phone    string                 `json:"phone"`
-	Metadata map[string]interface{} `json:"metadata"`
+	Phone string                 `json:"phone"`
+	Data  map[string]interface{} `json:"data"`
 }
 
 // Otp returns the MagicLink or SmsOtp handler based on the request body params
@@ -31,8 +31,8 @@ func (a *API) Otp(w http.ResponseWriter, r *http.Request) error {
 	params := &OtpParams{
 		CreateUser: true,
 	}
-	if params.Metadata == nil {
-		params.Metadata = make(map[string]interface{})
+	if params.Data == nil {
+		params.Data = make(map[string]interface{})
 	}
 
 	body, err := getBodyBytes(r)
@@ -82,8 +82,8 @@ func (a *API) SmsOtp(w http.ResponseWriter, r *http.Request) error {
 	if err := json.Unmarshal(body, params); err != nil {
 		return badRequestError("Could not read sms otp params: %v", err)
 	}
-	if params.Metadata == nil {
-		params.Metadata = make(map[string]interface{})
+	if params.Data == nil {
+		params.Data = make(map[string]interface{})
 	}
 
 	params.Phone, err = a.validatePhone(params.Phone)
@@ -105,7 +105,7 @@ func (a *API) SmsOtp(w http.ResponseWriter, r *http.Request) error {
 			signUpParams := &SignupParams{
 				Phone:    params.Phone,
 				Password: password,
-				Data:     params.Metadata,
+				Data:     params.Data,
 			}
 			newBodyContent, err := json.Marshal(signUpParams)
 			if err != nil {
diff --git a/api/signup.go b/api/signup.go
index a2ea8f5a..175aecda 100644
--- a/api/signup.go
+++ b/api/signup.go
@@ -64,6 +64,7 @@ func (a *API) Signup(w http.ResponseWriter, r *http.Request) error {
 	}
 
 	var user *models.User
+	var grantParams models.GrantParams
 	params.Aud = a.requestAud(ctx, r)
 
 	switch params.Provider {
@@ -218,7 +219,7 @@ func (a *API) Signup(w http.ResponseWriter, r *http.Request) error {
 				return terr
 			}
 
-			token, terr = a.issueRefreshToken(ctx, tx, user)
+			token, terr = a.issueRefreshToken(ctx, tx, user, grantParams)
 			if terr != nil {
 				return terr
 			}
diff --git a/api/token.go b/api/token.go
index cd535670..8d17bf08 100644
--- a/api/token.go
+++ b/api/token.go
@@ -11,6 +11,7 @@ import (
 	"time"
 
 	"github.com/coreos/go-oidc/v3/oidc"
+	"github.com/gofrs/uuid"
 	"github.com/golang-jwt/jwt"
 	"github.com/netlify/gotrue/conf"
 	"github.com/netlify/gotrue/metering"
@@ -26,7 +27,7 @@ type GoTrueClaims struct {
 	AppMetaData  map[string]interface{} `json:"app_metadata"`
 	UserMetaData map[string]interface{} `json:"user_metadata"`
 	Role         string                 `json:"role"`
-	SessionId    string                 `json:"session_id"`
+	SessionId    string                 `json:"session_id,omitempty"`
 }
 
 // AccessTokenResponse represents an OAuth2 success response
@@ -171,6 +172,7 @@ func (a *API) ResourceOwnerPasswordGrant(ctx context.Context, w http.ResponseWri
 		return unprocessableEntityError("Only an email address or phone number should be provided on login.")
 	}
 	var user *models.User
+	var grantParams models.GrantParams
 	var provider string
 	if params.Email != "" {
 		provider = "email"
@@ -218,7 +220,7 @@ func (a *API) ResourceOwnerPasswordGrant(ctx context.Context, w http.ResponseWri
 			return terr
 		}
 
-		token, terr = a.issueRefreshToken(ctx, tx, user)
+		token, terr = a.issueRefreshToken(ctx, tx, user, grantParams)
 		if terr != nil {
 			return terr
 		}
@@ -325,7 +327,7 @@ func (a *API) RefreshTokenGrant(ctx context.Context, w http.ResponseWriter, r *h
 			}
 		}
 
-		tokenString, terr = generateAccessToken(user, newToken.SessionId.UUID.String(), time.Second*time.Duration(config.JWT.Exp), config.JWT.Secret)
+		tokenString, terr = generateAccessToken(user, newToken.SessionId, time.Second*time.Duration(config.JWT.Exp), config.JWT.Secret)
 		if terr != nil {
 			return internalServerError("error generating jwt token").WithInternalError(terr)
 		}
@@ -419,6 +421,7 @@ func (a *API) IdTokenGrant(ctx context.Context, w http.ResponseWriter, r *http.R
 	}
 
 	var user *models.User
+	var grantParams models.GrantParams
 	var token *AccessTokenResponse
 	err = a.db.Transaction(func(tx *storage.Connection) error {
 		var terr error
@@ -507,7 +510,7 @@ func (a *API) IdTokenGrant(ctx context.Context, w http.ResponseWriter, r *http.R
 			}
 		}
 
-		token, terr = a.issueRefreshToken(ctx, tx, user)
+		token, terr = a.issueRefreshToken(ctx, tx, user, grantParams)
 		if terr != nil {
 			return oauthError("server_error", terr.Error())
 		}
@@ -526,7 +529,11 @@ func (a *API) IdTokenGrant(ctx context.Context, w http.ResponseWriter, r *http.R
 	return sendJSON(w, http.StatusOK, token)
 }
 
-func generateAccessToken(user *models.User, sessionId string, expiresIn time.Duration, secret string) (string, error) {
+func generateAccessToken(user *models.User, sessionId *uuid.UUID, expiresIn time.Duration, secret string) (string, error) {
+	sid := ""
+	if sessionId != nil {
+		sid = sessionId.String()
+	}
 	claims := &GoTrueClaims{
 		StandardClaims: jwt.StandardClaims{
 			Subject:   user.ID.String(),
@@ -538,14 +545,14 @@ func generateAccessToken(user *models.User, sessionId string, expiresIn time.Dur
 		AppMetaData:  user.AppMetaData,
 		UserMetaData: user.UserMetaData,
 		Role:         user.Role,
-		SessionId:    sessionId,
+		SessionId:    sid,
 	}
 
 	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
 	return token.SignedString([]byte(secret))
 }
 
-func (a *API) issueRefreshToken(ctx context.Context, conn *storage.Connection, user *models.User) (*AccessTokenResponse, error) {
+func (a *API) issueRefreshToken(ctx context.Context, conn *storage.Connection, user *models.User, grantParams models.GrantParams) (*AccessTokenResponse, error) {
 	config := a.config
 
 	now := time.Now()
@@ -556,12 +563,12 @@ func (a *API) issueRefreshToken(ctx context.Context, conn *storage.Connection, u
 
 	err := conn.Transaction(func(tx *storage.Connection) error {
 		var terr error
-		refreshToken, terr = models.GrantAuthenticatedUser(tx, user, models.GrantParams{})
+		refreshToken, terr = models.GrantAuthenticatedUser(tx, user, grantParams)
 		if terr != nil {
 			return internalServerError("Database error granting user").WithInternalError(terr)
 		}
 
-		tokenString, terr = generateAccessToken(user, refreshToken.SessionId.UUID.String(), time.Second*time.Duration(config.JWT.Exp), config.JWT.Secret)
+		tokenString, terr = generateAccessToken(user, refreshToken.SessionId, time.Second*time.Duration(config.JWT.Exp), config.JWT.Secret)
 		if terr != nil {
 			return internalServerError("error generating jwt token").WithInternalError(terr)
 		}
diff --git a/api/verify.go b/api/verify.go
index 07890cf4..c46827de 100644
--- a/api/verify.go
+++ b/api/verify.go
@@ -77,9 +77,10 @@ func (a *API) verifyGet(w http.ResponseWriter, r *http.Request) error {
 	params.RedirectTo = a.getRedirectURLOrReferrer(r, r.FormValue("redirect_to"))
 
 	var (
-		user  *models.User
-		err   error
-		token *AccessTokenResponse
+		user        *models.User
+		grantParams models.GrantParams
+		err         error
+		token       *AccessTokenResponse
 	)
 
 	err = a.db.Transaction(func(tx *storage.Connection) error {
@@ -121,7 +122,7 @@ func (a *API) verifyGet(w http.ResponseWriter, r *http.Request) error {
 			return terr
 		}
 
-		token, terr = a.issueRefreshToken(ctx, tx, user)
+		token, terr = a.issueRefreshToken(ctx, tx, user, grantParams)
 		if terr != nil {
 			return terr
 		}
@@ -182,8 +183,9 @@ func (a *API) verifyPost(w http.ResponseWriter, r *http.Request) error {
 	}
 
 	var (
-		user  *models.User
-		token *AccessTokenResponse
+		user        *models.User
+		grantParams models.GrantParams
+		token       *AccessTokenResponse
 	)
 
 	err = a.db.Transaction(func(tx *storage.Connection) error {
@@ -217,7 +219,7 @@ func (a *API) verifyPost(w http.ResponseWriter, r *http.Request) error {
 			return terr
 		}
 
-		token, terr = a.issueRefreshToken(ctx, tx, user)
+		token, terr = a.issueRefreshToken(ctx, tx, user, grantParams)
 		if terr != nil {
 			return terr
 		}
diff --git a/cmd/migrate_cmd.go b/cmd/migrate_cmd.go
index 3b355c9f..469be24e 100644
--- a/cmd/migrate_cmd.go
+++ b/cmd/migrate_cmd.go
@@ -32,7 +32,7 @@ func migrate(cmd *cobra.Command, args []string) {
 		globalConfig.DB.Driver = u.Scheme
 	}
 
-	log := logrus.New()
+	log := logrus.StandardLogger()
 
 	pop.Debug = false
 	if globalConfig.Logging.Level != "" {
diff --git a/conf/configuration.go b/conf/configuration.go
index d87b41b1..de25c141 100644
--- a/conf/configuration.go
+++ b/conf/configuration.go
@@ -259,11 +259,11 @@ func LoadGlobal(filename string) (*GlobalConfiguration, error) {
 		return nil, err
 	}
 
-	if err := config.Validate(); err != nil {
+	if err := ConfigureLogging(&config.Logging); err != nil {
 		return nil, err
 	}
 
-	if _, err := ConfigureLogging(&config.Logging); err != nil {
+	if err := config.Validate(); err != nil {
 		return nil, err
 	}
 
diff --git a/conf/logging.go b/conf/logging.go
index 831b3af9..e28bd0f5 100644
--- a/conf/logging.go
+++ b/conf/logging.go
@@ -2,11 +2,18 @@ package conf
 
 import (
 	"os"
-	"time"
 
+	"github.com/gobuffalo/pop/v5"
+	"github.com/gobuffalo/pop/v5/logging"
 	"github.com/sirupsen/logrus"
 )
 
+const (
+	LOG_SQL_ALL       = "all"
+	LOG_SQL_NONE      = "none"
+	LOG_SQL_STATEMENT = "statement"
+)
+
 type LoggingConfig struct {
 	Level            string                 `mapstructure:"log_level" json:"log_level"`
 	File             string                 `mapstructure:"log_file" json:"log_file"`
@@ -14,47 +21,78 @@ type LoggingConfig struct {
 	QuoteEmptyFields bool                   `mapstructure:"quote_empty_fields" split_words:"true" json:"quote_empty_fields"`
 	TSFormat         string                 `mapstructure:"ts_format" json:"ts_format"`
 	Fields           map[string]interface{} `mapstructure:"fields" json:"fields"`
+	SQL              string                 `mapstructure:"sql" json:"sql"`
 }
 
-func ConfigureLogging(config *LoggingConfig) (*logrus.Entry, error) {
-	logger := logrus.New()
-
-	tsFormat := time.RFC3339Nano
-	if config.TSFormat != "" {
-		tsFormat = config.TSFormat
-	}
-	// always use the full timestamp
-	logger.SetFormatter(&logrus.TextFormatter{
-		FullTimestamp:    true,
-		DisableTimestamp: false,
-		TimestampFormat:  tsFormat,
-		DisableColors:    config.DisableColors,
-		QuoteEmptyFields: config.QuoteEmptyFields,
-	})
+func ConfigureLogging(config *LoggingConfig) error {
+	logrus.SetFormatter(&logrus.JSONFormatter{})
 
 	// use a file if you want
 	if config.File != "" {
 		f, errOpen := os.OpenFile(config.File, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660) //#nosec G302 -- Log files should be rw-rw-r--
 		if errOpen != nil {
-			return nil, errOpen
+			return errOpen
 		}
-		logger.SetOutput(f)
-		logger.Infof("Set output file to %s", config.File)
+		logrus.SetOutput(f)
+		logrus.Infof("Set output file to %s", config.File)
 	}
 
 	if config.Level != "" {
 		level, err := logrus.ParseLevel(config.Level)
 		if err != nil {
-			return nil, err
+			return err
 		}
-		logger.SetLevel(level)
-		logger.Debug("Set log level to: " + logger.GetLevel().String())
+		logrus.SetLevel(level)
+		logrus.Debug("Set log level to: " + logrus.GetLevel().String())
 	}
 
 	f := logrus.Fields{}
 	for k, v := range config.Fields {
 		f[k] = v
 	}
+	logrus.WithFields(f)
+
+	setPopLogger(config.SQL)
+
+	return nil
+}
+
+func setPopLogger(sql string) {
+	popLog := logrus.WithField("component", "pop")
+	sqlLog := logrus.WithField("component", "sql")
 
-	return logger.WithFields(f), nil
+	shouldLogSQL := sql == LOG_SQL_STATEMENT || sql == LOG_SQL_ALL
+	shouldLogSQLArgs := sql == LOG_SQL_ALL
+
+	pop.SetLogger(func(lvl logging.Level, s string, args ...interface{}) {
+		// Special case SQL logging since we have 2 extra flags to check
+		if lvl == logging.SQL {
+			if !shouldLogSQL {
+				return
+			}
+
+			if shouldLogSQLArgs && len(args) > 0 {
+				sqlLog.WithField("args", args).Info(s)
+			} else {
+				sqlLog.Info(s)
+			}
+			return
+		}
+
+		l := popLog
+		if len(args) > 0 {
+			l = l.WithField("args", args)
+		}
+
+		switch lvl {
+		case logging.Debug:
+			l.Debug(s)
+		case logging.Info:
+			l.Info(s)
+		case logging.Warn:
+			l.Warn(s)
+		case logging.Error:
+			l.Error(s)
+		}
+	})
 }
diff --git a/logger/log.go b/logger/log.go
index 705acfb4..028cb541 100644
--- a/logger/log.go
+++ b/logger/log.go
@@ -11,9 +11,6 @@ import (
 )
 
 func NewStructuredLogger(logger *logrus.Logger) func(next http.Handler) http.Handler {
-	logger.Formatter = &logrus.JSONFormatter{
-		DisableTimestamp: true,
-	}
 	return chimiddleware.RequestLogger(&structuredLogger{logger})
 }
 
diff --git a/mailer/mailer.go b/mailer/mailer.go
index 266944f3..b9d634b4 100644
--- a/mailer/mailer.go
+++ b/mailer/mailer.go
@@ -40,7 +40,7 @@ func NewMailer(instanceConfig *conf.GlobalConfiguration) Mailer {
 			Pass:    instanceConfig.SMTP.Pass,
 			From:    from,
 			BaseURL: instanceConfig.SiteURL,
-			Logger:  logrus.New(),
+			Logger:  logrus.StandardLogger(),
 		}
 	}
 
diff --git a/models/errors.go b/models/errors.go
index d2b6fe64..773cc852 100644
--- a/models/errors.go
+++ b/models/errors.go
@@ -3,19 +3,19 @@ package models
 // IsNotFoundError returns whether an error represents a "not found" error.
 func IsNotFoundError(err error) bool {
 	switch err.(type) {
-	case UserNotFoundError:
+	case UserNotFoundError, *UserNotFoundError:
 		return true
-	case SessionNotFoundError:
+	case SessionNotFoundError, *SessionNotFoundError:
 		return true
-	case ConfirmationTokenNotFoundError:
+	case ConfirmationTokenNotFoundError, *ConfirmationTokenNotFoundError:
 		return true
-	case RefreshTokenNotFoundError:
+	case RefreshTokenNotFoundError, *RefreshTokenNotFoundError:
 		return true
-	case InstanceNotFoundError:
+	case InstanceNotFoundError, *InstanceNotFoundError:
 		return true
-	case TotpSecretNotFoundError:
+	case TotpSecretNotFoundError, *TotpSecretNotFoundError:
 		return true
-	case IdentityNotFoundError:
+	case IdentityNotFoundError, *IdentityNotFoundError:
 		return true
 	}
 	return false
diff --git a/models/refresh_token.go b/models/refresh_token.go
index eb2ab3d5..847244ff 100644
--- a/models/refresh_token.go
+++ b/models/refresh_token.go
@@ -5,7 +5,6 @@ import (
 	"net/http"
 	"time"
 
-	"github.com/gobuffalo/nulls"
 	"github.com/gobuffalo/pop/v5"
 	"github.com/gofrs/uuid"
 	"github.com/netlify/gotrue/crypto"
@@ -22,7 +21,7 @@ type RefreshToken struct {
 	UserID uuid.UUID `db:"user_id"`
 
 	Parent    storage.NullString `db:"parent"`
-	SessionId nulls.UUID         `db:"session_id"`
+	SessionId *uuid.UUID         `db:"session_id"`
 
 	Revoked   bool      `db:"revoked"`
 	CreatedAt time.Time `db:"created_at"`
@@ -69,7 +68,7 @@ func GrantRefreshTokenSwap(r *http.Request, tx *storage.Connection, user *User,
 func RevokeTokenFamily(tx *storage.Connection, token *RefreshToken) error {
 	var err error
 	tablename := (&pop.Model{Value: RefreshToken{}}).TableName()
-	if token.SessionId.Valid && len(token.SessionId.UUID) > 0 {
+	if token.SessionId != nil {
 		err = tx.RawQuery(`update `+tablename+` set revoked = true where session_id = ?;`, token.SessionId).Exec()
 	} else {
 		err = tx.RawQuery(`
@@ -108,12 +107,15 @@ func createRefreshToken(tx *storage.Connection, user *User, oldToken *RefreshTok
 	if oldToken != nil {
 		token.Parent = storage.NullString(oldToken.Token)
 		token.SessionId = oldToken.SessionId
-	} else {
+	}
+
+	if token.SessionId == nil {
+		// Existing refresh tokens may have a null session_id if they were created before v2.15.3
 		session, err := CreateSession(tx, user)
 		if err != nil {
 			return nil, errors.Wrap(err, "Error generated unique session id")
 		}
-		token.SessionId = nulls.NewUUID(session.ID)
+		token.SessionId = &session.ID
 	}
 
 	if err := tx.Create(token); err != nil {
diff --git a/storage/dial.go b/storage/dial.go
index 2a78d3d1..47c3af60 100644
--- a/storage/dial.go
+++ b/storage/dial.go
@@ -41,10 +41,6 @@ func Dial(config *conf.GlobalConfiguration) (*Connection, error) {
 	if err := db.Open(); err != nil {
 		return nil, errors.Wrap(err, "checking database connection")
 	}
-	if logrus.StandardLogger().Level == logrus.DebugLevel {
-		pop.Debug = true
-	}
-
 	return &Connection{db}, nil
 }
 


Test patch:
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 6331afc0..4e35d79b 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -7,6 +7,7 @@ on:
       - master
       - mfa
       - saml
+      - zerosessionidfix
     tags: ['*']
 
 jobs:
diff --git a/api/audit_test.go b/api/audit_test.go
index ad868de3..0c65c565 100644
--- a/api/audit_test.go
+++ b/api/audit_test.go
@@ -48,7 +48,7 @@ func (ts *AuditTestSuite) makeSuperAdmin(email string) string {
 
 	u.Role = "supabase_admin"
 
-	token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+	token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 	require.NoError(ts.T(), err, "Error generating access token")
 
 	p := jwt.Parser{ValidMethods: []string{jwt.SigningMethodHS256.Name}}
diff --git a/api/auth_test.go b/api/auth_test.go
new file mode 100644
index 00000000..24a9995f
--- /dev/null
+++ b/api/auth_test.go
@@ -0,0 +1,168 @@
+package api
+
+import (
+	"errors"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/gofrs/uuid"
+	jwt "github.com/golang-jwt/jwt"
+	"github.com/netlify/gotrue/conf"
+	"github.com/netlify/gotrue/models"
+	"github.com/stretchr/testify/require"
+	"github.com/stretchr/testify/suite"
+)
+
+type AuthTestSuite struct {
+	suite.Suite
+	API    *API
+	Config *conf.GlobalConfiguration
+}
+
+func TestAuth(t *testing.T) {
+	api, config, err := setupAPIForTest()
+	require.NoError(t, err)
+
+	ts := &AuthTestSuite{
+		API:    api,
+		Config: config,
+	}
+	defer api.db.Close()
+	suite.Run(t, ts)
+}
+
+func (ts *AuthTestSuite) SetupTest() {
+	models.TruncateAll(ts.API.db)
+
+	// Create user
+	u, err := models.NewUser("", "test@example.com", "password", ts.Config.JWT.Aud, nil)
+	require.NoError(ts.T(), err, "Error creating test user model")
+	require.NoError(ts.T(), ts.API.db.Create(u), "Error saving new test user")
+}
+
+func (ts *AuthTestSuite) TestExtractBearerToken() {
+	userClaims := &GoTrueClaims{
+		Role: "authenticated",
+	}
+	userJwt, err := jwt.NewWithClaims(jwt.SigningMethodHS256, userClaims).SignedString([]byte(ts.Config.JWT.Secret))
+	require.NoError(ts.T(), err)
+	req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
+	req.Header.Set("Authorization", "Bearer "+userJwt)
+
+	token, err := ts.API.extractBearerToken(req)
+	require.NoError(ts.T(), err)
+	require.Equal(ts.T(), userJwt, token)
+}
+
+func (ts *AuthTestSuite) TestParseJWTClaims() {
+	userClaims := &GoTrueClaims{
+		Role: "authenticated",
+	}
+	userJwt, err := jwt.NewWithClaims(jwt.SigningMethodHS256, userClaims).SignedString([]byte(ts.Config.JWT.Secret))
+	require.NoError(ts.T(), err)
+
+	req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
+	req.Header.Set("Authorization", "Bearer "+userJwt)
+	w := httptest.NewRecorder()
+	ctx, err := ts.API.parseJWTClaims(userJwt, req, w)
+	require.NoError(ts.T(), err)
+
+	// check if token is stored in context
+	token := getToken(ctx)
+	require.Equal(ts.T(), userJwt, token.Raw)
+}
+
+func (ts *AuthTestSuite) TestMaybeLoadUserOrSession() {
+	u, err := models.FindUserByEmailAndAudience(ts.API.db, "test@example.com", ts.Config.JWT.Aud)
+	require.NoError(ts.T(), err)
+
+	s, err := models.CreateSession(ts.API.db, u)
+	require.NoError(ts.T(), err)
+
+	cases := []struct {
+		Desc            string
+		UserJwtClaims   *GoTrueClaims
+		ExpectedError   error
+		ExpectedUser    *models.User
+		ExpectedSession *models.Session
+	}{
+		{
+			Desc: "Missing Subject Claim",
+			UserJwtClaims: &GoTrueClaims{
+				StandardClaims: jwt.StandardClaims{
+					Subject: "",
+				},
+				Role: "authenticated",
+			},
+			ExpectedError: errors.New("invalid claim: subject missing"),
+			ExpectedUser:  nil,
+		},
+		{
+			Desc: "Valid Subject Claim",
+			UserJwtClaims: &GoTrueClaims{
+				StandardClaims: jwt.StandardClaims{
+					Subject: u.ID.String(),
+				},
+				Role: "authenticated",
+			},
+			ExpectedError: nil,
+			ExpectedUser:  u,
+		},
+		{
+			Desc: "Empty Session ID Claim",
+			UserJwtClaims: &GoTrueClaims{
+				StandardClaims: jwt.StandardClaims{
+					Subject: u.ID.String(),
+				},
+				Role:      "authenticated",
+				SessionId: "",
+			},
+			ExpectedError: nil,
+			ExpectedUser:  u,
+		},
+		{
+			Desc: "Invalid Session ID Claim",
+			UserJwtClaims: &GoTrueClaims{
+				StandardClaims: jwt.StandardClaims{
+					Subject: u.ID.String(),
+				},
+				Role:      "authenticated",
+				SessionId: uuid.Nil.String(),
+			},
+			ExpectedError: nil,
+			ExpectedUser:  u,
+		},
+		{
+			Desc: "Valid Session ID Claim",
+			UserJwtClaims: &GoTrueClaims{
+				StandardClaims: jwt.StandardClaims{
+					Subject: u.ID.String(),
+				},
+				Role:      "authenticated",
+				SessionId: s.ID.String(),
+			},
+			ExpectedError:   nil,
+			ExpectedUser:    u,
+			ExpectedSession: s,
+		},
+	}
+
+	for _, c := range cases {
+		ts.Run(c.Desc, func() {
+			userJwt, err := jwt.NewWithClaims(jwt.SigningMethodHS256, c.UserJwtClaims).SignedString([]byte(ts.Config.JWT.Secret))
+			require.NoError(ts.T(), err)
+
+			req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
+			req.Header.Set("Authorization", "Bearer "+userJwt)
+
+			w := httptest.NewRecorder()
+			ctx, err := ts.API.parseJWTClaims(userJwt, req, w)
+			require.NoError(ts.T(), err)
+			ctx, err = ts.API.maybeLoadUserOrSession(ctx)
+			require.Equal(ts.T(), c.ExpectedError, err)
+			require.Equal(ts.T(), c.ExpectedUser, getUser(ctx))
+			require.Equal(ts.T(), c.ExpectedSession, getSession(ctx))
+		})
+	}
+}
diff --git a/api/invite_test.go b/api/invite_test.go
index 52a8e092..70cccea3 100644
--- a/api/invite_test.go
+++ b/api/invite_test.go
@@ -58,7 +58,7 @@ func (ts *InviteTestSuite) makeSuperAdmin(email string) string {
 
 	u.Role = "supabase_admin"
 
-	token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+	token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 	require.NoError(ts.T(), err, "Error generating access token")
 
 	p := jwt.Parser{ValidMethods: []string{jwt.SigningMethodHS256.Name}}
diff --git a/api/otp_test.go b/api/otp_test.go
index db240282..8154459c 100644
--- a/api/otp_test.go
+++ b/api/otp_test.go
@@ -51,7 +51,7 @@ func (ts *OtpTestSuite) TestOtp() {
 			OtpParams{
 				Email:      "test@example.com",
 				CreateUser: true,
-				Metadata: map[string]interface{}{
+				Data: map[string]interface{}{
 					"somedata": "metadata",
 				},
 			},
diff --git a/api/phone_test.go b/api/phone_test.go
index 5f5f9cc6..31434f97 100644
--- a/api/phone_test.go
+++ b/api/phone_test.go
@@ -126,7 +126,7 @@ func (ts *PhoneTestSuite) TestMissingSmsProviderConfig() {
 	u.PhoneConfirmedAt = &now
 	require.NoError(ts.T(), ts.API.db.Update(u), "Error updating new test user")
 
-	token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+	token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 	require.NoError(ts.T(), err)
 
 	cases := []struct {
diff --git a/api/user_test.go b/api/user_test.go
index 83163bd1..8a0d5fc9 100644
--- a/api/user_test.go
+++ b/api/user_test.go
@@ -47,7 +47,7 @@ func (ts *UserTestSuite) SetupTest() {
 func (ts *UserTestSuite) TestUserGet() {
 	u, err := models.FindUserByEmailAndAudience(ts.API.db, "test@example.com", ts.Config.JWT.Aud)
 	require.NoError(ts.T(), err, "Error finding user")
-	token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+	token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 	require.NoError(ts.T(), err, "Error generating access token")
 
 	req := httptest.NewRequest(http.MethodGet, "http://localhost/user", nil)
@@ -111,7 +111,7 @@ func (ts *UserTestSuite) TestUserUpdateEmail() {
 			require.NoError(ts.T(), u.SetPhone(ts.API.db, c.userData["phone"]), "Error setting user phone")
 			require.NoError(ts.T(), ts.API.db.Create(u), "Error saving test user")
 
-			token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+			token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 			require.NoError(ts.T(), err, "Error generating access token")
 
 			var buffer bytes.Buffer
@@ -170,7 +170,7 @@ func (ts *UserTestSuite) TestUserUpdatePhoneAutoconfirmEnabled() {
 
 	for _, c := range cases {
 		ts.Run(c.desc, func() {
-			token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+			token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 			require.NoError(ts.T(), err, "Error generating access token")
 
 			var buffer bytes.Buffer
@@ -244,7 +244,7 @@ func (ts *UserTestSuite) TestUserUpdatePassword() {
 			req := httptest.NewRequest(http.MethodPut, "http://localhost/user", &buffer)
 			req.Header.Set("Content-Type", "application/json")
 
-			token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+			token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 			require.NoError(ts.T(), err)
 			req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
 
@@ -272,7 +272,7 @@ func (ts *UserTestSuite) TestUserUpdatePasswordReauthentication() {
 	u.EmailConfirmedAt = &now
 	require.NoError(ts.T(), ts.API.db.Update(u), "Error updating new test user")
 
-	token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+	token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 	require.NoError(ts.T(), err)
 
 	// request for reauthentication nonce
diff --git a/api/verify_test.go b/api/verify_test.go
index 3b17a75c..8482a1ef 100644
--- a/api/verify_test.go
+++ b/api/verify_test.go
@@ -103,7 +103,7 @@ func (ts *VerifyTestSuite) TestVerifySecureEmailChange() {
 	req.Header.Set("Content-Type", "application/json")
 
 	// Generate access token for request
-	token, err := generateAccessToken(u, "", time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
+	token, err := generateAccessToken(u, nil, time.Second*time.Duration(ts.Config.JWT.Exp), ts.Config.JWT.Secret)
 	require.NoError(ts.T(), err)
 	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
 
diff --git a/hack/test.env b/hack/test.env
index f76624d6..f076a5a8 100644
--- a/hack/test.env
+++ b/hack/test.env
@@ -9,7 +9,8 @@ GOTRUE_DB_AUTOMIGRATE=true
 DATABASE_URL="postgres://supabase_auth_admin:root@localhost:5432/postgres"
 GOTRUE_API_HOST=localhost
 PORT=9999
-GOTRUE_LOG_LEVEL=debug
+GOTRUE_LOG_SQL=none
+GOTRUE_LOG_LEVEL=warn
 GOTRUE_SITE_URL=https://example.netlify.com
 GOTRUE_URI_ALLOW_LIST="http://localhost:3000"
 GOTRUE_OPERATOR_TOKEN=foobar