diff options
Diffstat (limited to 'modules/session')
-rw-r--r-- | modules/session/db.go | 171 | ||||
-rw-r--r-- | modules/session/redis.go | 227 | ||||
-rw-r--r-- | modules/session/store.go | 29 | ||||
-rw-r--r-- | modules/session/virtual.go | 197 |
4 files changed, 624 insertions, 0 deletions
diff --git a/modules/session/db.go b/modules/session/db.go new file mode 100644 index 00000000..9909f2dc --- /dev/null +++ b/modules/session/db.go @@ -0,0 +1,171 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package session + +import ( + "log" + "sync" + + "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/timeutil" + + "gitea.com/go-chi/session" +) + +// DBStore represents a session store implementation based on the DB. +type DBStore struct { + sid string + lock sync.RWMutex + data map[any]any +} + +// NewDBStore creates and returns a DB session store. +func NewDBStore(sid string, kv map[any]any) *DBStore { + return &DBStore{ + sid: sid, + data: kv, + } +} + +// Set sets value to given key in session. +func (s *DBStore) Set(key, val any) error { + s.lock.Lock() + defer s.lock.Unlock() + + s.data[key] = val + return nil +} + +// Get gets value by given key in session. +func (s *DBStore) Get(key any) any { + s.lock.RLock() + defer s.lock.RUnlock() + + return s.data[key] +} + +// Delete delete a key from session. +func (s *DBStore) Delete(key any) error { + s.lock.Lock() + defer s.lock.Unlock() + + delete(s.data, key) + return nil +} + +// ID returns current session ID. +func (s *DBStore) ID() string { + return s.sid +} + +// Release releases resource and save data to provider. +func (s *DBStore) Release() error { + // Skip encoding if the data is empty + if len(s.data) == 0 { + return nil + } + + data, err := session.EncodeGob(s.data) + if err != nil { + return err + } + + return auth.UpdateSession(db.DefaultContext, s.sid, data) +} + +// Flush deletes all session data. +func (s *DBStore) Flush() error { + s.lock.Lock() + defer s.lock.Unlock() + + s.data = make(map[any]any) + return nil +} + +// DBProvider represents a DB session provider implementation. +type DBProvider struct { + maxLifetime int64 +} + +// Init initializes DB session provider. +// connStr: username:password@protocol(address)/dbname?param=value +func (p *DBProvider) Init(maxLifetime int64, connStr string) error { + p.maxLifetime = maxLifetime + return nil +} + +// Read returns raw session store by session ID. +func (p *DBProvider) Read(sid string) (session.RawStore, error) { + s, err := auth.ReadSession(db.DefaultContext, sid) + if err != nil { + return nil, err + } + + var kv map[any]any + if len(s.Data) == 0 || s.Expiry.Add(p.maxLifetime) <= timeutil.TimeStampNow() { + kv = make(map[any]any) + } else { + kv, err = session.DecodeGob(s.Data) + if err != nil { + return nil, err + } + } + + return NewDBStore(sid, kv), nil +} + +// Exist returns true if session with given ID exists. +func (p *DBProvider) Exist(sid string) bool { + has, err := auth.ExistSession(db.DefaultContext, sid) + if err != nil { + panic("session/DB: error checking existence: " + err.Error()) + } + return has +} + +// Destroy deletes a session by session ID. +func (p *DBProvider) Destroy(sid string) error { + return auth.DestroySession(db.DefaultContext, sid) +} + +// Regenerate regenerates a session store from old session ID to new one. +func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) { + s, err := auth.RegenerateSession(db.DefaultContext, oldsid, sid) + if err != nil { + return nil, err + } + + var kv map[any]any + if len(s.Data) == 0 || s.Expiry.Add(p.maxLifetime) <= timeutil.TimeStampNow() { + kv = make(map[any]any) + } else { + kv, err = session.DecodeGob(s.Data) + if err != nil { + return nil, err + } + } + + return NewDBStore(sid, kv), nil +} + +// Count counts and returns number of sessions. +func (p *DBProvider) Count() int { + total, err := auth.CountSessions(db.DefaultContext) + if err != nil { + panic("session/DB: error counting records: " + err.Error()) + } + return int(total) +} + +// GC calls GC to clean expired sessions. +func (p *DBProvider) GC() { + if err := auth.CleanupSessions(db.DefaultContext, p.maxLifetime); err != nil { + log.Printf("session/DB: error garbage collecting: %v", err) + } +} + +func init() { + session.Register("db", &DBProvider{}) +} diff --git a/modules/session/redis.go b/modules/session/redis.go new file mode 100644 index 00000000..d89d8bc6 --- /dev/null +++ b/modules/session/redis.go @@ -0,0 +1,227 @@ +// Copyright 2013 Beego Authors +// Copyright 2014 The Macaron Authors +// Copyright 2020 The Gitea Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// SPDX-License-Identifier: Apache-2.0 + +package session + +import ( + "fmt" + "sync" + "time" + + "code.gitea.io/gitea/modules/graceful" + "code.gitea.io/gitea/modules/nosql" + + "gitea.com/go-chi/session" + "github.com/redis/go-redis/v9" +) + +// RedisStore represents a redis session store implementation. +type RedisStore struct { + c redis.UniversalClient + prefix, sid string + duration time.Duration + lock sync.RWMutex + data map[any]any +} + +// NewRedisStore creates and returns a redis session store. +func NewRedisStore(c redis.UniversalClient, prefix, sid string, dur time.Duration, kv map[any]any) *RedisStore { + return &RedisStore{ + c: c, + prefix: prefix, + sid: sid, + duration: dur, + data: kv, + } +} + +// Set sets value to given key in session. +func (s *RedisStore) Set(key, val any) error { + s.lock.Lock() + defer s.lock.Unlock() + + s.data[key] = val + return nil +} + +// Get gets value by given key in session. +func (s *RedisStore) Get(key any) any { + s.lock.RLock() + defer s.lock.RUnlock() + + return s.data[key] +} + +// Delete delete a key from session. +func (s *RedisStore) Delete(key any) error { + s.lock.Lock() + defer s.lock.Unlock() + + delete(s.data, key) + return nil +} + +// ID returns current session ID. +func (s *RedisStore) ID() string { + return s.sid +} + +// Release releases resource and save data to provider. +func (s *RedisStore) Release() error { + // Skip encoding if the data is empty + if len(s.data) == 0 { + return nil + } + + data, err := session.EncodeGob(s.data) + if err != nil { + return err + } + + return s.c.Set(graceful.GetManager().HammerContext(), s.prefix+s.sid, string(data), s.duration).Err() +} + +// Flush deletes all session data. +func (s *RedisStore) Flush() error { + s.lock.Lock() + defer s.lock.Unlock() + + s.data = make(map[any]any) + return nil +} + +// RedisProvider represents a redis session provider implementation. +type RedisProvider struct { + c redis.UniversalClient + duration time.Duration + prefix string +} + +// Init initializes redis session provider. +// configs: network=tcp,addr=:6379,password=macaron,db=0,pool_size=100,idle_timeout=180,prefix=session; +func (p *RedisProvider) Init(maxlifetime int64, configs string) (err error) { + p.duration, err = time.ParseDuration(fmt.Sprintf("%ds", maxlifetime)) + if err != nil { + return err + } + + uri := nosql.ToRedisURI(configs) + + for k, v := range uri.Query() { + switch k { + case "prefix": + p.prefix = v[0] + } + } + + p.c = nosql.GetManager().GetRedisClient(uri.String()) + return p.c.Ping(graceful.GetManager().ShutdownContext()).Err() +} + +// Read returns raw session store by session ID. +func (p *RedisProvider) Read(sid string) (session.RawStore, error) { + psid := p.prefix + sid + if !p.Exist(sid) { + if err := p.c.Set(graceful.GetManager().HammerContext(), psid, "", p.duration).Err(); err != nil { + return nil, err + } + } + + var kv map[any]any + kvs, err := p.c.Get(graceful.GetManager().HammerContext(), psid).Result() + if err != nil { + return nil, err + } + if len(kvs) == 0 { + kv = make(map[any]any) + } else { + kv, err = session.DecodeGob([]byte(kvs)) + if err != nil { + return nil, err + } + } + + return NewRedisStore(p.c, p.prefix, sid, p.duration, kv), nil +} + +// Exist returns true if session with given ID exists. +func (p *RedisProvider) Exist(sid string) bool { + v, err := p.c.Exists(graceful.GetManager().HammerContext(), p.prefix+sid).Result() + return err == nil && v == 1 +} + +// Destroy deletes a session by session ID. +func (p *RedisProvider) Destroy(sid string) error { + return p.c.Del(graceful.GetManager().HammerContext(), p.prefix+sid).Err() +} + +// Regenerate regenerates a session store from old session ID to new one. +func (p *RedisProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) { + poldsid := p.prefix + oldsid + psid := p.prefix + sid + + if p.Exist(sid) { + return nil, fmt.Errorf("new sid '%s' already exists", sid) + } else if !p.Exist(oldsid) { + // Make a fake old session. + if err = p.c.Set(graceful.GetManager().HammerContext(), poldsid, "", p.duration).Err(); err != nil { + return nil, err + } + } + + // do not use Rename here, because the old sid and new sid may be in different redis cluster slot. + kvs, err := p.c.Get(graceful.GetManager().HammerContext(), poldsid).Result() + if err != nil { + return nil, err + } + + if err = p.c.Del(graceful.GetManager().HammerContext(), poldsid).Err(); err != nil { + return nil, err + } + + if err = p.c.Set(graceful.GetManager().HammerContext(), psid, kvs, p.duration).Err(); err != nil { + return nil, err + } + + var kv map[any]any + if len(kvs) == 0 { + kv = make(map[any]any) + } else { + kv, err = session.DecodeGob([]byte(kvs)) + if err != nil { + return nil, err + } + } + + return NewRedisStore(p.c, p.prefix, sid, p.duration, kv), nil +} + +// Count counts and returns number of sessions. +func (p *RedisProvider) Count() int { + size, err := p.c.DBSize(graceful.GetManager().HammerContext()).Result() + if err != nil { + return 0 + } + return int(size) +} + +// GC calls GC to clean expired sessions. +func (*RedisProvider) GC() {} + +func init() { + session.Register("redis", &RedisProvider{}) +} diff --git a/modules/session/store.go b/modules/session/store.go new file mode 100644 index 00000000..70988fcd --- /dev/null +++ b/modules/session/store.go @@ -0,0 +1,29 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package session + +import ( + "net/http" + + "gitea.com/go-chi/session" +) + +// Store represents a session store +type Store interface { + Get(any) any + Set(any, any) error + Delete(any) error +} + +// RegenerateSession regenerates the underlying session and returns the new store +func RegenerateSession(resp http.ResponseWriter, req *http.Request) (Store, error) { + for _, f := range BeforeRegenerateSession { + f(resp, req) + } + s, err := session.RegenerateSession(resp, req) + return s, err +} + +// BeforeRegenerateSession is a list of functions that are called before a session is regenerated. +var BeforeRegenerateSession []func(http.ResponseWriter, *http.Request) diff --git a/modules/session/virtual.go b/modules/session/virtual.go new file mode 100644 index 00000000..80352b6e --- /dev/null +++ b/modules/session/virtual.go @@ -0,0 +1,197 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package session + +import ( + "fmt" + "sync" + + "code.gitea.io/gitea/modules/json" + + "gitea.com/go-chi/session" + couchbase "gitea.com/go-chi/session/couchbase" + memcache "gitea.com/go-chi/session/memcache" + mysql "gitea.com/go-chi/session/mysql" + postgres "gitea.com/go-chi/session/postgres" +) + +// VirtualSessionProvider represents a shadowed session provider implementation. +type VirtualSessionProvider struct { + lock sync.RWMutex + provider session.Provider +} + +// Init initializes the cookie session provider with given root path. +func (o *VirtualSessionProvider) Init(gclifetime int64, config string) error { + var opts session.Options + if err := json.Unmarshal([]byte(config), &opts); err != nil { + return err + } + // Note that these options are unprepared so we can't just use NewManager here. + // Nor can we access the provider map in session. + // So we will just have to do this by hand. + // This is only slightly more wrong than modules/setting/session.go:23 + switch opts.Provider { + case "memory": + o.provider = &session.MemProvider{} + case "file": + o.provider = &session.FileProvider{} + case "redis": + o.provider = &RedisProvider{} + case "db": + o.provider = &DBProvider{} + case "mysql": + o.provider = &mysql.MysqlProvider{} + case "postgres": + o.provider = &postgres.PostgresProvider{} + case "couchbase": + o.provider = &couchbase.CouchbaseProvider{} + case "memcache": + o.provider = &memcache.MemcacheProvider{} + default: + return fmt.Errorf("VirtualSessionProvider: Unknown Provider: %s", opts.Provider) + } + return o.provider.Init(gclifetime, opts.ProviderConfig) +} + +// Read returns raw session store by session ID. +func (o *VirtualSessionProvider) Read(sid string) (session.RawStore, error) { + o.lock.RLock() + defer o.lock.RUnlock() + if o.provider.Exist(sid) { + return o.provider.Read(sid) + } + kv := make(map[any]any) + kv["_old_uid"] = "0" + return NewVirtualStore(o, sid, kv), nil +} + +// Exist returns true if session with given ID exists. +func (o *VirtualSessionProvider) Exist(sid string) bool { + return true +} + +// Destroy deletes a session by session ID. +func (o *VirtualSessionProvider) Destroy(sid string) error { + o.lock.Lock() + defer o.lock.Unlock() + return o.provider.Destroy(sid) +} + +// Regenerate regenerates a session store from old session ID to new one. +func (o *VirtualSessionProvider) Regenerate(oldsid, sid string) (session.RawStore, error) { + o.lock.Lock() + defer o.lock.Unlock() + return o.provider.Regenerate(oldsid, sid) +} + +// Count counts and returns number of sessions. +func (o *VirtualSessionProvider) Count() int { + o.lock.RLock() + defer o.lock.RUnlock() + return o.provider.Count() +} + +// GC calls GC to clean expired sessions. +func (o *VirtualSessionProvider) GC() { + o.provider.GC() +} + +func init() { + session.Register("VirtualSession", &VirtualSessionProvider{}) +} + +// VirtualStore represents a virtual session store implementation. +type VirtualStore struct { + p *VirtualSessionProvider + sid string + lock sync.RWMutex + data map[any]any + released bool +} + +// NewVirtualStore creates and returns a virtual session store. +func NewVirtualStore(p *VirtualSessionProvider, sid string, kv map[any]any) *VirtualStore { + return &VirtualStore{ + p: p, + sid: sid, + data: kv, + } +} + +// Set sets value to given key in session. +func (s *VirtualStore) Set(key, val any) error { + s.lock.Lock() + defer s.lock.Unlock() + + s.data[key] = val + return nil +} + +// Get gets value by given key in session. +func (s *VirtualStore) Get(key any) any { + s.lock.RLock() + defer s.lock.RUnlock() + + return s.data[key] +} + +// Delete delete a key from session. +func (s *VirtualStore) Delete(key any) error { + s.lock.Lock() + defer s.lock.Unlock() + + delete(s.data, key) + return nil +} + +// ID returns current session ID. +func (s *VirtualStore) ID() string { + return s.sid +} + +// Release releases resource and save data to provider. +func (s *VirtualStore) Release() error { + s.lock.Lock() + defer s.lock.Unlock() + // Now need to lock the provider + s.p.lock.Lock() + defer s.p.lock.Unlock() + if oldUID, ok := s.data["_old_uid"]; (ok && (oldUID != "0" || len(s.data) > 1)) || (!ok && len(s.data) > 0) { + // Now ensure that we don't exist! + realProvider := s.p.provider + + if !s.released && realProvider.Exist(s.sid) { + // This is an error! + return fmt.Errorf("new sid '%s' already exists", s.sid) + } + realStore, err := realProvider.Read(s.sid) + if err != nil { + return err + } + if err := realStore.Flush(); err != nil { + return err + } + for key, value := range s.data { + if err := realStore.Set(key, value); err != nil { + return err + } + } + err = realStore.Release() + if err == nil { + s.released = true + } + return err + } + return nil +} + +// Flush deletes all session data. +func (s *VirtualStore) Flush() error { + s.lock.Lock() + defer s.lock.Unlock() + + s.data = make(map[any]any) + return nil +} |