Skip to content

Commit 2d9be80

Browse files
authored
security: harden sync point config, scheduling, and redo queries (pingcap#7034)
close pingcap#7033
1 parent d27892f commit 2d9be80

12 files changed

Lines changed: 163 additions & 32 deletions

File tree

‎api/v2/api.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ func RegisterOpenAPIV2Routes(router *gin.Engine, api OpenAPIV2) {
5858
debugGroup.Use(middleware.LogMiddleware())
5959
debugGroup.Use(middleware.ErrorHandleMiddleware())
6060
debugGroup.Use(nodeAuthenticateMiddleware, keyspaceCheckerMiddleware)
61+
// Failpoints are only instrumented in test builds (via failpoint-ctl enable);
62+
// production release binaries (make cdc) compile all failpoint.Inject sites out as no-ops.
6163
debugGroup.POST("/failpoints", middleware.ChangefeedOperationMiddleware("enable_failpoint"), api.EnableFailpoint)
6264
debugGroup.DELETE("/failpoints", middleware.ChangefeedOperationMiddleware("disable_failpoint"), api.DisableFailpoint)
6365
debugGroup.GET("/failpoints", api.ListFailpoints)

‎api/v2/failpoint.go‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,10 @@ func (r *failpointRegistry) snapshot() map[string]string {
7070

7171
var failpointState = newFailpointRegistry()
7272

73-
// EnableFailpoint enables a failpoint dynamically.
73+
// EnableFailpoint enables a failpoint dynamically for testing.
74+
// Production binaries are built without failpoint-ctl instrumentation, so all
75+
// failpoint.Inject sites are compiled out as no-ops and this endpoint has no
76+
// runtime injection effect in production.
7477
func (h *OpenAPIV2) EnableFailpoint(c *gin.Context) {
7578
req := &FailpointRequest{}
7679
if err := c.BindJSON(req); err != nil {

‎api/v2/failpoint_test.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//
99
// Unless required by applicable law or agreed to in writing, software
1010
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
// See the License for the specific language governing permissions and
1213
// limitations under the License.
1314

‎downstreamadapter/dispatchermanager/heartbeat_collector.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,12 @@ func (c *HeartBeatCollector) RecvMessages(_ context.Context, msg *messaging.Targ
271271
log.Warn("ignore schedule dispatcher request without changefeed ID", zap.Stringer("from", msg.From))
272272
return nil
273273
}
274+
if !isValidScheduleAction(schedulerDispatcherRequest.ScheduleAction) {
275+
log.Warn("ignore schedule dispatcher request with unknown action",
276+
zap.Stringer("from", msg.From),
277+
zap.Int32("action", int32(schedulerDispatcherRequest.ScheduleAction)))
278+
return nil
279+
}
274280
c.schedulerDispatcherRequestDynamicStream.Push(
275281
common.NewChangefeedGIDFromPB(schedulerDispatcherRequest.ChangefeedID),
276282
NewSchedulerDispatcherRequest(msg.From, schedulerDispatcherRequest))

‎downstreamadapter/dispatchermanager/helper.go‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ func (h *SchedulerDispatcherRequestHandler) Handle(dispatcherManager *Dispatcher
239239
// The remove operator will be deleted after the dispatcher is removed from dispatcherMap.
240240
handleScheduleRemove(dispatcherManager, req, dispatcherID)
241241
default:
242-
log.Panic("unknown schedule action", zap.Int("action", int(req.ScheduleAction)))
242+
log.Warn("ignore unknown schedule action", zap.Int32("action", int32(req.ScheduleAction)))
243243
}
244244
}
245245

@@ -263,11 +263,19 @@ func (h *SchedulerDispatcherRequestHandler) Handle(dispatcherManager *Dispatcher
263263
// Note: Remove requests are allowed to proceed even if the dispatcher doesn't exist (we still want to emit a
264264
// terminal status to the maintainer), but we must be careful not to store such requests (see handleScheduleRemove),
265265
// otherwise the operator entry would never be cleaned up.
266+
func isValidScheduleAction(action heartbeatpb.ScheduleAction) bool {
267+
return action == heartbeatpb.ScheduleAction_Create || action == heartbeatpb.ScheduleAction_Remove
268+
}
269+
266270
func preCheckForSchedulerHandler(req SchedulerDispatcherRequest, dispatcherManager *DispatcherManager) (common.DispatcherID, bool) {
267271
if req.ScheduleDispatcherRequest == nil {
268272
log.Warn("scheduleDispatcherRequest is nil, skip")
269273
return common.DispatcherID{}, false
270274
}
275+
if !isValidScheduleAction(req.ScheduleAction) {
276+
log.Warn("ignore unknown schedule action", zap.Int32("action", int32(req.ScheduleAction)))
277+
return common.DispatcherID{}, false
278+
}
271279
if req.Config == nil {
272280
log.Warn("scheduleDispatcherRequest config is nil, skip")
273281
return common.DispatcherID{}, false
@@ -464,7 +472,7 @@ func (h *SchedulerDispatcherRequestHandler) GetType(event SchedulerDispatcherReq
464472
case heartbeatpb.ScheduleAction_Remove:
465473
return dynstream.EventType{DataGroup: 2, Property: dynstream.NonBatchable}
466474
default:
467-
log.Panic("unknown schedule action", zap.Int("action", int(event.ScheduleAction)))
475+
log.Warn("ignore unknown schedule action", zap.Int32("action", int32(event.ScheduleAction)))
468476
}
469477
return dynstream.DefaultEventType
470478
}

‎downstreamadapter/dispatchermanager/helper_test.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@ import (
2424
"github.com/pingcap/ticdc/downstreamadapter/sink/redo"
2525
"github.com/pingcap/ticdc/heartbeatpb"
2626
"github.com/pingcap/ticdc/pkg/common"
27+
"github.com/pingcap/ticdc/pkg/messaging"
2728
"github.com/pingcap/ticdc/pkg/node"
29+
"github.com/pingcap/ticdc/utils/dynstream"
2830
"github.com/stretchr/testify/require"
2931
)
3032

@@ -450,3 +452,41 @@ func TestDispatcherManagerIsRedoReadyRequiresPublication(t *testing.T) {
450452

451453
require.True(t, dm.IsRedoReady())
452454
}
455+
456+
func TestUnknownScheduleActionIgnored(t *testing.T) {
457+
t.Parallel()
458+
459+
changefeedID := common.NewChangeFeedIDWithName("test-changefeed", "test-namespace")
460+
dispatcherID := common.NewDispatcherID()
461+
unknownReq := &heartbeatpb.ScheduleDispatcherRequest{
462+
ChangefeedID: changefeedID.ToPB(),
463+
Config: &heartbeatpb.DispatcherConfig{
464+
DispatcherID: dispatcherID.ToPB(),
465+
Mode: common.DefaultMode,
466+
},
467+
ScheduleAction: heartbeatpb.ScheduleAction(99),
468+
}
469+
470+
collector := &HeartBeatCollector{}
471+
targetMsg := messaging.NewSingleTargetMessage(
472+
node.ID("target"),
473+
messaging.HeartbeatCollectorTopic,
474+
unknownReq,
475+
)
476+
targetMsg.From = node.ID("maintainer")
477+
require.NoError(t, collector.RecvMessages(context.Background(), targetMsg))
478+
479+
dm := &DispatcherManager{
480+
changefeedID: changefeedID,
481+
dispatcherMap: newDispatcherMap[*dispatcher.EventDispatcher](),
482+
}
483+
req := NewSchedulerDispatcherRequest("maintainer", unknownReq)
484+
485+
_, ok := preCheckForSchedulerHandler(req, dm)
486+
require.False(t, ok)
487+
488+
handler := &SchedulerDispatcherRequestHandler{}
489+
require.Equal(t, dynstream.DefaultEventType, handler.GetType(req))
490+
require.False(t, handler.Handle(dm, req))
491+
require.Equal(t, 0, dm.dispatcherMap.Len())
492+
}

‎maintainer/maintainer_helper.go‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import (
1818

1919
"github.com/pingcap/ticdc/heartbeatpb"
2020
"github.com/pingcap/ticdc/maintainer/replica"
21-
"github.com/pingcap/ticdc/pkg/common"
2221
"github.com/pingcap/ticdc/pkg/node"
2322
)
2423

@@ -56,10 +55,14 @@ func (c *WatermarkCaptureMap) Delete(nodeID node.ID) {
5655

5756
// GetDispatcherCount returns the number of dispatchers.
5857
func (m *Maintainer) GetDispatcherCount(mode int64) int {
59-
if common.IsRedoMode(mode) {
60-
return len(m.controller.redoSpanController.GetAllTasks())
58+
if m.controller == nil {
59+
return 0
6160
}
62-
return len(m.controller.spanController.GetAllTasks())
61+
sc := m.controller.getSpanController(mode)
62+
if sc == nil {
63+
return 0
64+
}
65+
return len(sc.GetAllTasks())
6366
}
6467

6568
// MoveTable moves a table to a specific node.
@@ -74,10 +77,14 @@ func (m *Maintainer) MoveSplitTable(tableId int64, targetNode node.ID, mode int6
7477

7578
// GetTables returns all tables.
7679
func (m *Maintainer) GetTables(mode int64) []*replica.SpanReplication {
77-
if common.IsRedoMode(mode) {
78-
return m.controller.redoSpanController.GetAllTasks()
80+
if m.controller == nil {
81+
return nil
82+
}
83+
sc := m.controller.getSpanController(mode)
84+
if sc == nil {
85+
return nil
7986
}
80-
return m.controller.spanController.GetAllTasks()
87+
return sc.GetAllTasks()
8188
}
8289

8390
// SplitTableByRegionCount split table based on region count

‎maintainer/maintainer_test.go‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -988,3 +988,19 @@ func TestUpdateMetricsSyncPoint(t *testing.T) {
988988
require.False(t, maintainerSyncPointTsGauge.DeleteLabelValues(cfID.Keyspace(), cfID.Name()))
989989
require.False(t, maintainerSyncPointTsLagGauge.DeleteLabelValues(cfID.Keyspace(), cfID.Name()))
990990
}
991+
992+
func TestMaintainerGetDispatcherCountAndTablesWithNilRedoController(t *testing.T) {
993+
t.Parallel()
994+
995+
m := &Maintainer{
996+
controller: &Controller{},
997+
}
998+
require.Equal(t, 0, m.GetDispatcherCount(common.RedoMode))
999+
require.Nil(t, m.GetTables(common.RedoMode))
1000+
require.Equal(t, 0, m.GetDispatcherCount(common.DefaultMode))
1001+
require.Nil(t, m.GetTables(common.DefaultMode))
1002+
1003+
mNil := &Maintainer{}
1004+
require.Equal(t, 0, mNil.GetDispatcherCount(common.RedoMode))
1005+
require.Nil(t, mNil.GetTables(common.RedoMode))
1006+
}

‎pkg/config/replica_config.go‎

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -294,8 +294,7 @@ func (c *ReplicaConfig) ValidateAndAdjust(sinkURI *url.URL) error { // check sin
294294
if performanceMode == "" {
295295
c.PerformanceMode = util.AddressOf(PerformanceModeThroughput)
296296
} else if performanceMode != PerformanceModeThroughput && performanceMode != PerformanceModeLowLatency {
297-
return cerror.ErrInvalidReplicaConfig.FastGenByArgs(
298-
fmt.Sprintf("unknown performance mode: %s", performanceMode))
297+
return cerror.ErrInvalidReplicaConfig.FastGen("unknown performance mode: %s", performanceMode)
299298
}
300299

301300
enableRedoIOCheck := true
@@ -327,21 +326,21 @@ func (c *ReplicaConfig) ValidateAndAdjust(sinkURI *url.URL) error { // check sin
327326
return cerror.ErrInvalidReplicaConfig.
328327
FastGenByArgs("The SyncPoint must be disabled when the downstream is not tidb or mysql")
329328
}
330-
if c.SyncPointInterval != nil &&
331-
*c.SyncPointInterval < minSyncPointInterval {
332-
return cerror.ErrInvalidReplicaConfig.
333-
FastGenByArgs(
334-
fmt.Sprintf("The SyncPointInterval:%s must be larger than %s",
335-
c.SyncPointInterval.String(),
336-
minSyncPointInterval.String()))
329+
if c.SyncPointInterval == nil {
330+
c.SyncPointInterval = util.AddressOf(*defaultReplicaConfig.SyncPointInterval)
331+
}
332+
if *c.SyncPointInterval < minSyncPointInterval {
333+
return cerror.ErrInvalidReplicaConfig.FastGen(
334+
"The SyncPointInterval:%s must be larger than %s",
335+
c.SyncPointInterval.String(),
336+
minSyncPointInterval.String())
337337
}
338338
if c.SyncPointRetention != nil &&
339339
*c.SyncPointRetention < minSyncPointRetention {
340-
return cerror.ErrInvalidReplicaConfig.
341-
FastGenByArgs(
342-
fmt.Sprintf("The SyncPointRetention:%s must be larger than %s",
343-
c.SyncPointRetention.String(),
344-
minSyncPointRetention.String()))
340+
return cerror.ErrInvalidReplicaConfig.FastGen(
341+
"The SyncPointRetention:%s must be larger than %s",
342+
c.SyncPointRetention.String(),
343+
minSyncPointRetention.String())
345344
}
346345
}
347346
if util.GetOrZero(c.MemoryQuota) == uint64(0) {
@@ -385,19 +384,18 @@ func (c *ReplicaConfig) ValidateAndAdjust(sinkURI *url.URL) error { // check sin
385384

386385
if c.ChangefeedErrorStuckDuration != nil &&
387386
*c.ChangefeedErrorStuckDuration < minChangeFeedErrorStuckDuration {
388-
return cerror.ErrInvalidReplicaConfig.
389-
FastGenByArgs(
390-
fmt.Sprintf("The ChangefeedErrorStuckDuration:%f must be larger than %f Seconds",
391-
c.ChangefeedErrorStuckDuration.Seconds(),
392-
minChangeFeedErrorStuckDuration.Seconds()))
387+
return cerror.ErrInvalidReplicaConfig.FastGen(
388+
"The ChangefeedErrorStuckDuration:%f must be larger than %f Seconds",
389+
c.ChangefeedErrorStuckDuration.Seconds(),
390+
minChangeFeedErrorStuckDuration.Seconds())
393391
}
394392

395393
// allow the batch count and batch bytes set to 0, to disable the batch mechanism
396394
if c.EventCollectorBatchCount != nil && *c.EventCollectorBatchCount < 0 {
397395
return cerror.ErrInvalidReplicaConfig.FastGenByArgs("event-collector-batch-count must be set not smaller than 0")
398396
}
399397
if c.EventCollectorBatchCount != nil && *c.EventCollectorBatchCount > MaxEventCollectorBatchCount {
400-
return cerror.ErrInvalidReplicaConfig.FastGenByArgs(
398+
return cerror.ErrInvalidReplicaConfig.FastGen(
401399
"event-collector-batch-count must be set not larger than %d", MaxEventCollectorBatchCount,
402400
)
403401
}

‎pkg/config/replica_config_test.go‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,3 +338,23 @@ func TestReplicaConfig_AllowSameCluster(t *testing.T) {
338338
info := &ChangeFeedInfo{Config: cfg}
339339
require.True(t, info.ToChangefeedConfig().AllowSameCluster)
340340
}
341+
342+
func TestReplicaConfigSyncPointIntervalValidation(t *testing.T) {
343+
sinkURI, err := url.Parse("mysql://127.0.0.1:3306")
344+
require.NoError(t, err)
345+
346+
cfg := GetDefaultReplicaConfig()
347+
cfg.EnableSyncPoint = util.AddressOf(true)
348+
cfg.SyncPointInterval = nil
349+
require.NoError(t, cfg.ValidateAndAdjust(sinkURI))
350+
require.NotNil(t, cfg.SyncPointInterval)
351+
require.Equal(t, *defaultReplicaConfig.SyncPointInterval, *cfg.SyncPointInterval)
352+
353+
for _, d := range []time.Duration{0, -time.Second, 10 * time.Second} {
354+
cfg.SyncPointInterval = util.AddressOf(d)
355+
require.ErrorIs(t, cfg.ValidateAndAdjust(sinkURI), errors.ErrInvalidReplicaConfig)
356+
}
357+
358+
cfg.SyncPointInterval = util.AddressOf(30 * time.Second)
359+
require.NoError(t, cfg.ValidateAndAdjust(sinkURI))
360+
}

0 commit comments

Comments
 (0)