Boot started a ticker goroutine inside lagoon.OnDatabase that nothing stopped, so every booting process (serve, each console command, each test boot) leaked one and swept the blacklist once per process. The sweep is now the console command user:jwt-blacklist-sweep, which the conga scheduler runs on the job worker every golem15.user.jwt.blacklist_sweep_interval (default 10m, 0 for none), once per period across instances. An interval the scheduler cannot run (unparsable, negative, under 1s, not dividing 24h) now fails boot.
354 lines
11 KiB
Go
354 lines
11 KiB
Go
package user
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"embed"
|
|
"fmt"
|
|
"io/fs"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.golem15.com/golem15/sm-user-plugin/classes"
|
|
"git.golem15.com/golem15/sm-user-plugin/console"
|
|
usermiddleware "git.golem15.com/golem15/sm-user-plugin/middleware"
|
|
"git.golem15.com/golem15/sm-user-plugin/models"
|
|
"git.golem15.com/golem15/sm-user-plugin/updates"
|
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
|
"git.golem15.com/golem15/summercms/modules/pact"
|
|
"git.golem15.com/golem15/summercms/modules/party"
|
|
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
|
"git.golem15.com/golem15/summercms/modules/surf"
|
|
"github.com/go-gormigrate/gormigrate/v2"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var (
|
|
_ party.Plugin = (*Plugin)(nil)
|
|
_ pact.HasConfig = (*Plugin)(nil)
|
|
_ pact.HasMigrations = (*Plugin)(nil)
|
|
_ pact.HasMiddleware = (*Plugin)(nil)
|
|
_ pact.HasMiddlewareFactories = (*Plugin)(nil)
|
|
_ pact.HasModels = (*Plugin)(nil)
|
|
_ pact.HasRoutes = (*Plugin)(nil)
|
|
_ pact.HasMailTemplates = (*Plugin)(nil)
|
|
_ pact.HasLang = (*Plugin)(nil)
|
|
_ pact.HasCommands = (*Plugin)(nil)
|
|
_ pact.HasSchedule = (*Plugin)(nil)
|
|
_ surf.BucketProvider = (*Plugin)(nil)
|
|
_ bouncer.UserProvider = classes.GormUsers{}
|
|
)
|
|
|
|
//go:embed config
|
|
var configFS embed.FS
|
|
|
|
//go:embed views/mail
|
|
var mailFS embed.FS
|
|
|
|
//go:embed lang
|
|
var langFS embed.FS
|
|
|
|
// Plugin is the golem15.user plugin.
|
|
type Plugin struct {
|
|
app *backpack.App
|
|
}
|
|
|
|
func (p *Plugin) ID() string { return "golem15.user" }
|
|
func (p *Plugin) Requires() []string { return nil }
|
|
|
|
// Register publishes the login-gate registry (*classes.LoginGates), so a
|
|
// plugin that requires this one can add its gate in its Boot.
|
|
func (p *Plugin) Register(app *backpack.App) error {
|
|
p.app = app
|
|
if gates, ok := app.Lookup[*classes.LoginGates](); ok && gates != nil {
|
|
return nil
|
|
}
|
|
return app.Publish(classes.NewLoginGates())
|
|
}
|
|
|
|
func (p *Plugin) Boot(app *backpack.App) error {
|
|
p.app = app
|
|
secret, err := classes.JWTSecret(app)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := classes.MailFallbackLocale(app); err != nil {
|
|
return err
|
|
}
|
|
if _, err := classes.BlacklistSweepInterval(app); err != nil {
|
|
return err
|
|
}
|
|
// Serve publishes the database after Boot, so the GORM hooks and the
|
|
// blacklist store are installed on lagoon.Publish, or at once when the
|
|
// database is already published. Expired blacklist rows are deleted by
|
|
// the scheduled user:jwt-blacklist-sweep command (Schedule).
|
|
if err := lagoon.OnDatabase(app, func(sqlDB *sql.DB, gdb *gorm.DB) error {
|
|
if err := classes.RegisterHooks(gdb); err != nil {
|
|
return err
|
|
}
|
|
store := bouncer.NewPostgresBlacklist(sqlDB, classes.JWTBlacklistTable)
|
|
return app.Publish[bouncer.BlacklistStore](store)
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
reg, ok := app.Lookup[*bouncer.Registry]()
|
|
if !ok || reg == nil {
|
|
reg = bouncer.NewRegistry()
|
|
if err := app.Publish(reg); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := reg.Register(p.ID(), "jwt", bouncer.NewJWTGuard(secret, classes.GormUsers{App: app}, &appBlacklist{app: app}, classes.SessionCookieNames()...)); err != nil {
|
|
return err
|
|
}
|
|
prefix, err := classes.APITokenPrefix(app)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
trusted := surf.TrustedProxies(app.Config)
|
|
if err := reg.Register(p.ID(), "api_token", &usermiddleware.APITokenGuard{
|
|
App: app, Prefix: prefix,
|
|
ClientIP: func(r *http.Request) string { return surf.ClientIP(r, trusted) },
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
if err := p.bootBackendLinks(app); err != nil {
|
|
return err
|
|
}
|
|
p.bootDeviceRevocation(app)
|
|
if err := p.bootAPITokenScopes(app); err != nil {
|
|
return err
|
|
}
|
|
if err := p.bootMCPGuard(app); err != nil {
|
|
return err
|
|
}
|
|
return classes.RegisterUserAuthorizer(app)
|
|
}
|
|
|
|
// bootDeviceRevocation revokes the pending and confirmed device sessions of
|
|
// users who lose access (a ban or a password change, AccessRevokedEvent)
|
|
// inside the write's transaction, so a device authorized before the change
|
|
// is never handed a session token after it; a failed write rolls the change
|
|
// back.
|
|
func (p *Plugin) bootDeviceRevocation(app *backpack.App) {
|
|
if app == nil || app.Events == nil {
|
|
return
|
|
}
|
|
app.Events.Listen(p.ID(), func(ctx context.Context, ev *classes.AccessRevokedEvent) error {
|
|
if ev == nil || len(ev.UserIDs) == 0 {
|
|
return nil
|
|
}
|
|
db := ev.Tx
|
|
if db == nil {
|
|
gdb, ok := app.Lookup[*gorm.DB]()
|
|
if !ok || gdb == nil {
|
|
return fmt.Errorf("golem15.user: revoke device sessions: database is not configured")
|
|
}
|
|
db = gdb
|
|
}
|
|
return classes.RevokeDeviceSessions(ctx, db, ev.UserIDs...)
|
|
})
|
|
}
|
|
|
|
// bootAPITokenScopes compiles the member token scope catalog from the
|
|
// activated plugins (pact.HasFrontendTokenScopes), checks that every phrase
|
|
// key it names exists, and publishes it as *classes.APITokenScopeCatalog and
|
|
// as pact.MemberTokenScopeCatalog. A bad declaration fails boot.
|
|
func (p *Plugin) bootAPITokenScopes(app *backpack.App) error {
|
|
activated, _ := app.Lookup[party.Activated]()
|
|
catalog, err := classes.CompileAPITokenScopes(activated)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tr, ok := app.Lookup[*phrasebook.Translator](); ok && tr != nil {
|
|
for _, scope := range catalog.Scopes() {
|
|
for _, text := range []string{scope.Label, scope.Description} {
|
|
if strings.Contains(text, "::") && !tr.Has(text) {
|
|
who := scope.PluginID
|
|
if who == "" {
|
|
who = "golem15.user"
|
|
}
|
|
return fmt.Errorf("golem15.user: member token scope %s (%s) names missing phrase key %s", scope.Name, who, text)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if err := app.Publish(catalog); err != nil {
|
|
return err
|
|
}
|
|
return app.Publish[pact.MemberTokenScopeCatalog](catalog)
|
|
}
|
|
|
|
// bootMCPGuard registers the "user" MCP guard provider in the application's
|
|
// *pact.MCPGuards (publishing the registry when no one did yet) and
|
|
// publishes the same value as pact.MCPPersonalTokenResolver for the
|
|
// plugin's personal API tokens. Without the MCP module both stay unused.
|
|
func (p *Plugin) bootMCPGuard(app *backpack.App) error {
|
|
guards, ok := app.Lookup[*pact.MCPGuards]()
|
|
if !ok || guards == nil {
|
|
guards = pact.NewMCPGuards()
|
|
if err := app.Publish(guards); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
guard := &classes.MCPUserGuard{App: app}
|
|
if err := guards.Register(guard); err != nil {
|
|
return err
|
|
}
|
|
return app.Publish[pact.MCPPersonalTokenResolver](guard)
|
|
}
|
|
|
|
// bootBackendLinks publishes the account link service as *classes.BackendLinks
|
|
// and as the MCP linked-backend resolver, and removes a frontend user's link
|
|
// when the user is deleted or deactivated. The request lifetime is checked
|
|
// here so a bad golem15.user.backend_links.request_ttl fails the boot.
|
|
func (p *Plugin) bootBackendLinks(app *backpack.App) error {
|
|
if _, err := classes.BackendLinkRequestTTL(app); err != nil {
|
|
return err
|
|
}
|
|
links := &classes.BackendLinks{App: app}
|
|
if err := app.Publish(links); err != nil {
|
|
return err
|
|
}
|
|
if err := app.Publish[pact.MCPLinkedBackendResolver](links); err != nil {
|
|
return err
|
|
}
|
|
links.RegisterBackendLinkListeners(app)
|
|
return nil
|
|
}
|
|
|
|
// Schedule returns the scheduled commands: user:jwt-blacklist-sweep every
|
|
// golem15.user.jwt.blacklist_sweep_interval (10m by default), none when the
|
|
// interval is 0. p.app is nil before Register, which yields the default. A
|
|
// bad interval schedules nothing; Boot reports it.
|
|
func (p *Plugin) Schedule() []pact.ScheduledCommand {
|
|
interval, err := classes.BlacklistSweepInterval(p.app)
|
|
if err != nil || interval == 0 {
|
|
return nil
|
|
}
|
|
return []pact.ScheduledCommand{{Command: "user:jwt-blacklist-sweep", Cadence: pact.Every(interval)}}
|
|
}
|
|
|
|
func (p *Plugin) Buckets() map[string]surf.Bucket {
|
|
trusted := surf.TrustedProxies(nil)
|
|
if p.app != nil {
|
|
trusted = surf.TrustedProxies(p.app.Config)
|
|
}
|
|
secret := ""
|
|
if p.app != nil {
|
|
secret, _ = classes.JWTSecret(p.app)
|
|
}
|
|
return map[string]surf.Bucket{
|
|
"user-api": {
|
|
Max: 120,
|
|
Decay: time.Minute,
|
|
Key: func(r *http.Request) string {
|
|
if sub, err := bouncer.Verify(bearerFrom(r), secret); err == nil {
|
|
return "u:" + sub
|
|
}
|
|
return surf.ClientIP(r, trusted)
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
func bearerFrom(r *http.Request) string {
|
|
h := strings.TrimSpace(r.Header.Get("Authorization"))
|
|
token, ok := strings.CutPrefix(h, "Bearer ")
|
|
token = strings.TrimSpace(token)
|
|
if !ok || token == "" {
|
|
return ""
|
|
}
|
|
return token
|
|
}
|
|
|
|
func (p *Plugin) ConfigFS() fs.FS { return configFS }
|
|
|
|
func (p *Plugin) LangFS() fs.FS { return langFS }
|
|
|
|
func (p *Plugin) MailTemplatesFS() fs.FS { return mailFS }
|
|
|
|
func (p *Plugin) MailTemplates() []string {
|
|
return []string{
|
|
"golem15.user::mail.activate",
|
|
"golem15.user::mail.activate-en",
|
|
"golem15.user::mail.restore",
|
|
"golem15.user::mail.restore-en",
|
|
"golem15.user::mail.reactivate",
|
|
"golem15.user::mail.reactivate-en",
|
|
"golem15.user::mail.invite",
|
|
"golem15.user::mail.invite-en",
|
|
}
|
|
}
|
|
|
|
func (p *Plugin) MailLayouts() map[string]string {
|
|
return map[string]string{
|
|
"user": "golem15.user::mail.layouts.user",
|
|
}
|
|
}
|
|
|
|
// Commands returns the console commands, among them
|
|
// user:jwt-blacklist-sweep, which Schedule runs.
|
|
func (p *Plugin) Commands() []bonfire.Command {
|
|
return append([]bonfire.Command{
|
|
console.RequirePasswordChange(p.withDB),
|
|
console.BackfillHandles(p.app),
|
|
console.JWTBlacklistSweep(p.app),
|
|
}, console.APITokenCommands(p.app, p.withDB)...)
|
|
}
|
|
|
|
// withDB runs fn with the application's database: the one the serve command
|
|
// published, or, when a console command runs, one opened from the config for
|
|
// the duration of fn.
|
|
func (p *Plugin) withDB(ctx context.Context, fn func(*gorm.DB) error) error {
|
|
if p == nil || p.app == nil {
|
|
return fmt.Errorf("golem15.user: app is nil")
|
|
}
|
|
if gdb, ok := p.app.Lookup[*gorm.DB](); ok && gdb != nil {
|
|
return fn(gdb)
|
|
}
|
|
sqlDB, gdb, err := lagoon.OpenFromApp(ctx, p.app)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer sqlDB.Close()
|
|
return fn(gdb)
|
|
}
|
|
|
|
func (p *Plugin) Migrations() []*gormigrate.Migration { return updates.All() }
|
|
|
|
func (p *Plugin) Models() []any { return models.All() }
|
|
|
|
func (p *Plugin) Middlewares() map[string]pact.Middleware {
|
|
if p.app == nil {
|
|
return nil
|
|
}
|
|
reg, ok := p.app.Lookup[*bouncer.Registry]()
|
|
if !ok || reg == nil {
|
|
return nil
|
|
}
|
|
out := map[string]pact.Middleware{}
|
|
if mw, err := reg.Middleware("jwt"); err == nil {
|
|
out["jwt.auth"] = mw
|
|
}
|
|
if mw, err := reg.Middleware("api_token"); err == nil {
|
|
out["user.api_token"] = mw
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (p *Plugin) MiddlewareFactories() map[string]func(string) pact.Middleware {
|
|
return map[string]func(string) pact.Middleware{
|
|
"user.scope": usermiddleware.Scope,
|
|
"user.permission": usermiddleware.Permission,
|
|
}
|
|
}
|
|
|
|
func init() {
|
|
party.Register(&Plugin{})
|
|
}
|