@@ -16,11 +16,15 @@ import (
1616
1717// mockScopeFetcher is a mock implementation of scopes.FetcherInterface
1818type mockScopeFetcher struct {
19- scopes []string
20- err error
19+ scopes []string
20+ err error
21+ callCount int
22+ tokens []string
2123}
2224
23- func (m * mockScopeFetcher ) FetchTokenScopes (_ context.Context , _ string ) ([]string , error ) {
25+ func (m * mockScopeFetcher ) FetchTokenScopes (_ context.Context , token string ) ([]string , error ) {
26+ m .callCount += 1
27+ m .tokens = append (m .tokens , token )
2428 return m .scopes , m .err
2529}
2630
@@ -188,3 +192,40 @@ func TestWithPATScopes_PreservesExistingTokenInfo(t *testing.T) {
188192 assert .True (t , scopesFound )
189193 assert .Equal (t , []string {"repo" , "user" }, capturedScopes )
190194}
195+
196+ func TestWithPATScopes_RefetchesWhenCachedScopesBelongToDifferentToken (t * testing.T ) {
197+ logger := slog .Default ()
198+
199+ var capturedScopes []string
200+ var scopesFound bool
201+
202+ nextHandler := http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
203+ capturedScopes , scopesFound = ghcontext .GetTokenScopes (r .Context ())
204+ w .WriteHeader (http .StatusOK )
205+ })
206+
207+ fetcher := & mockScopeFetcher {
208+ scopes : []string {"read:org" },
209+ }
210+
211+ middleware := WithPATScopes (logger , fetcher )
212+ handler := middleware (nextHandler )
213+
214+ req := httptest .NewRequest (http .MethodGet , "/test" , nil )
215+ ctx := req .Context ()
216+ ctx = ghcontext .WithTokenInfo (ctx , & ghcontext.TokenInfo {
217+ Token : "ghp_new_token" ,
218+ TokenType : utils .TokenTypePersonalAccessToken ,
219+ })
220+ ctx = ghcontext .WithTokenScopesForToken (ctx , "ghp_old_token" , []string {"repo" })
221+ req = req .WithContext (ctx )
222+
223+ rr := httptest .NewRecorder ()
224+ handler .ServeHTTP (rr , req )
225+
226+ assert .True (t , scopesFound )
227+ assert .Equal (t , []string {"read:org" }, capturedScopes )
228+ assert .Equal (t , 1 , fetcher .callCount )
229+ require .Len (t , fetcher .tokens , 1 )
230+ assert .Equal (t , "ghp_new_token" , fetcher .tokens [0 ])
231+ }
0 commit comments