package service import ( "context" "github.com/phishingclub/phishingclub/model" "github.com/phishingclub/phishingclub/repository" "io" "net/http" "strings" "testing" "time" "github.com/google/uuid" "github.com/phishingclub/phishingclub/cache" "github.com/phishingclub/phishingclub/data" "github.com/phishingclub/phishingclub/database" "go.uber.org/zap" ) // TestDeviceCodeEventSavedWhenRequestCancelled checks the device code event // is saved when the page request that made the code was cancelled func TestDeviceCodeEventSavedWhenRequestCancelled(t *testing.T) { campaignSvc, db := newPauseResumeService(t) if cache.EventIDByName[data.EVENT_CAMPAIGN_RECIPIENT_INFO] == nil { id := uuid.New() cache.EventIDByName[data.EVENT_CAMPAIGN_RECIPIENT_INFO] = &id } campaignID := seedCampaign(t, db, nil, nil, nil, nil) recipientID := uuid.New() svc := &MicrosoftDeviceCode{ Common: Common{Logger: zap.NewNop().Sugar()}, CampaignRepository: campaignSvc.CampaignRepository, CampaignRecipientRepository: campaignSvc.CampaignRecipientRepository, } ctx, cancel := context.WithCancel(context.Background()) cancel() svc.saveDeviceCodeCreatedEvent(ctx, &campaignID, &recipientID, "ABCD", "https://example.com/device", "") var n int64 if err := db.Model(&database.CampaignEvent{}).Where("campaign_id = ?", campaignID).Count(&n).Error; err != nil { t.Fatal(err) } if n != 1 { t.Fatalf("device code events %d, want 1", n) } } // tokenRoundTripper answers every token poll with captured tokens type tokenRoundTripper struct{} func (tokenRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { body := `{"access_token":"access","refresh_token":"refresh","id_token":"id"}` return &http.Response{ StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body)), }, nil } // deviceCodeRoundTripper answers every device code request with a new code type deviceCodeRoundTripper struct{} func (deviceCodeRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { body := `{"device_code":"device","user_code":"USER","verification_uri":"https://example.test/device","expires_in":900,"interval":5}` return &http.Response{ StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body)), }, nil } // TestRecipientDeleteRemovesDeviceCodes: deleting a person removes their // device codes with the captured tokens, in every campaign, and leaves those // of other people. A poll that gets tokens for a person who is deleted, or // is being deleted, stores no tokens and no event. A poll whose entry was // only replaced still records the capture. func TestRecipientDeleteRemovesDeviceCodes(t *testing.T) { p := newProgramLifecycleTest(t) if cache.EventIDByName[data.EVENT_CAMPAIGN_RECIPIENT_SUBMITTED_DATA] == nil { id := uuid.New() cache.EventIDByName[data.EVENT_CAMPAIGN_RECIPIENT_SUBMITTED_DATA] = &id } repo := &repository.MicrosoftDeviceCode{DB: p.db} svc := &MicrosoftDeviceCode{ Common: Common{Logger: zap.NewNop().Sugar()}, MicrosoftDeviceCodeRepository: repo, CampaignRepository: &repository.Campaign{DB: p.db}, CampaignRecipientRepository: &repository.CampaignRecipient{DB: p.db}, RecipientRepository: &repository.Recipient{DB: p.db}, HTTPClient: &http.Client{Transport: tokenRoundTripper{}}, } now := time.Now().UTC() expires := now.Add(time.Hour) campaignID := seedCampaign(t, p.db, nil, nil, nil, nil) person := func(email string) uuid.UUID { id := uuid.New() if err := p.db.Create(&database.Recipient{ID: &id, CreatedAt: &now, UpdatedAt: &now, Email: &email}).Error; err != nil { t.Fatalf("insert recipient: %v", err) } return id } entry := func(recipientID, campaign uuid.UUID) uuid.UUID { id := uuid.New() if err := p.db.Create(&database.MicrosoftDeviceCode{ ID: &id, CreatedAt: &now, UpdatedAt: &now, ExpiresAt: &expires, DeviceCode: "device", UserCode: "USER", VerificationURI: "https://example.test/device", ClientID: "client", CampaignID: &campaign, RecipientID: &recipientID, }).Error; err != nil { t.Fatalf("insert device code: %v", err) } return id } load := func(recipientID uuid.UUID) *model.MicrosoftDeviceCode { row, err := repo.GetByCampaignAndRecipientID(p.ctx, &campaignID, &recipientID) if err != nil { t.Fatalf("load device code: %v", err) } return row } events := func(recipientID uuid.UUID) int64 { var n int64 if err := p.db.Model(&database.CampaignEvent{}). Where("campaign_id = ? AND recipient_id = ?", campaignID.String(), recipientID.String()). Count(&n).Error; err != nil { t.Fatal(err) } return n } exists := func(id uuid.UUID) bool { var n int64 if err := p.db.Model(&database.MicrosoftDeviceCode{}).Where("id = ?", id.String()).Count(&n).Error; err != nil { t.Fatal(err) } return n > 0 } deleted, kept := person("deleted@example.test"), person("kept@example.test") deletedEntries := []uuid.UUID{entry(deleted, campaignID), entry(deleted, uuid.New())} keptEntry := entry(kept, campaignID) // the poll read this entry before the person was deleted stale := load(deleted) p.deleteRecipient(deleted) for _, id := range deletedEntries { if exists(id) { t.Fatal("a device code of the deleted person is still stored") } } if !exists(keptEntry) { t.Fatal("a device code of another person was removed") } if err := svc.pollAndCapture(p.ctx, stale); err != nil { t.Fatalf("poll after delete: %v", err) } if n := events(deleted); n != 0 { t.Fatalf("a capture after the delete stored %d events", n) } // a delete that is still running counts as deleted running := person("running@example.test") entry(running, campaignID) recipientDeletes.Store(running, struct{}{}) err := svc.pollAndCapture(p.ctx, load(running)) recipientDeletes.Delete(running) if err != nil { t.Fatalf("poll during delete: %v", err) } if n := events(running); n != 0 { t.Fatalf("a capture during the delete stored %d events", n) } if row := load(running); row.AccessToken != "" || row.Captured { t.Fatal("a capture during the delete stored tokens") } // a code made for a person whose delete is running is not kept creating := person("creating@example.test") svc.HTTPClient = &http.Client{Transport: deviceCodeRoundTripper{}} recipientDeletes.Store(creating, struct{}{}) _, err = svc.GetOrCreateDeviceCode(p.ctx, &campaignID, &creating, MicrosoftDeviceCodeOptions{ClientID: "11111111-2222-3333-4444-555555555555"}) recipientDeletes.Delete(creating) if err == nil || !strings.Contains(err.Error(), "recipient is deleted") { t.Fatalf("a device code for a person who is being deleted must be refused, got %v", err) } var left int64 if err := p.db.Model(&database.MicrosoftDeviceCode{}). Where("recipient_id = ?", creating.String()).Count(&left).Error; err != nil || left != 0 { t.Fatalf("device codes left for a person who is being deleted: %d %v", left, err) } if _, err := svc.GetOrCreateDeviceCode(p.ctx, &campaignID, &creating, MicrosoftDeviceCodeOptions{ClientID: "11111111-2222-3333-4444-555555555555"}); err != nil { t.Fatalf("a device code for a person who exists: %v", err) } svc.HTTPClient = &http.Client{Transport: tokenRoundTripper{}} // an entry that was only replaced still records the capture of a person // who exists replaced := load(kept) if err := p.db.Where("id = ?", keptEntry.String()).Delete(&database.MicrosoftDeviceCode{}).Error; err != nil { t.Fatal(err) } if err := svc.pollAndCapture(p.ctx, replaced); err != nil { t.Fatalf("poll of a replaced entry: %v", err) } if n := events(kept); n != 1 { t.Fatalf("the capture of a replaced entry stored %d events, want 1", n) } // a capture marks the entry and keeps no tokens on it, the capture is // saved as an event if err := svc.pollAndCapture(p.ctx, load(creating)); err != nil { t.Fatalf("poll of an entry: %v", err) } if row := load(creating); !row.Captured || row.AccessToken != "" || row.RefreshToken != "" || row.IDToken != "" { t.Fatalf("a capture must mark the entry and keep no tokens on it: captured %v, token %q", row.Captured, row.AccessToken) } if events(creating) == 0 { t.Fatal("the capture saved no event") } } // TestAnonymizeDataRemovesDeviceCodeTokens: Anonymize Data on an open // campaign removes the captured tokens kept on its device code entries. The // entries stay, a captured one stays captured, and another campaign keeps // its tokens. func TestAnonymizeDataRemovesDeviceCodeTokens(t *testing.T) { p := newProgramLifecycleTest(t) now := time.Now().UTC() expires := now.Add(time.Hour) campaignID := seedCampaign(t, p.db, nil, nil, nil, nil) otherID := seedCampaign(t, p.db, nil, nil, nil, nil) entry := func(campaign uuid.UUID, captured bool, token string) uuid.UUID { id, recipientID := uuid.New(), uuid.New() if err := p.db.Create(&database.MicrosoftDeviceCode{ ID: &id, CreatedAt: &now, UpdatedAt: &now, ExpiresAt: &expires, DeviceCode: "device", UserCode: "USER", VerificationURI: "https://example.test/device", ClientID: "client", CampaignID: &campaign, RecipientID: &recipientID, Captured: captured, AccessToken: token, RefreshToken: token, IDToken: token, }).Error; err != nil { t.Fatalf("insert device code: %v", err) } return id } read := func(id uuid.UUID) database.MicrosoftDeviceCode { var row database.MicrosoftDeviceCode if err := p.db.Where("id = ?", id.String()).First(&row).Error; err != nil { t.Fatalf("read device code: %v", err) } return row } captured := entry(campaignID, true, "secret") pending := entry(campaignID, false, "") other := entry(otherID, true, "secret") if err := p.svc.CampaignService.AnonymizeDataByID(p.ctx, authorizedSession(t), &campaignID); err != nil { t.Fatalf("anonymize data: %v", err) } row := read(captured) if row.AccessToken != "" || row.RefreshToken != "" || row.IDToken != "" { t.Fatalf("tokens were kept after Anonymize Data: %q %q %q", row.AccessToken, row.RefreshToken, row.IDToken) } if !row.Captured { t.Fatal("a captured entry must stay captured, or it is polled again") } if read(pending).Captured || read(pending).DeviceCode != "device" { t.Fatal("a pending entry was changed") } if read(other).AccessToken != "secret" { t.Fatal("the tokens of another campaign were removed") } }