alexedwards / scs

HTTP Session Management for Go
MIT License
2.02k stars 165 forks source link

How to recover from corrupt session data? (or how to Destroy without loading the session) #167

Closed gabrielhora closed 1 year ago

gabrielhora commented 1 year ago

Suppose I'm storing session data in a database table, if, for whatever reason, a user session data gets corrupted (someone updated the table directly for example) there's currently no way that I could find to recover from that.

The LoadAndSave middleware will always try to load the corrupted session data and we have no way of deleting the session cookie. We can't Destroy the session in a custom ErrorFunc because the session is not in the context.

We could rely on a custom ErrorFunc and delete the data directly in the store manually. Something like (error handling removed for brevity):

var sessionManager *scs.SessionManager

func errorFunc(w http.ResponseWriter, req *http.Request, err error) {
    cookie, _ := req.Cookie("session")
    _ = sessionManager.Store.Delete(cookie.Value)
    http.SetCookie(w, &http.Cookie{Name: "session", Expires: time.Unix(0, 0)})
    http.Redirect(w, req, "/login", http.StatusFound)
}

This feels awkward in the sense that I have to rely on scs internals (the cookie name) and reach directly into the session store. And the above function is something I have to implement on all projects.

My question then is, should there be a way to destroy a session without trying to load it's data first (internally reaching to the Store and deleting the record and also deleting the cookie)? Or maybe even better a flag that tells scs to do that automatically when failing to decode the session data?

Thank you for you time.

alexedwards commented 1 year ago

Kudos for the thoughtful issue description :+1:

If this is a one-off issue, I would suggest writing a standalone script which connects to your DB, identifies the corrupted entries, and deletes them. This below is untested code, but I think it should work. Assuming you're using the postgres store and the standard GobCodec to encode the data:

store := postgresstore.New(db)

allSessions, err := store.All()
if err != nil {
    // Handle error
}

for token, b := range allSessions {
    _, _, err := scs.GobCodec.Decode(b)
    if err != nil {
        if err == "whatever error you are getting from decoding the corrupted data"
                err := store.Delete(token)
                if err != nil {
                    // Handle error
                }
        else {
            // Handle error
        }
    }
}

If it isn't a one-off, then I suggest fixing the actual issue and taking steps to prevent your production DB data from being corrupted.

If it's outside of your control to fix that, then the custom ErrorFunc seems like a reasonable approach. You can probably make it a bit more robust by changing "session" for sessionManager.SessionCookie.Name and by checking that the value of err passed to errorFunc is specifically the corruption error before you delete the session from the DB and redirect the user. I don't think that you need the http.SetCookie(...) line --- after the redirect the next HTTP request will send the cookie again but this time it won't be found in the DB by LoadAndSave and a new session will be created that will overwrite the old session cookie.

gabrielhora commented 1 year ago

Thank you @alexedwards for the valuable suggestions, I'll apply those in our custom ErrorFunc.

My concern was that in such cases, regardless of the origin, it would be hard to detect the problem, and for an end user the only solution would be to clear the cookie manually in the browser. So I believe the custom ErrorFunc that deals with this is a must, although this is indeed a rare condition.