Skip to content

The only tool you need to know what is happening and how to fix it.

fix: transactionality fix the store

dduxb9984fda95a6
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 9cebc639..8d85eb83 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -121,7 +121,7 @@ func RegisterControllers(router *gin.RouterGroup) {
// OAuth (Google, GitHub via markbates/goth)
router.GET("/auth/providers", OAuthController.ListProviders)
- router.GET("/auth/start/:provider", OAuthController.Begin)
+ router.GET("/auth/start/:provider", middleware.Transactional, OAuthController.Begin)
router.GET("/auth/callback/:provider", middleware.Transactional, OAuthController.Callback)
router.POST("/auth/finish-setup", middleware.UseAppAuth, middleware.Transactional, OAuthController.FinishSetup)
diff --git a/backend/app/middleware/transactional.middleware.go b/backend/app/middleware/transactional.middleware.go
index 1f8aca32..7c7a923d 100644
--- a/backend/app/middleware/transactional.middleware.go
+++ b/backend/app/middleware/transactional.middleware.go
@@ -2,6 +2,7 @@ package middleware
import (
"github.com/tracewayapp/traceway/backend/app/db"
+ "context"
"database/sql"
"net/http"
@@ -28,9 +29,11 @@ func Transactional(c *gin.Context) {
c.Set(TransactionContextKey, txHandle)
+ c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), TransactionContextKey, txHandle))
+
c.Next()
- if status := c.Writer.Status(); status == http.StatusOK || status == http.StatusCreated || status == http.StatusSeeOther {
+ if status := c.Writer.Status(); status >= 200 && status < 400 {
if err := txHandle.Commit(); err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
panic(err)
diff --git a/backend/app/services/oauth_session_store.go b/backend/app/services/oauth_session_store.go
index edf4a585..02d9ade5 100644
--- a/backend/app/services/oauth_session_store.go
+++ b/backend/app/services/oauth_session_store.go
@@ -2,7 +2,6 @@ package services
import (
"crypto/sha256"
- "database/sql"
"encoding/base32"
"errors"
"net/http"
@@ -19,11 +18,19 @@ import (
// DB. The cookie holds only a signed session ID; the session data (which can
// exceed the 4096-byte cookie limit for large OIDC ID tokens) lives in the
// oauth_sessions table.
+//
+// Contract: every route that hands a request to this store (directly or via
+// gothic) must be wrapped in middleware.Transactional so the request context
+// carries a *sql.Tx. The store reuses that tx rather than opening its own —
+// opening a second tx from the same handler would deadlock against the
+// single-connection SQLite main DB.
type dbSessionStore struct {
codecs []securecookie.Codec
options *sessions.Options
}
+var errNoTransaction = errors.New("oauth session store: no transaction in request context (route must use middleware.Transactional)")
+
func newDBSessionStore(secret string, options *sessions.Options) *dbSessionStore {
hashKey := []byte(secret)
blockKey := sha256.Sum256([]byte(secret + ":oauth-session-encryption"))
@@ -56,9 +63,11 @@ func (s *dbSessionStore) New(r *http.Request, name string) (*sessions.Session, e
return session, nil
}
- data, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]byte, error) {
- return repositories.OAuthSessionRepository.Get(tx, id)
- })
+ tx := db.GetTx(r.Context())
+ if tx == nil {
+ return session, errNoTransaction
+ }
+ data, err := repositories.OAuthSessionRepository.Get(tx, id)
if err != nil || data == nil {
return session, nil
}
@@ -72,11 +81,14 @@ func (s *dbSessionStore) New(r *http.Request, name string) (*sessions.Session, e
}
func (s *dbSessionStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
+ tx := db.GetTx(r.Context())
+ if tx == nil {
+ return errNoTransaction
+ }
+
if session.Options != nil && session.Options.MaxAge < 0 {
if session.ID != "" {
- if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
- return struct{}{}, repositories.OAuthSessionRepository.Delete(tx, session.ID)
- }); err != nil {
+ if err := repositories.OAuthSessionRepository.Delete(tx, session.ID); err != nil {
return err
}
}
@@ -98,9 +110,7 @@ func (s *dbSessionStore) Save(r *http.Request, w http.ResponseWriter, session *s
}
expires := time.Now().UTC().Add(time.Duration(session.Options.MaxAge) * time.Second)
- if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
- return struct{}{}, repositories.OAuthSessionRepository.Save(tx, session.ID, []byte(encoded), expires)
- }); err != nil {
+ if err := repositories.OAuthSessionRepository.Save(tx, session.ID, []byte(encoded), expires); err != nil {
return err
}
diff --git a/backend/cmd/run.go b/backend/cmd/run.go
index 039ab8ac..47b9b3c1 100644
--- a/backend/cmd/run.go
+++ b/backend/cmd/run.go
@@ -20,6 +20,7 @@ import (
"fmt"
"io/fs"
"net/http"
+ "os"
"strings"
"time"
@@ -66,6 +67,8 @@ func Run(opts ...Option) {
if o.disableLogging {
config.LoggingEnabled = false
}
+
+ applyOAuthEnvOverrides(cfg)
}
config.Init(cfg)
@@ -207,6 +210,39 @@ func Run(opts ...Option) {
}
}
+// applyOAuthEnvOverrides lets the dev-options path pick up OAuth/OIDC env vars
+// so embedded examples (e.g. devtesting-embedded) can be configured for SSO
+// testing without exposing every OIDC knob as a WithXxx option.
+func applyOAuthEnvOverrides(cfg *config.Cfg) {
+ for _, m := range []struct {
+ envVar string
+ dest *string
+ }{
+ {"OAUTH_SESSION_SECRET", &cfg.OAuthSessionSecret},
+ {"GOOGLE_CLIENT_ID", &cfg.GoogleClientID},
+ {"GOOGLE_CLIENT_SECRET", &cfg.GoogleClientSecret},
+ {"GITHUB_CLIENT_ID", &cfg.GitHubClientID},
+ {"GITHUB_CLIENT_SECRET", &cfg.GitHubClientSecret},
+ {"OIDC_CLIENT_ID", &cfg.OIDCClientID},
+ {"OIDC_CLIENT_SECRET", &cfg.OIDCClientSecret},
+ {"OIDC_DISCOVERY_URL", &cfg.OIDCDiscoveryURL},
+ {"OIDC_DISPLAY_NAME", &cfg.OIDCDisplayName},
+ {"OIDC_AUTO_CREATE_USERS", &cfg.OIDCAutoCreateUsers},
+ {"OIDC_ORG_CLAIM", &cfg.OIDCOrgClaim},
+ {"OIDC_EXTRA_SCOPES", &cfg.OIDCExtraScopes},
+ {"OIDC_ROLE_CLAIM", &cfg.OIDCRoleClaim},
+ {"OIDC_ROLE_MAP", &cfg.OIDCRoleMap},
+ {"OIDC_AUTH_URL", &cfg.OIDCAuthURL},
+ {"OIDC_TOKEN_URL", &cfg.OIDCTokenURL},
+ {"OIDC_USER_INFO_URL", &cfg.OIDCUserInfoURL},
+ {"DISABLE_PASSWORD_LOGIN", &cfg.DisablePasswordLogin},
+ } {
+ if v := os.Getenv(m.envVar); v != "" {
+ *m.dest = v
+ }
+ }
+}
+
func notifySystemd() {
sent, err := daemon.SdNotify(false, daemon.SdNotifyReady)
if err != nil {