Repository navigation
fix(worker): lock the risk while resolving its evidence links #490
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
puzza007
wants to merge
4
commits into
compliance-framework:main
Choose a base branch
from
puzza007:fix/risk-resolution-row-lock
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+177
−6
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e5818a9
test(worker): provoke an open risk left with no evidence links
puzza007 2d45d7e
fix(worker): lock the risk while resolving its evidence links
puzza007 31c987f
refactor(risks): share the terminal-status check with the worker
puzza007 c93cc32
test(worker): cover a risk closed or accepted while resolution runs
puzza007 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
internal/service/worker/risk_evidence_integration_helpers_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| //go:build integration | ||
|
|
||
| package worker | ||
|
|
||
| import ( | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/compliance-framework/api/internal/service/relational" | ||
| oscalTypes_1_1_3 "github.com/defenseunicorns/go-oscal/src/types/oscal-1-1-3" | ||
| "github.com/google/uuid" | ||
| "github.com/stretchr/testify/require" | ||
| "gorm.io/datatypes" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| // createStreamEvidence creates an evidence of the given stream with the given state and end. | ||
| func createStreamEvidence(t *testing.T, db *gorm.DB, stream uuid.UUID, state string, end time.Time) *relational.Evidence { | ||
| t.Helper() | ||
| id := uuid.New() | ||
| evidence := &relational.Evidence{ | ||
| UUIDModel: relational.UUIDModel{ID: &id}, | ||
| UUID: stream, | ||
| Title: "Test Evidence", | ||
| Start: end.Add(-time.Hour), | ||
| End: end, | ||
| Status: datatypes.NewJSONType(oscalTypes_1_1_3.ObjectiveStatus{State: state}), | ||
| } | ||
| require.NoError(t, db.Create(evidence).Error) | ||
| return evidence | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
124 changes: 124 additions & 0 deletions
124
internal/service/worker/risk_resolution_race_integration_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| //go:build integration | ||
|
|
||
| package worker | ||
|
|
||
| import ( | ||
| "context" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/compliance-framework/api/internal/service/relational" | ||
| "github.com/compliance-framework/api/internal/service/relational/risks" | ||
| "github.com/compliance-framework/api/internal/tests" | ||
| "github.com/google/uuid" | ||
| "github.com/stretchr/testify/suite" | ||
| "go.uber.org/zap" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| type RiskResolutionRaceIntegrationSuite struct { | ||
| tests.IntegrationTestSuite | ||
| } | ||
|
|
||
| func TestRiskResolutionRaceIntegrationSuite(t *testing.T) { | ||
| suite.Run(t, new(RiskResolutionRaceIntegrationSuite)) | ||
| } | ||
|
|
||
| func (s *RiskResolutionRaceIntegrationSuite) SetupTest() { | ||
| s.Require().NoError(s.Migrator.Refresh()) | ||
| } | ||
|
|
||
| // Two streams of a risk pass at once: the second job runs between the first's count of the | ||
| // risk's remaining links and its commit, and the risk must still end up remediated. | ||
| func (s *RiskResolutionRaceIntegrationSuite) TestConcurrentPassingStreamsRemediateTheRisk() { | ||
| ctx := context.Background() | ||
| worker := NewRiskEvidenceWorker(s.DB, zap.NewNop().Sugar()) | ||
| first := createStreamEvidence(s.T(), s.DB, uuid.New(), relational.EvidenceStatusSatisfied, time.Now()) | ||
| second := createStreamEvidence(s.T(), s.DB, uuid.New(), relational.EvidenceStatusSatisfied, time.Now()) | ||
| risk := createRiskWithEvidenceLink(s.T(), s.DB, string(risks.RiskStatusOpen), first.UUID, nil) | ||
| s.Require().NoError(s.DB.Create(&risks.RiskEvidenceLink{RiskID: *risk.ID, EvidenceID: second.UUID}).Error) | ||
|
|
||
| const cb = "test:second_stream_resolves" | ||
| var fired atomic.Bool | ||
| var secondErr error | ||
| secondDone := make(chan struct{}) | ||
| s.Require().NoError(s.DB.Callback().Query().After("gorm:query").Register(cb, func(db *gorm.DB) { | ||
| _, isCount := db.Statement.Dest.(*int64) | ||
| if !isCount || db.Statement.Table != (risks.RiskEvidenceLink{}).TableName() || !fired.CompareAndSwap(false, true) { | ||
| return | ||
| } | ||
| go func() { | ||
| defer close(secondDone) | ||
| secondErr = worker.Work(ctx, makeWorkerJob(RiskProcessEvidenceArgs{EvidenceID: *second.ID})) | ||
| }() | ||
| // Let the second job finish, or block on a lock the first job holds. | ||
| s.Eventually(func() bool { | ||
| select { | ||
| case <-secondDone: | ||
| return true | ||
| default: | ||
| } | ||
| var waiting int64 | ||
| err := s.DB.Raw(`SELECT count(*) FROM pg_stat_activity | ||
| WHERE datname = current_database() AND wait_event_type = 'Lock'`).Scan(&waiting).Error | ||
| return err == nil && waiting > 0 | ||
| }, 10*time.Second, 10*time.Millisecond) | ||
| })) | ||
| defer func() { s.Require().NoError(s.DB.Callback().Query().Remove(cb)) }() | ||
|
|
||
| s.Require().NoError(worker.Work(ctx, makeWorkerJob(RiskProcessEvidenceArgs{EvidenceID: *first.ID}))) | ||
| s.Require().True(fired.Load()) | ||
| <-secondDone | ||
| s.Require().NoError(secondErr) | ||
|
|
||
| s.assertRisk(*risk.ID, risks.RiskStatusRemediated, 0) | ||
| } | ||
|
|
||
| // A user closes the risk after resolution read it: the link stays and the risk stays closed. | ||
| func (s *RiskResolutionRaceIntegrationSuite) TestResolutionLeavesRiskClosedMeanwhile() { | ||
| riskID := s.resolveWhileStatusChanges(risks.RiskStatusClosed) | ||
| s.assertRisk(riskID, risks.RiskStatusClosed, 1) | ||
| } | ||
|
|
||
| // A user accepts the risk after resolution read it: the link goes and the risk stays | ||
| // accepted, with an evidence_recovered event in place of remediation. | ||
| func (s *RiskResolutionRaceIntegrationSuite) TestResolutionKeepsRiskAcceptedMeanwhile() { | ||
| riskID := s.resolveWhileStatusChanges(risks.RiskStatusRiskAccepted) | ||
| s.assertRisk(riskID, risks.RiskStatusRiskAccepted, 0) | ||
| var recovered int64 | ||
| s.Require().NoError(s.DB.Model(&risks.RiskEvent{}).Where("risk_id = ? AND event_type = ?", | ||
| riskID, string(risks.RiskEventTypeEvidenceRecovered)).Count(&recovered).Error) | ||
| s.Equal(int64(1), recovered) | ||
| } | ||
|
|
||
| // resolveWhileStatusChanges resolves a passing evidence of an open risk, setting the risk's | ||
| // status right after resolution's unlocked read of the linked risks. | ||
| func (s *RiskResolutionRaceIntegrationSuite) resolveWhileStatusChanges(status risks.RiskStatus) uuid.UUID { | ||
| worker := NewRiskEvidenceWorker(s.DB, zap.NewNop().Sugar()) | ||
| evidence := createStreamEvidence(s.T(), s.DB, uuid.New(), relational.EvidenceStatusSatisfied, time.Now()) | ||
| risk := createRiskWithEvidenceLink(s.T(), s.DB, string(risks.RiskStatusOpen), evidence.UUID, nil) | ||
|
|
||
| const cb = "test:status_changes_after_read" | ||
| var changed atomic.Bool | ||
| s.Require().NoError(s.DB.Callback().Query().After("gorm:query").Register(cb, func(db *gorm.DB) { | ||
| if _, ok := db.Statement.Dest.(*[]risks.Risk); ok && changed.CompareAndSwap(false, true) { | ||
| s.Require().NoError(s.DB.Model(risk).Update("status", string(status)).Error) | ||
| } | ||
| })) | ||
| defer func() { s.Require().NoError(s.DB.Callback().Query().Remove(cb)) }() | ||
|
|
||
| s.Require().NoError(worker.handleEvidenceResolution(context.Background(), evidence)) | ||
| s.Require().True(changed.Load()) | ||
| return *risk.ID | ||
| } | ||
|
|
||
| // assertRisk checks the stored risk's status and how many evidence links it has left. | ||
| func (s *RiskResolutionRaceIntegrationSuite) assertRisk(id uuid.UUID, status risks.RiskStatus, links int64) { | ||
| var stored risks.Risk | ||
| s.Require().NoError(s.DB.First(&stored, "id = ?", id).Error) | ||
| s.Equal(string(status), stored.Status) | ||
| var count int64 | ||
| s.Require().NoError(s.DB.Model(&risks.RiskEvidenceLink{}).Where("risk_id = ?", id).Count(&count).Error) | ||
| s.Equal(links, count) | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.