GoToSocial/internal/oauth/tokenstore.go

256 lines
8.4 KiB
Go
Raw Normal View History

// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2021-03-14 17:56:16 +01:00
package oauth
import (
"context"
"errors"
2021-03-17 16:01:31 +01:00
"fmt"
2021-03-14 17:56:16 +01:00
"time"
Api/v1/accounts (#8) * start work on accounts module * plodding away on the accounts endpoint * groundwork for other account routes * add password validator * validation utils * require account approval flags * comments * comments * go fmt * comments * add distributor stub * rename api to federator * tidy a bit * validate new account requests * rename r router * comments * add domain blocks * add some more shortcuts * add some more shortcuts * check email + username availability * email block checking for signups * chunking away at it * tick off a few more things * some fiddling with tests * add mock package * relocate repo * move mocks around * set app id on new signups * initialize oauth server properly * rename oauth server * proper mocking tests * go fmt ./... * add required fields * change name of func * move validation to account.go * more tests! * add some file utility tools * add mediaconfig * new shortcut * add some more fields * add followrequest model * add notify * update mastotypes * mock out storage interface * start building media interface * start on update credentials * mess about with media a bit more * test image manipulation * media more or less working * account update nearly working * rearranging my package ;) ;) ;) * phew big stuff!!!! * fix type checking * *fiddles* * Add CreateTables func * account registration flow working * tidy * script to step through auth flow * add a lil helper for generating user uris * fiddling with federation a bit * update progress * Tidying and linting
2021-04-01 20:46:45 +02:00
"github.com/superseriousbusiness/gotosocial/internal/db"
2021-09-01 11:45:01 +02:00
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/id"
[chore] use our own logging implementation (#716) * first commit Signed-off-by: kim <grufwub@gmail.com> * replace logging with our own log library Signed-off-by: kim <grufwub@gmail.com> * fix imports Signed-off-by: kim <grufwub@gmail.com> * fix log imports Signed-off-by: kim <grufwub@gmail.com> * add license text Signed-off-by: kim <grufwub@gmail.com> * fix package import cycle between config and log package Signed-off-by: kim <grufwub@gmail.com> * fix empty kv.Fields{} being passed to WithFields() Signed-off-by: kim <grufwub@gmail.com> * fix uses of log.WithFields() with whitespace issues and empty slices Signed-off-by: kim <grufwub@gmail.com> * *linter related grumbling* Signed-off-by: kim <grufwub@gmail.com> * gofmt the codebase! also fix more log.WithFields() formatting issues Signed-off-by: kim <grufwub@gmail.com> * update testrig code to match new changes Signed-off-by: kim <grufwub@gmail.com> * fix error wrapping in non fmt.Errorf function Signed-off-by: kim <grufwub@gmail.com> * add benchmarking of log.Caller() vs non-cached Signed-off-by: kim <grufwub@gmail.com> * fix syslog tests, add standard build tags to test runner to ensure consistency Signed-off-by: kim <grufwub@gmail.com> * make syslog tests more robust Signed-off-by: kim <grufwub@gmail.com> * fix caller depth arithmatic (is that how you spell it?) Signed-off-by: kim <grufwub@gmail.com> * update to use unkeyed fields in kv.Field{} instances Signed-off-by: kim <grufwub@gmail.com> * update go-kv library Signed-off-by: kim <grufwub@gmail.com> * update libraries list Signed-off-by: kim <grufwub@gmail.com> * fuck you linter get nerfed Signed-off-by: kim <grufwub@gmail.com> Co-authored-by: tobi <31960611+tsmethurst@users.noreply.github.com>
2022-07-19 10:47:55 +02:00
"github.com/superseriousbusiness/gotosocial/internal/log"
Api/v1/accounts (#8) * start work on accounts module * plodding away on the accounts endpoint * groundwork for other account routes * add password validator * validation utils * require account approval flags * comments * comments * go fmt * comments * add distributor stub * rename api to federator * tidy a bit * validate new account requests * rename r router * comments * add domain blocks * add some more shortcuts * add some more shortcuts * check email + username availability * email block checking for signups * chunking away at it * tick off a few more things * some fiddling with tests * add mock package * relocate repo * move mocks around * set app id on new signups * initialize oauth server properly * rename oauth server * proper mocking tests * go fmt ./... * add required fields * change name of func * move validation to account.go * more tests! * add some file utility tools * add mediaconfig * new shortcut * add some more fields * add followrequest model * add notify * update mastotypes * mock out storage interface * start building media interface * start on update credentials * mess about with media a bit more * test image manipulation * media more or less working * account update nearly working * rearranging my package ;) ;) ;) * phew big stuff!!!! * fix type checking * *fiddles* * Add CreateTables func * account registration flow working * tidy * script to step through auth flow * add a lil helper for generating user uris * fiddling with federation a bit * update progress * Tidying and linting
2021-04-01 20:46:45 +02:00
"github.com/superseriousbusiness/oauth2/v4"
"github.com/superseriousbusiness/oauth2/v4/models"
2021-03-14 17:56:16 +01:00
)
// tokenStore is an implementation of oauth2.TokenStore, which uses our db interface as a storage backend.
type tokenStore struct {
2021-03-14 17:56:16 +01:00
oauth2.TokenStore
2021-10-13 13:50:24 +02:00
db db.Basic
2021-03-14 17:56:16 +01:00
}
// newTokenStore returns a token store that satisfies the oauth2.TokenStore interface.
2021-03-14 17:56:16 +01:00
//
// In order to allow tokens to 'expire', it will also set off a goroutine that iterates through
// the tokens in the DB once per minute and deletes any that have expired.
func newTokenStore(ctx context.Context, db db.Basic) oauth2.TokenStore {
ts := &tokenStore{
2021-10-13 13:50:24 +02:00
db: db,
2021-03-14 17:56:16 +01:00
}
// set the token store to clean out expired tokens once per minute, or return if we're done
go func(ctx context.Context, ts *tokenStore) {
2021-03-14 17:56:16 +01:00
cleanloop:
for {
select {
case <-ctx.Done():
log.Info(ctx, "breaking cleanloop")
2021-03-14 17:56:16 +01:00
break cleanloop
case <-time.After(1 * time.Minute):
log.Trace(ctx, "sweeping out old oauth entries broom broom")
if err := ts.sweep(ctx); err != nil {
log.Errorf(ctx, "error while sweeping oauth entries: %s", err)
2021-03-14 17:56:16 +01:00
}
}
}
}(ctx, ts)
return ts
2021-03-14 17:56:16 +01:00
}
// sweep clears out old tokens that have expired; it should be run on a loop about once per minute or so.
func (ts *tokenStore) sweep(ctx context.Context) error {
2021-03-14 17:56:16 +01:00
// select *all* tokens from the db
// todo: if this becomes expensive (ie., there are fucking LOADS of tokens) then figure out a better way.
2021-09-01 11:45:01 +02:00
tokens := new([]*gtsmodel.Token)
if err := ts.db.GetAll(ctx, tokens); err != nil {
2021-03-14 17:56:16 +01:00
return err
}
// iterate through and remove expired tokens
now := time.Now()
for _, dbt := range *tokens {
2021-03-14 17:56:16 +01:00
// The zero value of a time.Time is 00:00 january 1 1970, which will always be before now. So:
// we only want to check if a token expired before now if the expiry time is *not zero*;
// ie., if it's been explicity set.
if !dbt.CodeExpiresAt.IsZero() && dbt.CodeExpiresAt.Before(now) || !dbt.RefreshExpiresAt.IsZero() && dbt.RefreshExpiresAt.Before(now) || !dbt.AccessExpiresAt.IsZero() && dbt.AccessExpiresAt.Before(now) {
if err := ts.db.DeleteByID(ctx, dbt.ID, dbt); err != nil {
2021-03-14 17:56:16 +01:00
return err
}
}
}
return nil
}
// Create creates and store the new token information.
Api/v1/accounts (#8) * start work on accounts module * plodding away on the accounts endpoint * groundwork for other account routes * add password validator * validation utils * require account approval flags * comments * comments * go fmt * comments * add distributor stub * rename api to federator * tidy a bit * validate new account requests * rename r router * comments * add domain blocks * add some more shortcuts * add some more shortcuts * check email + username availability * email block checking for signups * chunking away at it * tick off a few more things * some fiddling with tests * add mock package * relocate repo * move mocks around * set app id on new signups * initialize oauth server properly * rename oauth server * proper mocking tests * go fmt ./... * add required fields * change name of func * move validation to account.go * more tests! * add some file utility tools * add mediaconfig * new shortcut * add some more fields * add followrequest model * add notify * update mastotypes * mock out storage interface * start building media interface * start on update credentials * mess about with media a bit more * test image manipulation * media more or less working * account update nearly working * rearranging my package ;) ;) ;) * phew big stuff!!!! * fix type checking * *fiddles* * Add CreateTables func * account registration flow working * tidy * script to step through auth flow * add a lil helper for generating user uris * fiddling with federation a bit * update progress * Tidying and linting
2021-04-01 20:46:45 +02:00
// For the original implementation, see https://github.com/superseriousbusiness/oauth2/blob/master/store/token.go#L34
func (ts *tokenStore) Create(ctx context.Context, info oauth2.TokenInfo) error {
2021-03-14 17:56:16 +01:00
t, ok := info.(*models.Token)
if !ok {
return errors.New("info param was not a models.Token")
}
dbt := TokenToDBToken(t)
if dbt.ID == "" {
dbtID, err := id.NewRandomULID()
if err != nil {
return err
}
dbt.ID = dbtID
}
if err := ts.db.Put(ctx, dbt); err != nil {
2021-03-17 16:01:31 +01:00
return fmt.Errorf("error in tokenstore create: %s", err)
}
return nil
2021-03-14 17:56:16 +01:00
}
// RemoveByCode deletes a token from the DB based on the Code field
func (ts *tokenStore) RemoveByCode(ctx context.Context, code string) error {
2021-09-01 11:45:01 +02:00
return ts.db.DeleteWhere(ctx, []db.Where{{Key: "code", Value: code}}, &gtsmodel.Token{})
2021-03-14 17:56:16 +01:00
}
// RemoveByAccess deletes a token from the DB based on the Access field
func (ts *tokenStore) RemoveByAccess(ctx context.Context, access string) error {
2021-09-01 11:45:01 +02:00
return ts.db.DeleteWhere(ctx, []db.Where{{Key: "access", Value: access}}, &gtsmodel.Token{})
2021-03-14 17:56:16 +01:00
}
// RemoveByRefresh deletes a token from the DB based on the Refresh field
func (ts *tokenStore) RemoveByRefresh(ctx context.Context, refresh string) error {
2021-09-01 11:45:01 +02:00
return ts.db.DeleteWhere(ctx, []db.Where{{Key: "refresh", Value: refresh}}, &gtsmodel.Token{})
2021-03-14 17:56:16 +01:00
}
// GetByCode selects a token from the DB based on the Code field
func (ts *tokenStore) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error) {
Api/v1/accounts (#8) * start work on accounts module * plodding away on the accounts endpoint * groundwork for other account routes * add password validator * validation utils * require account approval flags * comments * comments * go fmt * comments * add distributor stub * rename api to federator * tidy a bit * validate new account requests * rename r router * comments * add domain blocks * add some more shortcuts * add some more shortcuts * check email + username availability * email block checking for signups * chunking away at it * tick off a few more things * some fiddling with tests * add mock package * relocate repo * move mocks around * set app id on new signups * initialize oauth server properly * rename oauth server * proper mocking tests * go fmt ./... * add required fields * change name of func * move validation to account.go * more tests! * add some file utility tools * add mediaconfig * new shortcut * add some more fields * add followrequest model * add notify * update mastotypes * mock out storage interface * start building media interface * start on update credentials * mess about with media a bit more * test image manipulation * media more or less working * account update nearly working * rearranging my package ;) ;) ;) * phew big stuff!!!! * fix type checking * *fiddles* * Add CreateTables func * account registration flow working * tidy * script to step through auth flow * add a lil helper for generating user uris * fiddling with federation a bit * update progress * Tidying and linting
2021-04-01 20:46:45 +02:00
if code == "" {
return nil, nil
}
2021-09-01 11:45:01 +02:00
dbt := &gtsmodel.Token{
Code: code,
}
if err := ts.db.GetWhere(ctx, []db.Where{{Key: "code", Value: code}}, dbt); err != nil {
return nil, err
2021-03-14 17:56:16 +01:00
}
return DBTokenToToken(dbt), nil
2021-03-14 17:56:16 +01:00
}
// GetByAccess selects a token from the DB based on the Access field
func (ts *tokenStore) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error) {
Api/v1/accounts (#8) * start work on accounts module * plodding away on the accounts endpoint * groundwork for other account routes * add password validator * validation utils * require account approval flags * comments * comments * go fmt * comments * add distributor stub * rename api to federator * tidy a bit * validate new account requests * rename r router * comments * add domain blocks * add some more shortcuts * add some more shortcuts * check email + username availability * email block checking for signups * chunking away at it * tick off a few more things * some fiddling with tests * add mock package * relocate repo * move mocks around * set app id on new signups * initialize oauth server properly * rename oauth server * proper mocking tests * go fmt ./... * add required fields * change name of func * move validation to account.go * more tests! * add some file utility tools * add mediaconfig * new shortcut * add some more fields * add followrequest model * add notify * update mastotypes * mock out storage interface * start building media interface * start on update credentials * mess about with media a bit more * test image manipulation * media more or less working * account update nearly working * rearranging my package ;) ;) ;) * phew big stuff!!!! * fix type checking * *fiddles* * Add CreateTables func * account registration flow working * tidy * script to step through auth flow * add a lil helper for generating user uris * fiddling with federation a bit * update progress * Tidying and linting
2021-04-01 20:46:45 +02:00
if access == "" {
return nil, nil
}
2021-09-01 11:45:01 +02:00
dbt := &gtsmodel.Token{
Access: access,
}
if err := ts.db.GetWhere(ctx, []db.Where{{Key: "access", Value: access}}, dbt); err != nil {
return nil, err
2021-03-14 17:56:16 +01:00
}
return DBTokenToToken(dbt), nil
2021-03-14 17:56:16 +01:00
}
// GetByRefresh selects a token from the DB based on the Refresh field
func (ts *tokenStore) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error) {
Api/v1/accounts (#8) * start work on accounts module * plodding away on the accounts endpoint * groundwork for other account routes * add password validator * validation utils * require account approval flags * comments * comments * go fmt * comments * add distributor stub * rename api to federator * tidy a bit * validate new account requests * rename r router * comments * add domain blocks * add some more shortcuts * add some more shortcuts * check email + username availability * email block checking for signups * chunking away at it * tick off a few more things * some fiddling with tests * add mock package * relocate repo * move mocks around * set app id on new signups * initialize oauth server properly * rename oauth server * proper mocking tests * go fmt ./... * add required fields * change name of func * move validation to account.go * more tests! * add some file utility tools * add mediaconfig * new shortcut * add some more fields * add followrequest model * add notify * update mastotypes * mock out storage interface * start building media interface * start on update credentials * mess about with media a bit more * test image manipulation * media more or less working * account update nearly working * rearranging my package ;) ;) ;) * phew big stuff!!!! * fix type checking * *fiddles* * Add CreateTables func * account registration flow working * tidy * script to step through auth flow * add a lil helper for generating user uris * fiddling with federation a bit * update progress * Tidying and linting
2021-04-01 20:46:45 +02:00
if refresh == "" {
return nil, nil
}
2021-09-01 11:45:01 +02:00
dbt := &gtsmodel.Token{
Refresh: refresh,
}
if err := ts.db.GetWhere(ctx, []db.Where{{Key: "refresh", Value: refresh}}, dbt); err != nil {
return nil, err
2021-03-14 17:56:16 +01:00
}
return DBTokenToToken(dbt), nil
2021-03-14 17:56:16 +01:00
}
/*
The following models are basically helpers for the token store implementation, they should only be used internally.
2021-03-14 17:56:16 +01:00
*/
// TokenToDBToken is a lil util function that takes a gotosocial token and gives back a token for inserting into a database.
2021-09-01 11:45:01 +02:00
func TokenToDBToken(tkn *models.Token) *gtsmodel.Token {
2021-03-14 17:56:16 +01:00
now := time.Now()
// For the following, we want to make sure we're not adding a time.Now() to an *empty* ExpiresIn, otherwise that's
// going to cause all sorts of interesting problems. So check first to make sure that the ExpiresIn is not equal
// to the zero value of a time.Duration, which is 0s. If it *is* empty/nil, just leave the ExpiresAt at nil as well.
cea := time.Time{}
2021-03-14 17:56:16 +01:00
if tkn.CodeExpiresIn != 0*time.Second {
cea = now.Add(tkn.CodeExpiresIn)
}
aea := time.Time{}
2021-03-14 17:56:16 +01:00
if tkn.AccessExpiresIn != 0*time.Second {
aea = now.Add(tkn.AccessExpiresIn)
}
rea := time.Time{}
2021-03-14 17:56:16 +01:00
if tkn.RefreshExpiresIn != 0*time.Second {
rea = now.Add(tkn.RefreshExpiresIn)
}
2021-09-01 11:45:01 +02:00
return &gtsmodel.Token{
2021-03-14 17:56:16 +01:00
ClientID: tkn.ClientID,
UserID: tkn.UserID,
RedirectURI: tkn.RedirectURI,
Scope: tkn.Scope,
Code: tkn.Code,
CodeChallenge: tkn.CodeChallenge,
CodeChallengeMethod: tkn.CodeChallengeMethod,
CodeCreateAt: tkn.CodeCreateAt,
CodeExpiresAt: cea,
Access: tkn.Access,
AccessCreateAt: tkn.AccessCreateAt,
AccessExpiresAt: aea,
Refresh: tkn.Refresh,
RefreshCreateAt: tkn.RefreshCreateAt,
RefreshExpiresAt: rea,
}
}
// DBTokenToToken is a lil util function that takes a database token and gives back a gotosocial token
2021-09-01 11:45:01 +02:00
func DBTokenToToken(dbt *gtsmodel.Token) *models.Token {
2021-03-14 17:56:16 +01:00
now := time.Now()
var codeExpiresIn time.Duration
if !dbt.CodeExpiresAt.IsZero() {
codeExpiresIn = dbt.CodeExpiresAt.Sub(now)
}
var accessExpiresIn time.Duration
if !dbt.AccessExpiresAt.IsZero() {
accessExpiresIn = dbt.AccessExpiresAt.Sub(now)
}
var refreshExpiresIn time.Duration
if !dbt.RefreshExpiresAt.IsZero() {
refreshExpiresIn = dbt.RefreshExpiresAt.Sub(now)
}
2021-03-14 17:56:16 +01:00
return &models.Token{
ClientID: dbt.ClientID,
UserID: dbt.UserID,
RedirectURI: dbt.RedirectURI,
Scope: dbt.Scope,
Code: dbt.Code,
CodeChallenge: dbt.CodeChallenge,
CodeChallengeMethod: dbt.CodeChallengeMethod,
CodeCreateAt: dbt.CodeCreateAt,
CodeExpiresIn: codeExpiresIn,
Access: dbt.Access,
AccessCreateAt: dbt.AccessCreateAt,
AccessExpiresIn: accessExpiresIn,
Refresh: dbt.Refresh,
RefreshCreateAt: dbt.RefreshCreateAt,
RefreshExpiresIn: refreshExpiresIn,
2021-03-14 17:56:16 +01:00
}
}