{"record":{"id":"ef97fbe755158e93","repo":"Tencent/WeKnora","slug":"oauth-state-not-found-or-expired","errorCode":null,"errorMessage":"oauth state not found or expired","messagePattern":"oauth state not found or expired","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/mcp/oauth_state.go","lineNumber":192,"sourceCode":"\t}\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tentry, ok := s.attempts[state]\n\tif !ok || time.Now().After(entry.expiresAt) {\n\t\tdelete(s.attempts, state)\n\t\treturn OAuthAttempt{}, fmt.Errorf(\"oauth attempt not found or expired\")\n\t}\n\treturn entry.value, nil\n}\n\n// Take retrieves and deletes a state (single-use). Returns an error if the\n// state is unknown or expired.\nfunc (s *oauthStateStore) Take(ctx context.Context, state string) (OAuthState, error) {\n\tif s.rdb != nil {\n\t\tdata, err := s.rdb.GetDel(ctx, s.key(state)).Bytes()\n\t\tif err != nil {\n\t\t\tif err == redis.Nil {\n\t\t\t\treturn OAuthState{}, fmt.Errorf(\"oauth state not found or expired\")\n\t\t\t}\n\t\t\treturn OAuthState{}, err\n\t\t}\n\t\tvar v OAuthState\n\t\tif err := json.Unmarshal(data, &v); err != nil {\n\t\t\treturn OAuthState{}, err\n\t\t}\n\t\treturn v, nil\n\t}\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tentry, ok := s.mem[state]\n\tif !ok {\n\t\treturn OAuthState{}, fmt.Errorf(\"oauth state not found or expired\")\n\t}\n\tdelete(s.mem, state)\n\tif time.Now().After(entry.expiresAt) {\n\t\treturn OAuthState{}, fmt.Errorf(\"oauth state not found or expired\")","sourceCodeStart":174,"sourceCodeEnd":210,"githubUrl":"https://github.com/Tencent/WeKnora/blob/988cbb03305e055d8ebb7d46d9ac6cc0803cd074/internal/mcp/oauth_state.go#L174-L210","documentation":"Take retrieves and deletes the OAuthState (single-use CSRF state) during the callback. In Redis-backed mode a missing key (redis.Nil) returns this error. Because Take is get-and-delete, this error also fires on any second use of the same state.","triggerScenarios":"CompleteAuthorization calls Take with a state whose Redis key is gone — expired TTL, Redis restart/flush, replayed callback (state already consumed by a prior Take), or state never issued by this deployment.","commonSituations":"Double callback delivery (browser retry, webhook replay); user clicked the authorization link twice and both callbacks fired; Redis persistence disabled and the instance restarted mid-flow; stale bookmarked callback URL reused later.","solutions":["Since Take is single-use, ensure the callback handler runs only once and handles replayed callbacks gracefully (check whether the token was already stored).","Restart the OAuth flow with a fresh state if the first attempt genuinely expired.","Enable Redis persistence / verify the same Redis is used by the authorize-start and callback endpoints.","Reject duplicate callbacks with a friendly 'authorization already completed' response."],"exampleFix":"// before\nstate, err := store.Take(ctx, r.URL.Query().Get(\"state\"))\nif err != nil { return err }\n// after\nst, err := store.Take(ctx, stateParam)\nif err != nil {\n    if tokenStored(ctx, session) { return redirectDone() } // replay after success\n    return restartOAuthFlow()\n}","handlingStrategy":"try-catch","validationCode":"// check for prior completion before Take:\nif _, err := tokenStore.GetToken(ctx, principal); err == nil { // already completed; ignore duplicate callback }","typeGuard":null,"tryCatchPattern":"st, err := store.Take(ctx, stateParam)\nif err != nil {\n    if strings.Contains(err.Error(), \"not found or expired\") {\n        // single-use replay or expiry: check token, else restart flow\n        if done := maybeAlreadyCompleted(ctx, session); done { return redirectDone() }\n        return restartAuthorization()\n    }\n    return err\n}","preventionTips":["Never call Take more than once per callback; guard the handler against browser retries.","Enable Redis persistence and share the instance across callback handlers.","Issue fresh state per attempt; never reuse or pre-generate states.","Treat unknown states as potential CSRF and log them with request metadata."],"tags":["oauth","csrf-state","single-use","redis"],"backgroundTag":"oauth-state-expired","analyzedSha":"988cbb03305e055d8ebb7d46d9ac6cc0803cd074","analyzedAt":"2026-09-02T14:41:08.344Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}