Skip to content

Commit 45ccf87

Browse files
committed
security: harden p2p input validation, tso auth, and failpoint routes
Validate sync-point intervals, enforce 16-byte GID/DDLEvent length checks, remove remaining P2P/HTTP input panics, enforce authentication on POST /api/v2/tso when client-user-required is enabled, and gate /debug/failpoints routes behind the intest build tag. close pingcap#7033
1 parent 83f6d0d commit 45ccf87

23 files changed

Lines changed: 360 additions & 71 deletions

‎api/v2/api.go‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,7 @@ func RegisterOpenAPIV2Routes(router *gin.Engine, api OpenAPIV2) {
5858
debugGroup.Use(middleware.LogMiddleware())
5959
debugGroup.Use(middleware.ErrorHandleMiddleware())
6060
debugGroup.Use(nodeAuthenticateMiddleware, keyspaceCheckerMiddleware)
61-
debugGroup.POST("/failpoints", middleware.ChangefeedOperationMiddleware("enable_failpoint"), api.EnableFailpoint)
62-
debugGroup.DELETE("/failpoints", middleware.ChangefeedOperationMiddleware("disable_failpoint"), api.DisableFailpoint)
63-
debugGroup.GET("/failpoints", api.ListFailpoints)
61+
api.registerFailpointRoutes(debugGroup)
6462
debugGroup.GET("/puller", api.GetPullerDebugInfo)
6563
debugGroup.GET(
6664
"/puller/subscriptions/:subscription_id/regions/:region_id",
@@ -116,7 +114,7 @@ func RegisterOpenAPIV2Routes(router *gin.Engine, api OpenAPIV2) {
116114
ownerGroup.POST("/resign", api.ResignOwner)
117115

118116
// common APIs
119-
v2.POST("/tso", api.QueryTso)
117+
v2.POST("/tso", nodeAuthenticateMiddleware, api.QueryTso)
120118

121119
// unsafe apis
122120
unsafeGroup := v2.Group("/unsafe")

‎api/v2/api_test.go‎

Lines changed: 3 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -192,9 +192,7 @@ func TestManagementRoutesRequireAuthentication(t *testing.T) {
192192
}{
193193
{http.MethodPost, "/api/v2/log/redact?keyspace=" + common.DefaultKeyspaceName},
194194
{http.MethodPost, "/api/v2/owner/resign?keyspace=" + common.DefaultKeyspaceName},
195-
{http.MethodGet, "/debug/failpoints?keyspace=" + common.DefaultKeyspaceName},
196-
{http.MethodPost, "/debug/failpoints?keyspace=" + common.DefaultKeyspaceName},
197-
{http.MethodDelete, "/debug/failpoints?keyspace=" + common.DefaultKeyspaceName},
195+
{http.MethodPost, "/api/v2/tso?keyspace=" + common.DefaultKeyspaceName},
198196
{http.MethodGet, "/debug/puller?keyspace=" + common.DefaultKeyspaceName},
199197
{http.MethodGet, "/api/v2/unsafe/metadata?keyspace=" + common.DefaultKeyspaceName},
200198
{http.MethodPost, "/api/v2/unsafe/resolve_lock?keyspace=" + common.DefaultKeyspaceName},
@@ -253,13 +251,13 @@ func TestCaptureRouteAllowedWithClientUserRequired(t *testing.T) {
253251
require.Equal(t, http.StatusOK, response.Code, response.Body.String())
254252
}
255253

256-
func TestTsoRouteAllowedWithClientUserRequired(t *testing.T) {
254+
func TestManagementRoutesAllowedWithoutClientUserRequired(t *testing.T) {
257255
gin.SetMode(gin.TestMode)
258256

259257
originalConfig := config.GetGlobalServerConfig()
260258
t.Cleanup(func() { config.StoreGlobalServerConfig(originalConfig) })
261259
cfg := originalConfig.Clone()
262-
cfg.Security.ClientUserRequired = true
260+
cfg.Security.ClientUserRequired = false
263261
config.StoreGlobalServerConfig(cfg)
264262

265263
ctrl := gomock.NewController(t)
@@ -276,38 +274,3 @@ func TestTsoRouteAllowedWithClientUserRequired(t *testing.T) {
276274

277275
require.Equal(t, http.StatusOK, response.Code, response.Body.String())
278276
}
279-
280-
func TestManagementRoutesAllowedWithoutClientUserRequired(t *testing.T) {
281-
gin.SetMode(gin.TestMode)
282-
283-
originalConfig := config.GetGlobalServerConfig()
284-
t.Cleanup(func() { config.StoreGlobalServerConfig(originalConfig) })
285-
cfg := originalConfig.Clone()
286-
cfg.Security.ClientUserRequired = false
287-
config.StoreGlobalServerConfig(cfg)
288-
289-
ctrl := gomock.NewController(t)
290-
apiServer := mock.NewMockServer(ctrl)
291-
if kerneltype.IsNextGen() {
292-
previous, _ := appcontext.TryGetService[keyspace.Manager](appcontext.KeyspaceManager)
293-
t.Cleanup(func() { appcontext.SetService(appcontext.KeyspaceManager, previous) })
294-
keyspaceManager := keyspace.NewMockManager(ctrl)
295-
keyspaceManager.EXPECT().LoadKeyspace(gomock.Any(), common.DefaultKeyspaceName).Return(
296-
&keyspacepb.KeyspaceMeta{
297-
Keyspace: &keyspacepb.KeyspaceMeta_Id{Id: common.DefaultKeyspaceID},
298-
Name: common.DefaultKeyspaceName,
299-
}, nil,
300-
)
301-
appcontext.SetService[keyspace.Manager](appcontext.KeyspaceManager, keyspaceManager)
302-
}
303-
304-
router := gin.New()
305-
RegisterOpenAPIV2Routes(router, NewOpenAPIV2(apiServer))
306-
307-
request := httptest.NewRequest(http.MethodGet,
308-
"/debug/failpoints?keyspace="+common.DefaultKeyspaceName, nil)
309-
response := httptest.NewRecorder()
310-
router.ServeHTTP(response, request)
311-
312-
require.Equal(t, http.StatusOK, response.Code, response.Body.String())
313-
}

‎api/v2/failpoint.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
// See the License for the specific language governing permissions and
1212
// limitations under the License.
1313

14+
//go:build intest
15+
1416
package v2
1517

1618
import (
@@ -21,10 +23,17 @@ import (
2123

2224
"github.com/gin-gonic/gin"
2325
"github.com/pingcap/failpoint"
26+
"github.com/pingcap/ticdc/api/middleware"
2427
"github.com/pingcap/ticdc/pkg/api"
2528
cerror "github.com/pingcap/ticdc/pkg/errors"
2629
)
2730

31+
func (h *OpenAPIV2) registerFailpointRoutes(debugGroup *gin.RouterGroup) {
32+
debugGroup.POST("/failpoints", middleware.ChangefeedOperationMiddleware("enable_failpoint"), h.EnableFailpoint)
33+
debugGroup.DELETE("/failpoints", middleware.ChangefeedOperationMiddleware("disable_failpoint"), h.DisableFailpoint)
34+
debugGroup.GET("/failpoints", h.ListFailpoints)
35+
}
36+
2837
type FailpointRequest struct {
2938
Name string `json:"name"`
3039
Expr string `json:"expr"`

‎api/v2/failpoint_disabled.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright 2026 PingCAP, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
//go:build !intest
16+
17+
package v2
18+
19+
import "github.com/gin-gonic/gin"
20+
21+
func (h *OpenAPIV2) registerFailpointRoutes(_ *gin.RouterGroup) {}

‎api/v2/failpoint_test.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,12 @@
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

15+
//go:build intest
16+
1417
package v2
1518

1619
import (

‎downstreamadapter/dispatchermanager/heartbeat_collector.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,13 @@ 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 schedulerDispatcherRequest.ScheduleAction != heartbeatpb.ScheduleAction_Create &&
275+
schedulerDispatcherRequest.ScheduleAction != heartbeatpb.ScheduleAction_Remove {
276+
log.Warn("ignore schedule dispatcher request with unknown action",
277+
zap.Stringer("from", msg.From),
278+
zap.Int32("action", int32(schedulerDispatcherRequest.ScheduleAction)))
279+
return nil
280+
}
274281
c.schedulerDispatcherRequestDynamicStream.Push(
275282
common.NewChangefeedGIDFromPB(schedulerDispatcherRequest.ChangefeedID),
276283
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: 43 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,44 @@ func TestDispatcherManagerIsRedoReadyRequiresPublication(t *testing.T) {
450452

451453
require.True(t, dm.IsRedoReady())
452454
}
455+
456+
func TestUnknownScheduleActionDoesNotPanic(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.NotPanics(t, func() {
478+
require.NoError(t, collector.RecvMessages(context.Background(), targetMsg))
479+
})
480+
481+
dm := &DispatcherManager{
482+
changefeedID: changefeedID,
483+
dispatcherMap: newDispatcherMap[*dispatcher.EventDispatcher](),
484+
}
485+
req := NewSchedulerDispatcherRequest("maintainer", unknownReq)
486+
487+
_, ok := preCheckForSchedulerHandler(req, dm)
488+
require.False(t, ok)
489+
490+
handler := &SchedulerDispatcherRequestHandler{}
491+
require.NotPanics(t, func() {
492+
require.Equal(t, dynstream.DefaultEventType, handler.GetType(req))
493+
require.False(t, handler.Handle(dm, req))
494+
})
495+
}

‎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+
}

0 commit comments

Comments
 (0)