package service import ( "context" "strings" "testing" "time" "github.com/google/uuid" "github.com/oapi-codegen/nullable" "github.com/phishingclub/phishingclub/model" "github.com/phishingclub/phishingclub/repository" "go.uber.org/zap" ) // TestProgramAnonymizeDates checks the anonymize dates of a create follow // the start and end, and an update checks them with the stored values func TestProgramAnonymizeDates(t *testing.T) { start := time.Now().UTC().Add(time.Hour) end := start.Add(24 * time.Hour) at := func(t time.Time) *model.Program { p := &model.Program{} p.AnonymizeAt.Set(t) return p } data := func(t time.Time) *model.Program { p := &model.Program{} p.DataAnonymizeAt.Set(t) return p } cases := []struct { name string p *model.Program anonymous bool end *time.Time ok bool }{ {"anonymize needs an end", at(end), false, nil, false}, {"anonymize after the end", at(end.Add(time.Hour)), false, &end, true}, {"anonymize at the end", at(end), false, &end, true}, {"anonymize before the end", at(end.Add(-time.Hour)), false, &end, false}, {"anonymous takes no anonymize date", at(end.Add(time.Hour)), true, &end, false}, {"data without an end after the start", data(start.Add(time.Hour)), false, nil, true}, {"data before the start", data(start.Add(-time.Minute)), false, nil, false}, {"data before the end", data(end.Add(-time.Minute)), false, &end, false}, } for _, c := range cases { err := c.p.ValidateAnonymizeDates(c.anonymous, &start, c.end) if (err == nil) != c.ok { t.Errorf("%s: got %v", c.name, err) } } // an update keeps a stored end the date is checked against existing := &model.Program{} existing.EndAt.Set(end) existing.StartAt.Set(start) if err := validateAnonymizeDatesUpdate(at(end.Add(-time.Hour)), existing, false); err == nil { t.Fatal("an update must check the date against the stored end") } if err := validateAnonymizeDatesUpdate(at(end.Add(time.Hour)), existing, false); err != nil { t.Fatalf("a date after the stored end is fine: %v", err) } } func TestApplyStartRequest(t *testing.T) { now := time.Date(2024, 1, 8, 9, 0, 0, 0, time.UTC) yes, no := true, false future := now.Add(48 * time.Hour) past := now.Add(-48 * time.Hour) // create without a start starts now p := &model.Program{} applyStartRequest(p, nil, now) if got := p.StartAtTime(); got == nil || !got.Equal(now) { t.Fatalf("create without start: %v", got) } // create as draft has no start, also with a time given p = &model.Program{Draft: &yes, StartAt: nullable.NewNullableWithValue(future)} applyStartRequest(p, nil, now) if !p.StartAt.IsSpecified() || !p.StartAt.IsNull() { t.Fatal("draft must store a null start") } // a future start is kept, a past one is now p = &model.Program{StartAt: nullable.NewNullableWithValue(future)} applyStartRequest(p, nil, now) if !p.StartAtTime().Equal(future) { t.Fatal("future start changed") } p = &model.Program{StartAt: nullable.NewNullableWithValue(past)} applyStartRequest(p, nil, now) if !p.StartAtTime().Equal(now) { t.Fatal("past start should be now") } // update of a started program never changes the start started := now.Add(-time.Hour) existing := &model.Program{StartedAt: &started} p = &model.Program{Draft: &yes} applyStartRequest(p, existing, now) if p.StartAt.IsSpecified() { t.Fatal("started program start must not change") } // update of a draft without start fields leaves it alone draftProgram := &model.Program{} p = &model.Program{} applyStartRequest(p, draftProgram, now) if p.StartAt.IsSpecified() { t.Fatal("update without start fields must not change the start") } // update with draft false starts now p = &model.Program{Draft: &no} applyStartRequest(p, draftProgram, now) if got := p.StartAtTime(); got == nil || !got.Equal(now) { t.Fatal("draft false should start now") } // update with an explicit null start makes it a draft again p = &model.Program{StartAt: nullable.NewNullNullable[time.Time]()} applyStartRequest(p, draftProgram, now) if !p.StartAt.IsSpecified() || !p.StartAt.IsNull() { t.Fatal("null start should make a draft") } } func TestSameScope(t *testing.T) { a := uuid.New() b := uuid.New() global := nullable.NewNullNullable[uuid.UUID]() ownedByA := nullable.NewNullableWithValue(a) if !sameScope(nil, global) || !sameScope(&a, global) { t.Fatalf("a global resource is usable by every program") } if !sameScope(&a, ownedByA) { t.Fatalf("a company resource is usable by that company") } if sameScope(&b, ownedByA) { t.Fatalf("a company resource must not be usable by another company") } if sameScope(nil, ownedByA) { t.Fatalf("a company resource must not be usable by a global program") } } // TestValidateEndAtUpdate checks the end of an update against the start the // program will have and only asks a new end to be in the future func TestValidateEndAtUpdate(t *testing.T) { now := time.Now().UTC() started := now.Add(-30 * 24 * time.Hour) existing := &model.Program{ StartAt: nullable.NewNullableWithValue(started), EndAt: nullable.NewNullableWithValue(now.Add(-time.Minute)), } // an edit that leaves a passed end alone is allowed if changed, err := validateEndAtUpdate(&model.Program{}, existing, now); err != nil || changed { t.Fatalf("unchanged end: changed=%v err=%v", changed, err) } // a new end in the past is refused incoming := &model.Program{EndAt: nullable.NewNullableWithValue(now.Add(-time.Hour))} if _, err := validateEndAtUpdate(incoming, existing, now); err == nil || !strings.Contains(err.Error(), "in the future") { t.Fatalf("expected a past end refused, got %v", err) } // a new end in the future is a change incoming = &model.Program{EndAt: nullable.NewNullableWithValue(now.AddDate(1, 0, 0))} if changed, err := validateEndAtUpdate(incoming, existing, now); err != nil || !changed { t.Fatalf("future end: changed=%v err=%v", changed, err) } // clearing the end is allowed and is not a new end incoming = &model.Program{EndAt: nullable.NewNullNullable[time.Time]()} if changed, err := validateEndAtUpdate(incoming, existing, now); err != nil || changed { t.Fatalf("cleared end: changed=%v err=%v", changed, err) } // a scheduled program moved to start after its end is refused scheduled := &model.Program{ StartAt: nullable.NewNullableWithValue(now.Add(24 * time.Hour)), EndAt: nullable.NewNullableWithValue(now.Add(48 * time.Hour)), } incoming = &model.Program{StartAt: nullable.NewNullableWithValue(now.Add(72 * time.Hour))} if _, err := validateEndAtUpdate(incoming, scheduled, now); err == nil || !strings.Contains(err.Error(), "after the start") { t.Fatalf("expected a start after the end refused, got %v", err) } } func TestCtxMutexHonoursContext(t *testing.T) { var m ctxMutex m.Lock() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() if err := m.LockContext(ctx); err == nil { t.Fatal("a held lock must give up when the context ends") } m.Unlock() if err := m.LockContext(context.Background()); err != nil { t.Fatalf("a free lock must be taken: %v", err) } m.Unlock() } // callPanics runs fn and reports whether it panicked func callPanics(fn func()) (panicked bool) { defer func() { if recover() != nil { panicked = true } }() fn() return false } // TestLifecycleLockReleasedOnPanic checks a panic while the lifecycle lock is // held never leaves it held func TestLifecycleLockReleasedOnPanic(t *testing.T) { s := &Program{Common: Common{Logger: zap.NewNop().Sugar()}} if !callPanics(func() { _ = s.withLifecycleLock(context.Background(), func() error { panic("in the locked part") }) }) { t.Fatalf("expected the hook to panic") } if !lockIsFree(s) { t.Fatalf("a panic in withLifecycleLock left the lock held") } // a repository without a database panics on its first read, inside the // locked part of an advance batch and in a tick s.ProgramRepository = &repository.Program{} if !callPanics(func() { _, _ = s.advanceDueBatch(context.Background(), nil, time.Now()) }) { t.Fatalf("expected the advance batch to panic") } if !lockIsFree(s) { t.Fatalf("a panic in the advance batch left the lock held") } if !callPanics(func() { _ = s.Tick(context.Background(), authorizedSession(t)) }) { t.Fatalf("expected the tick to panic") } if !lockIsFree(s) { t.Fatalf("a panic in the tick left the lock held") } }