2024-01-01 16:52:18 +00:00
|
|
|
// Package access contains a service to manage Twitch tokens and scopes
|
2022-09-10 11:39:07 +00:00
|
|
|
package access
|
|
|
|
|
|
|
|
import (
|
2024-01-01 16:52:18 +00:00
|
|
|
"context"
|
2022-09-10 11:39:07 +00:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2022-10-22 22:08:02 +00:00
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/clause"
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2023-11-27 23:09:27 +00:00
|
|
|
"github.com/Luzifer/go_helpers/v2/backoff"
|
2022-09-10 11:39:07 +00:00
|
|
|
"github.com/Luzifer/go_helpers/v2/str"
|
2023-11-27 23:09:27 +00:00
|
|
|
"github.com/Luzifer/twitch-bot/v3/internal/helpers"
|
2022-11-02 21:38:14 +00:00
|
|
|
"github.com/Luzifer/twitch-bot/v3/pkg/database"
|
|
|
|
"github.com/Luzifer/twitch-bot/v3/pkg/twitch"
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
coreMetaKeyBotToken = "bot_access_token"
|
2023-02-06 18:40:06 +00:00
|
|
|
coreMetaKeyBotUsername = "bot_username"
|
2022-09-10 11:39:07 +00:00
|
|
|
coreMetaKeyBotRefreshToken = "bot_refresh_token" //#nosec:G101 // That's a key, not a credential
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2024-01-01 16:52:18 +00:00
|
|
|
// ClientConfig contains a configuration to derive new Twitch clients
|
|
|
|
// from
|
2022-09-10 11:39:07 +00:00
|
|
|
ClientConfig struct {
|
|
|
|
TwitchClient string
|
|
|
|
TwitchClientSecret string
|
|
|
|
|
2023-09-09 09:46:02 +00:00
|
|
|
FallbackToken string // DEPRECATED
|
2022-09-10 11:39:07 +00:00
|
|
|
|
|
|
|
TokenUpdateHook func()
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
extendedPermission struct {
|
|
|
|
Channel string `gorm:"primaryKey"`
|
|
|
|
AccessToken string
|
|
|
|
RefreshToken string
|
|
|
|
Scopes string
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// Service manages the permission database
|
2022-09-10 11:39:07 +00:00
|
|
|
Service struct{ db database.Connector }
|
|
|
|
)
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// ErrChannelNotAuthorized denotes there is no valid authoriztion for
|
|
|
|
// the given channel
|
2023-03-24 19:53:02 +00:00
|
|
|
var ErrChannelNotAuthorized = errors.New("channel is not authorized")
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// New creates a new Service on the given database
|
2022-10-22 22:08:02 +00:00
|
|
|
func New(db database.Connector) (*Service, error) {
|
|
|
|
return &Service{db}, errors.Wrap(
|
|
|
|
db.DB().AutoMigrate(&extendedPermission{}),
|
|
|
|
"migrating database schema",
|
|
|
|
)
|
2022-09-10 11:39:07 +00:00
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// CopyDatabase enables the bot to migrate the access database
|
|
|
|
func (*Service) CopyDatabase(src, target *gorm.DB) error {
|
|
|
|
return database.CopyObjects(src, target, &extendedPermission{}) //nolint:wrapcheck // Internal helper
|
2023-11-25 19:23:34 +00:00
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// GetBotUsername gets the cached bot username
|
2023-11-27 23:09:27 +00:00
|
|
|
func (s Service) GetBotUsername() (botUsername string, err error) {
|
|
|
|
err = s.db.ReadCoreMeta(coreMetaKeyBotUsername, &botUsername)
|
2023-02-06 18:40:06 +00:00
|
|
|
return botUsername, errors.Wrap(err, "reading bot username")
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// GetChannelPermissions returns the scopes granted for the given channel
|
2022-12-04 16:14:15 +00:00
|
|
|
func (s Service) GetChannelPermissions(channel string) ([]string, error) {
|
|
|
|
var (
|
|
|
|
err error
|
|
|
|
perm extendedPermission
|
|
|
|
)
|
|
|
|
|
2023-11-27 23:09:27 +00:00
|
|
|
if err = helpers.Retry(func() error {
|
|
|
|
err = s.db.DB().First(&perm, "channel = ?", strings.TrimLeft(channel, "#")).Error
|
2022-12-04 16:14:15 +00:00
|
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
2023-11-27 23:09:27 +00:00
|
|
|
return nil
|
2022-12-04 16:14:15 +00:00
|
|
|
}
|
2023-11-27 23:09:27 +00:00
|
|
|
|
|
|
|
return errors.Wrap(err, "getting twitch credential from database")
|
|
|
|
}); err != nil {
|
|
|
|
return nil, err
|
2022-12-04 16:14:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return strings.Split(perm.Scopes, " "), nil
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// GetBotTwitchClient returns a twitch.Client configured to act as the
|
|
|
|
// bot user
|
2022-09-10 11:39:07 +00:00
|
|
|
func (s Service) GetBotTwitchClient(cfg ClientConfig) (*twitch.Client, error) {
|
2023-02-06 18:40:06 +00:00
|
|
|
botUsername, err := s.GetBotUsername()
|
|
|
|
switch {
|
|
|
|
case errors.Is(err, nil):
|
|
|
|
// This is fine, we have a username
|
|
|
|
return s.GetTwitchClientForChannel(botUsername, cfg)
|
|
|
|
|
|
|
|
case errors.Is(err, database.ErrCoreMetaNotFound):
|
|
|
|
// The bot has no username stored, we try to auto-migrate below
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2023-02-06 18:40:06 +00:00
|
|
|
default:
|
|
|
|
return nil, errors.Wrap(err, "getting bot username from database")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bot username is not set, either we're running from fallback token
|
|
|
|
// or did not yet execute the v3.5.0 migration
|
|
|
|
|
|
|
|
var botAccessToken, botRefreshToken string
|
|
|
|
err = s.db.ReadEncryptedCoreMeta(coreMetaKeyBotToken, &botAccessToken)
|
2022-09-10 11:39:07 +00:00
|
|
|
switch {
|
|
|
|
case errors.Is(err, nil):
|
2023-02-06 18:40:06 +00:00
|
|
|
// This is fine, we do have a pre-v3.5.0 config, lets do the migration
|
2022-09-10 11:39:07 +00:00
|
|
|
|
|
|
|
case errors.Is(err, database.ErrCoreMetaNotFound):
|
2023-02-06 18:40:06 +00:00
|
|
|
// We're don't have a stored pre-v3.5.0 token either, so we're
|
|
|
|
// running from the fallback token (which might be empty)
|
|
|
|
return twitch.New(cfg.TwitchClient, cfg.TwitchClientSecret, cfg.FallbackToken, ""), nil
|
2022-09-10 11:39:07 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
return nil, errors.Wrap(err, "getting bot access token from database")
|
|
|
|
}
|
|
|
|
|
2023-02-06 18:40:06 +00:00
|
|
|
if err = s.db.ReadEncryptedCoreMeta(coreMetaKeyBotRefreshToken, &botRefreshToken); err != nil {
|
2022-09-10 11:39:07 +00:00
|
|
|
return nil, errors.Wrap(err, "getting bot refresh token from database")
|
|
|
|
}
|
|
|
|
|
2023-02-06 18:40:06 +00:00
|
|
|
// Now we do have (hopefully valid) tokens for the bot and therefore
|
|
|
|
// can determine who the bot is. That means we can set the username
|
|
|
|
// for later reference and afterwards delete the duplicated tokens.
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
_, botUser, err := twitch.New(cfg.TwitchClient, cfg.TwitchClientSecret, botAccessToken, botRefreshToken).GetAuthorizedUser(context.Background())
|
2023-02-06 18:40:06 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "validating stored access token")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = s.db.StoreCoreMeta(coreMetaKeyBotUsername, botUser); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "setting bot username")
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err = s.GetTwitchClientForChannel(botUser, cfg); errors.Is(err, gorm.ErrRecordNotFound) {
|
|
|
|
// There is no extended permission for that channel, we probably
|
|
|
|
// are in a state created by the v2 migrator. Lets just store the
|
|
|
|
// token without any permissions as we cannot know the permissions
|
|
|
|
// assigned to that token
|
|
|
|
if err = s.SetExtendedTwitchCredentials(botUser, botAccessToken, botRefreshToken, nil); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "moving bot access token")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = s.db.DeleteCoreMeta(coreMetaKeyBotToken); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "deleting deprecated bot token")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = s.db.DeleteCoreMeta(coreMetaKeyBotRefreshToken); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "deleting deprecated bot refresh-token")
|
|
|
|
}
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2023-02-06 18:40:06 +00:00
|
|
|
return s.GetTwitchClientForChannel(botUser, cfg)
|
2022-09-10 11:39:07 +00:00
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// GetTwitchClientForChannel returns a twitch.Client configured to act
|
|
|
|
// as the owner of the given channel
|
2022-09-10 11:39:07 +00:00
|
|
|
func (s Service) GetTwitchClientForChannel(channel string, cfg ClientConfig) (*twitch.Client, error) {
|
2022-10-22 22:08:02 +00:00
|
|
|
var (
|
|
|
|
err error
|
|
|
|
perm extendedPermission
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
|
2023-11-27 23:09:27 +00:00
|
|
|
if err = helpers.Retry(func() error {
|
|
|
|
err = s.db.DB().First(&perm, "channel = ?", strings.TrimLeft(channel, "#")).Error
|
2023-03-24 19:53:02 +00:00
|
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
2024-03-27 23:15:14 +00:00
|
|
|
return backoff.NewErrCannotRetry(ErrChannelNotAuthorized)
|
2023-03-24 19:53:02 +00:00
|
|
|
}
|
2023-11-27 23:09:27 +00:00
|
|
|
return errors.Wrap(err, "getting twitch credential from database")
|
|
|
|
}); err != nil {
|
|
|
|
return nil, err
|
2022-09-10 11:39:07 +00:00
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
if perm.AccessToken, err = s.db.DecryptField(perm.AccessToken); err != nil {
|
2022-09-10 11:39:07 +00:00
|
|
|
return nil, errors.Wrap(err, "decrypting access token")
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
if perm.RefreshToken, err = s.db.DecryptField(perm.RefreshToken); err != nil {
|
2022-09-10 11:39:07 +00:00
|
|
|
return nil, errors.Wrap(err, "decrypting refresh token")
|
|
|
|
}
|
|
|
|
|
2023-12-14 15:49:33 +00:00
|
|
|
if perm.AccessToken == "" && perm.RefreshToken == "" {
|
|
|
|
// We have no tokens but an entry in the permission table: Means
|
|
|
|
// we still can't do stuff on behalf of that channel so we treat
|
|
|
|
// that as an unauthorized channel
|
|
|
|
return nil, ErrChannelNotAuthorized
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
scopes := strings.Split(perm.Scopes, " ")
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
tc := twitch.New(cfg.TwitchClient, cfg.TwitchClientSecret, perm.AccessToken, perm.RefreshToken)
|
2022-09-10 11:39:07 +00:00
|
|
|
tc.SetTokenUpdateHook(func(at, rt string) error {
|
|
|
|
return errors.Wrap(s.SetExtendedTwitchCredentials(channel, at, rt, scopes), "updating extended permissions token")
|
|
|
|
})
|
|
|
|
|
|
|
|
return tc, nil
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// HasAnyPermissionForChannel checks whether any of the given scopes
|
|
|
|
// are granted for the given channel
|
2022-09-10 11:39:07 +00:00
|
|
|
func (s Service) HasAnyPermissionForChannel(channel string, scopes ...string) (bool, error) {
|
2022-12-04 16:14:15 +00:00
|
|
|
storedScopes, err := s.GetChannelPermissions(channel)
|
|
|
|
if err != nil {
|
|
|
|
return false, errors.Wrap(err, "getting channel scopes")
|
2022-09-10 11:39:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, scope := range scopes {
|
|
|
|
if str.StringInSlice(scope, storedScopes) {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// HasPermissionsForChannel checks whether all of the given scopes
|
|
|
|
// are granted for the given channel
|
2022-09-10 11:39:07 +00:00
|
|
|
func (s Service) HasPermissionsForChannel(channel string, scopes ...string) (bool, error) {
|
2022-12-04 16:14:15 +00:00
|
|
|
storedScopes, err := s.GetChannelPermissions(channel)
|
|
|
|
if err != nil {
|
|
|
|
return false, errors.Wrap(err, "getting channel scopes")
|
2022-09-10 11:39:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, scope := range scopes {
|
|
|
|
if !str.StringInSlice(scope, storedScopes) {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
2023-12-13 23:02:14 +00:00
|
|
|
// HasTokensForChannel retrieves and decrypts stored access- and
|
|
|
|
// refresh-tokens to evaluate whether tokens are available. Those
|
|
|
|
// tokens are NOT validated in this request, it's just checked whether
|
|
|
|
// they are present
|
|
|
|
func (s Service) HasTokensForChannel(channel string) (bool, error) {
|
|
|
|
var (
|
|
|
|
err error
|
|
|
|
perm extendedPermission
|
|
|
|
)
|
|
|
|
|
|
|
|
if err = helpers.Retry(func() error {
|
|
|
|
err = s.db.DB().First(&perm, "channel = ?", strings.TrimLeft(channel, "#")).Error
|
|
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
2024-03-27 23:15:14 +00:00
|
|
|
return backoff.NewErrCannotRetry(ErrChannelNotAuthorized)
|
2023-12-13 23:02:14 +00:00
|
|
|
}
|
|
|
|
return errors.Wrap(err, "getting twitch credential from database")
|
|
|
|
}); err != nil {
|
|
|
|
if errors.Is(err, ErrChannelNotAuthorized) {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if perm.AccessToken, err = s.db.DecryptField(perm.AccessToken); err != nil {
|
|
|
|
return false, errors.Wrap(err, "decrypting access token")
|
|
|
|
}
|
|
|
|
|
|
|
|
if perm.RefreshToken, err = s.db.DecryptField(perm.RefreshToken); err != nil {
|
|
|
|
return false, errors.Wrap(err, "decrypting refresh token")
|
|
|
|
}
|
|
|
|
|
|
|
|
return perm.AccessToken != "" && perm.RefreshToken != "", nil
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// ListPermittedChannels returns a list of all channels having a token
|
|
|
|
// for the channels owner
|
2023-11-27 23:09:27 +00:00
|
|
|
func (s Service) ListPermittedChannels() (out []string, err error) {
|
2023-02-08 18:10:26 +00:00
|
|
|
var perms []extendedPermission
|
2023-11-27 23:09:27 +00:00
|
|
|
if err = helpers.Retry(func() error {
|
|
|
|
return errors.Wrap(s.db.DB().Find(&perms).Error, "listing permissions")
|
|
|
|
}); err != nil {
|
2024-01-01 16:52:18 +00:00
|
|
|
return nil, err //nolint:wrapcheck // is already wrapped on the inside
|
2023-02-08 18:10:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, perm := range perms {
|
|
|
|
out = append(out, perm.Channel)
|
|
|
|
}
|
|
|
|
|
|
|
|
return out, nil
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// RemoveAllExtendedTwitchCredentials wipes the access database
|
2023-03-24 18:23:48 +00:00
|
|
|
func (s Service) RemoveAllExtendedTwitchCredentials() error {
|
|
|
|
return errors.Wrap(
|
2023-11-27 23:09:27 +00:00
|
|
|
helpers.RetryTransaction(s.db.DB(), func(tx *gorm.DB) error {
|
|
|
|
return tx.Delete(&extendedPermission{}, "1 = 1").Error
|
|
|
|
}),
|
2023-03-24 18:23:48 +00:00
|
|
|
"deleting data from table",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// RemoveExendedTwitchCredentials wipes the access database for a given
|
|
|
|
// channel
|
2022-09-10 11:39:07 +00:00
|
|
|
func (s Service) RemoveExendedTwitchCredentials(channel string) error {
|
2022-10-22 22:08:02 +00:00
|
|
|
return errors.Wrap(
|
2023-11-27 23:09:27 +00:00
|
|
|
helpers.RetryTransaction(s.db.DB(), func(tx *gorm.DB) error {
|
|
|
|
return tx.Delete(&extendedPermission{}, "channel = ?", strings.TrimLeft(channel, "#")).Error
|
|
|
|
}),
|
2022-10-22 22:08:02 +00:00
|
|
|
"deleting data from table",
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// SetBotUsername stores the username of the bot
|
2023-02-06 18:40:06 +00:00
|
|
|
func (s Service) SetBotUsername(channel string) (err error) {
|
|
|
|
return errors.Wrap(
|
2023-03-15 20:27:00 +00:00
|
|
|
s.db.StoreCoreMeta(coreMetaKeyBotUsername, strings.TrimLeft(channel, "#")),
|
2023-02-06 18:40:06 +00:00
|
|
|
"storing bot username",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// SetExtendedTwitchCredentials stores tokens and scopes for the given
|
|
|
|
// channel into the access database
|
2022-09-10 11:39:07 +00:00
|
|
|
func (s Service) SetExtendedTwitchCredentials(channel, accessToken, refreshToken string, scope []string) (err error) {
|
|
|
|
if accessToken, err = s.db.EncryptField(accessToken); err != nil {
|
|
|
|
return errors.Wrap(err, "encrypting access token")
|
|
|
|
}
|
|
|
|
|
|
|
|
if refreshToken, err = s.db.EncryptField(refreshToken); err != nil {
|
|
|
|
return errors.Wrap(err, "encrypting refresh token")
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
return errors.Wrap(
|
2023-11-27 23:09:27 +00:00
|
|
|
helpers.RetryTransaction(s.db.DB(), func(tx *gorm.DB) error {
|
|
|
|
return tx.Clauses(clause.OnConflict{
|
|
|
|
Columns: []clause.Column{{Name: "channel"}},
|
|
|
|
DoUpdates: clause.AssignmentColumns([]string{"access_token", "refresh_token", "scopes"}),
|
|
|
|
}).Create(extendedPermission{
|
|
|
|
Channel: strings.TrimLeft(channel, "#"),
|
|
|
|
AccessToken: accessToken,
|
|
|
|
RefreshToken: refreshToken,
|
|
|
|
Scopes: strings.Join(scope, " "),
|
|
|
|
}).Error
|
|
|
|
}),
|
2022-10-22 22:08:02 +00:00
|
|
|
"inserting data into table",
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
}
|