Skip to content

Commit 4548ef6

Browse files
committed
Fix race condition in OAuth callback channel handling
Use sync.Once to prevent double-close panic on tokChan when the HTTP handler is called concurrently or multiple times during the OAuth flow.
1 parent 42b506e commit 4548ef6

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

oauth/oauth.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import (
3333
"net/http"
3434
"os"
3535
"strconv"
36+
"sync"
3637
"time"
3738

3839
"github.com/dkorunic/e-dnevnik-bot/logger"
@@ -136,6 +137,8 @@ func getTokenFromWeb(ctx context.Context, config *oauth2.Config) (*oauth2.Token,
136137

137138
tokChan := make(chan string, 1)
138139

140+
var once sync.Once
141+
139142
// redirect uri listener for auth callback
140143
authListenHost := net.JoinHostPort(AuthListenAddr, strconv.Itoa(AuthListenPort))
141144
authURL := AuthScheme + authListenHost
@@ -190,13 +193,15 @@ func getTokenFromWeb(ctx context.Context, config *oauth2.Config) (*oauth2.Token,
190193
logger.Error().Msgf("template execution failed: %v", err)
191194
}
192195

193-
close(tokChan)
196+
once.Do(func() { close(tokChan) })
194197

195198
return
196199
}
197200

198-
tokChan <- req.URL.Query().Get("code")
199-
close(tokChan)
201+
once.Do(func() {
202+
tokChan <- req.URL.Query().Get("code")
203+
close(tokChan)
204+
})
200205

201206
if err := t.ExecuteTemplate(w, "success.html", map[string]any{}); err != nil {
202207
logger.Error().Msgf("template execution failed: %v", err)

0 commit comments

Comments
 (0)