Files
Gitea/modules/session/file.go
T
silverwind cf89ecd887 refactor!: move go-chi/session into Gitea (#39504)
The `gitea.com/go-chi/session` package only exists for Gitea, so it
moves into `modules/session` to fix its bugs directly. Fixes the flake
in
https://github.com/go-gitea/gitea/actions/runs/36726154500/job/109923538400.

- Sessions are only written back when changed, so a read-only request
can't revert a concurrent change or restore a logged-out session, like
https://github.com/go-macaron/session/commit/ae808a4a4660c802965c834299ab08f167effd12
- The session cookie is only set once a session holds data
- Every backend refreshes the expiry on load and file sessions are
written atomically
- Also fix  https://github.com/go-gitea/gitea/issues/36176

## ⚠️ BREAKING ⚠️

* the `mysql`, `postgres`, `couchbase` and `memcache` session providers
are removed, use `file`, `db` or `redis` instead
* login-related cookies are renamed to `gitea_session` and
`gitea_remember`, if you'd like to use the old names, set `COOKIE_NAME`
and `COOKIE_REMEMBER_NAME` in app.ini

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-10-02 21:08:14 +02:00

116 lines
2.8 KiB
Go

// Copyright 2013 Beego Authors
// Copyright 2014 The Macaron Authors
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package session
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync"
"time"
"gitea.dev/modules/log"
"gitea.dev/modules/util"
)
type fileBackend struct {
lock sync.RWMutex // exclusive for removals, so they never interleave with a load or save
rootPath string
maxLifetime time.Duration
}
func newFileBackend(rootPath string, maxLifetime int64) *fileBackend {
return &fileBackend{rootPath: filepath.Clean(rootPath), maxLifetime: time.Duration(maxLifetime) * time.Second}
}
func (b *fileBackend) filepath(sid string) string {
return filepath.Join(b.rootPath, sid[0:1], sid[1:2], sid)
}
func ignoreNotExist(err error) error {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
func (b *fileBackend) load(sid string) ([]byte, error) {
b.lock.RLock()
defer b.lock.RUnlock()
filename := b.filepath(sid)
stat, err := os.Lstat(filename)
if err != nil {
return nil, ignoreNotExist(err)
}
if !stat.Mode().IsRegular() {
return nil, fmt.Errorf("session file %s is not a regular file", filename)
}
if time.Since(stat.ModTime()) > b.maxLifetime {
return nil, nil
}
data, err := os.ReadFile(filename)
if err == nil {
now := time.Now()
err = os.Chtimes(filename, now, now)
}
return data, ignoreNotExist(err)
}
func (b *fileBackend) save(sid string, data []byte, create bool) error {
b.lock.RLock()
defer b.lock.RUnlock()
filename := b.filepath(sid)
if create {
if err := os.MkdirAll(filepath.Dir(filename), 0o700); err != nil {
return err
}
} else if _, err := os.Lstat(filename); err != nil {
return ignoreNotExist(err)
}
tmpFile, err := os.CreateTemp(filepath.Dir(filename), sid+".*.tmp")
if err != nil {
return err
}
_, err = tmpFile.Write(data)
if err = errors.Join(err, tmpFile.Close()); err == nil {
err = util.RenameWithRetry(tmpFile.Name(), filename)
}
if err != nil {
_ = os.Remove(tmpFile.Name())
}
return err
}
func (b *fileBackend) destroy(sid string) error {
b.lock.Lock()
defer b.lock.Unlock()
return ignoreNotExist(os.Remove(b.filepath(sid)))
}
func (b *fileBackend) expired(path string) bool {
info, err := os.Lstat(path)
return err == nil && time.Since(info.ModTime()) > b.maxLifetime
}
func (b *fileBackend) gc() {
err := filepath.WalkDir(b.rootPath, func(path string, entry fs.DirEntry, err error) error {
if err != nil || entry.IsDir() || !b.expired(path) {
return ignoreNotExist(err)
}
b.lock.Lock()
defer b.lock.Unlock()
if b.expired(path) { // a concurrent load may have refreshed it
err = os.Remove(path)
}
return ignoreNotExist(err)
})
if err != nil {
log.Error("Unable to garbage collect session files: %v", err)
}
}