package user import ( "bytes" "context" "encoding/base64" "errors" "os" "path/filepath" "strings" "sync" "testing" "time" "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/compass" "git.golem15.com/golem15/summercms/modules/pact" "gorm.io/gorm" ) const ( sweepCommand = "user:jwt-blacklist-sweep" sweepIntervalKey = "golem15.user.jwt.blacklist_sweep_interval" ) // badSweepIntervals are values the scheduler cannot run, so Boot rejects them. var badSweepIntervals = []string{"soon", "3", "-1m", "500ms", "7m", "48h"} // fakeBlacklist is a bouncer.BlacklistStore that records the Sweep calls. type fakeBlacklist struct { mu sync.Mutex sweeps []time.Time sweepErr error } func (f *fakeBlacklist) Add(context.Context, string, time.Time, time.Time) error { return nil } func (f *fakeBlacklist) IsBlacklisted(context.Context, string) (bool, error) { return false, nil } func (f *fakeBlacklist) Sweep(_ context.Context, now time.Time) error { f.mu.Lock() defer f.mu.Unlock() f.sweeps = append(f.sweeps, now) return f.sweepErr } func (f *fakeBlacklist) calls() []time.Time { f.mu.Lock() defer f.mu.Unlock() return append([]time.Time(nil), f.sweeps...) } // TestBlacklistSweepSchedule schedules user:jwt-blacklist-sweep every 10m // by default, before Register (nil app) too, at a custom interval, not at // all for 0 or a bad value, and every scheduled command is a registered // command. func TestBlacklistSweepSchedule(t *testing.T) { want := pact.ScheduledCommand{Command: sweepCommand, Cadence: pact.Every(10 * time.Minute)} app := bareApp(t) for name, p := range map[string]*Plugin{"unset": {app: app}, "nil app": {}} { s := p.Schedule() if len(s) != 1 || s[0].Command != want.Command || s[0].Cadence != want.Cadence || len(s[0].Args) != 0 { t.Fatalf("%s: schedule = %+v", name, s) } } names := map[string]bool{} for _, c := range (&Plugin{app: app}).Commands() { names[c.Name] = true } for _, s := range (&Plugin{app: app}).Schedule() { if !names[s.Command] { t.Fatalf("scheduled %s is not registered: %v", s.Command, names) } } for value, every := range map[string]time.Duration{"1h": time.Hour, "30s": 30 * time.Second} { app := bareApp(t) if err := app.Config.Set(sweepIntervalKey, value); err != nil { t.Fatal(err) } s := (&Plugin{app: app}).Schedule() if len(s) != 1 || s[0].Command != sweepCommand || s[0].Cadence != pact.Every(every) { t.Fatalf("%s: schedule = %+v", value, s) } } for _, off := range []string{"0", "0s"} { app := bareApp(t) if err := app.Config.Set(sweepIntervalKey, off); err != nil { t.Fatal(err) } if s := (&Plugin{app: app}).Schedule(); len(s) != 0 { t.Fatalf("%s: schedule = %+v, want none", off, s) } } if s := (&Plugin{app: envApp(t, "SUMMER_GOLEM15__USER__JWT__BLACKLIST_SWEEP_INTERVAL=0")}).Schedule(); len(s) != 0 { t.Fatalf("SUMMER_ 0: schedule = %+v, want none", s) } for _, bad := range badSweepIntervals { app := bareApp(t) if err := app.Config.Set(sweepIntervalKey, bad); err != nil { t.Fatal(err) } if s := (&Plugin{app: app}).Schedule(); s != nil { t.Fatalf("%s: schedule = %+v, want nil", bad, s) } } } // envApp is a bare application whose config also reads environ. func envApp(t *testing.T, environ ...string) *backpack.App { t.Helper() dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-env\n"), 0o644); err != nil { t.Fatal(err) } cfg, err := compass.Open(compass.Options{Dir: dir, Environ: append([]string{"SUMMER_ENV=development"}, environ...)}) if err != nil { t.Fatal(err) } return backpack.New(cfg) } // TestBlacklistSweepBoot fails Boot on an interval the scheduler cannot run, // naming the key, and accepts 10m, 0 and an unset key. func TestBlacklistSweepBoot(t *testing.T) { withSecret := func(t *testing.T) *backpack.App { app := bareApp(t) if err := app.Config.Set("golem15.user.jwt.secret", "blacklist-sweep-boot-secret"); err != nil { t.Fatal(err) } return app } for _, bad := range badSweepIntervals { app := withSecret(t) if err := app.Config.Set(sweepIntervalKey, bad); err != nil { t.Fatal(err) } if err := (&Plugin{}).Boot(app); err == nil || !strings.Contains(err.Error(), sweepIntervalKey) { t.Fatalf("Boot with %q: %v", bad, err) } } for _, good := range []string{"10m", "0", ""} { app := withSecret(t) if good != "" { if err := app.Config.Set(sweepIntervalKey, good); err != nil { t.Fatal(err) } } if err := (&Plugin{}).Boot(app); err != nil && strings.Contains(err.Error(), sweepIntervalKey) { t.Fatalf("Boot with %q: %v", good, err) } } } // TestJWTBlacklistSweepCommand runs the command over a published store: one // Sweep with the current time and the result line; a failing store is an // error and no result line; a nil app is an error. func TestJWTBlacklistSweepCommand(t *testing.T) { run := func(t *testing.T, p *Plugin) (string, error) { t.Helper() cmd := commandNamed(t, p.Commands(), sweepCommand) var buf bytes.Buffer err := cmd.Run(context.Background(), emailArg{}, bonfire.NewOutput(nil, &buf, &buf)) return buf.String(), err } t.Run("published store", func(t *testing.T) { app := bareApp(t) fake := &fakeBlacklist{} if err := app.Publish[bouncer.BlacklistStore](fake); err != nil { t.Fatal(err) } before := time.Now() out, err := run(t, &Plugin{app: app}) after := time.Now() if err != nil { t.Fatalf("run: %v (output %q)", err, out) } calls := fake.calls() if len(calls) != 1 || calls[0].Before(before) || calls[0].After(after) { t.Fatalf("sweeps = %v, want one between %v and %v", calls, before, after) } if !strings.Contains(out, "Deleted the expired JWT blacklist rows.") { t.Fatalf("output = %q", out) } }) t.Run("failing store", func(t *testing.T) { app := bareApp(t) down := errors.New("blacklist down") if err := app.Publish[bouncer.BlacklistStore](&fakeBlacklist{sweepErr: down}); err != nil { t.Fatal(err) } out, err := run(t, &Plugin{app: app}) if !errors.Is(err, down) { t.Fatalf("run error = %v, want it to wrap %v", err, down) } if strings.Contains(out, "Deleted") { t.Fatalf("output after a failure = %q", out) } }) t.Run("nil app", func(t *testing.T) { if _, err := run(t, &Plugin{}); err == nil { t.Fatal("run with a nil app: no error") } }) } // TestJWTBlacklistSweepPostgres runs user:jwt-blacklist-sweep against // Postgres: through the store Boot published it deletes the expired row and // keeps the one still valid; as a console command with no published // database it opens one from database.dsn. func TestJWTBlacklistSweepPostgres(t *testing.T) { skipShortPostgres(t) gdb, sqlDB := sessionDB(t) insert := func(t *testing.T, jti string, at time.Time) { t.Helper() if err := gdb.Exec(`INSERT INTO jwt_blacklist (jti, expires_at, valid_until) VALUES (?, ?, ?)`, jti, at, at).Error; err != nil { t.Fatal(err) } t.Cleanup(func() { gdb.Exec(`DELETE FROM jwt_blacklist WHERE jti = ?`, jti) }) } count := func(t *testing.T, jti string) int64 { t.Helper() var n int64 if err := gdb.Raw(`SELECT COUNT(*) FROM jwt_blacklist WHERE jti = ?`, jti).Scan(&n).Error; err != nil { t.Fatal(err) } return n } run := func(t *testing.T, p *Plugin) string { t.Helper() var buf bytes.Buffer if err := commandNamed(t, p.Commands(), sweepCommand).Run(context.Background(), emailArg{}, bonfire.NewOutput(nil, &buf, &buf)); err != nil { t.Fatalf("run: %v (output %q)", err, buf.String()) } return buf.String() } t.Run("published store", func(t *testing.T) { p := bootPlugin(t, newSessionApp(t, gdb, sqlDB), "0s") insert(t, "sweep-me-published", time.Now().Add(-time.Minute)) insert(t, "sweep-keep-published", time.Now().Add(time.Hour)) out := run(t, p) if count(t, "sweep-me-published") != 0 { t.Fatal("the expired row was not deleted") } if count(t, "sweep-keep-published") != 1 { t.Fatal("the unexpired row was deleted") } if !strings.Contains(out, "Deleted the expired JWT blacklist rows.") { t.Fatalf("output = %q", out) } }) t.Run("database from config", func(t *testing.T) { app := backpack.New(sessionConfig(t)) if err := app.Config.Set("database.dsn", sessionDSN); err != nil { t.Fatal(err) } // Opening a database also loads the encryption keys from app.key. if err := app.Config.Set("app.key", base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef"))); err != nil { t.Fatal(err) } if _, ok := app.Lookup[*gorm.DB](); ok { t.Fatal("setup: a database is published") } insert(t, "sweep-me-console", time.Now().Add(-time.Minute)) insert(t, "sweep-keep-console", time.Now().Add(time.Hour)) run(t, &Plugin{app: app}) if count(t, "sweep-me-console") != 0 { t.Fatal("the expired row was not deleted") } if count(t, "sweep-keep-console") != 1 { t.Fatal("the unexpired row was deleted") } }) }