Skip to content

Commit a76caa8

Browse files
committed
security: harden p2p input validation and tso authentication
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 document that /debug/failpoints is test-only and inert in production builds. close pingcap#7033
1 parent 83f6d0d commit a76caa8

22 files changed

Lines changed: 333 additions & 66 deletions

File tree

‎api/v2/api.go‎

Lines changed: 3 additions & 1 deletion
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)
@@ -116,7 +118,7 @@ func RegisterOpenAPIV2Routes(router *gin.Engine, api OpenAPIV2) {
116118
ownerGroup.POST("/resign", api.ResignOwner)
117119

118120
// common APIs
119-
v2.POST("/tso", api.QueryTso)
121+
v2.POST("/tso", nodeAuthenticateMiddleware, api.QueryTso)
120122

121123
// unsafe apis
122124
unsafeGroup := v2.Group("/unsafe")

‎api/v2/api_test.go‎

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +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.MethodPost, "/api/v2/tso?keyspace=" + common.DefaultKeyspaceName},
195196
{http.MethodGet, "/debug/failpoints?keyspace=" + common.DefaultKeyspaceName},
196197
{http.MethodPost, "/debug/failpoints?keyspace=" + common.DefaultKeyspaceName},
197198
{http.MethodDelete, "/debug/failpoints?keyspace=" + common.DefaultKeyspaceName},
@@ -253,13 +254,13 @@ func TestCaptureRouteAllowedWithClientUserRequired(t *testing.T) {
253254
require.Equal(t, http.StatusOK, response.Code, response.Body.String())
254255
}
255256

256-
func TestTsoRouteAllowedWithClientUserRequired(t *testing.T) {
257+
func TestManagementRoutesAllowedWithoutClientUserRequired(t *testing.T) {
257258
gin.SetMode(gin.TestMode)
258259

259260
originalConfig := config.GetGlobalServerConfig()
260261
t.Cleanup(func() { config.StoreGlobalServerConfig(originalConfig) })
261262
cfg := originalConfig.Clone()
262-
cfg.Security.ClientUserRequired = true
263+
cfg.Security.ClientUserRequired = false
263264
config.StoreGlobalServerConfig(cfg)
264265

265266
ctrl := gomock.NewController(t)
@@ -276,38 +277,3 @@ func TestTsoRouteAllowedWithClientUserRequired(t *testing.T) {
276277

277278
require.Equal(t, http.StatusOK, response.Code, response.Body.String())
278279
}
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: 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: 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+
}

‎pkg/common/event/congestion_control.go‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ func (m *AvailableMemory) unmarshalV1(buf *bytes.Buffer) error {
8989
if buf.Len() < gidSize {
9090
return fmt.Errorf("invalid AvailableMemory payload: insufficient bytes for gid, need %d, got %d", gidSize, buf.Len())
9191
}
92-
m.Gid.Unmarshal(buf.Next(gidSize))
92+
if err := m.Gid.Unmarshal(buf.Next(gidSize)); err != nil {
93+
return err
94+
}
9395

9496
if buf.Len() < 8 {
9597
return fmt.Errorf("invalid AvailableMemory payload: insufficient bytes for available, need %d, got %d", 8, buf.Len())
@@ -107,7 +109,9 @@ func (m *AvailableMemory) unmarshalV1(buf *bytes.Buffer) error {
107109
if buf.Len() < dispatcherIDSize {
108110
return fmt.Errorf("invalid AvailableMemory payload: insufficient bytes for dispatcher id, need %d, got %d", dispatcherIDSize, buf.Len())
109111
}
110-
dispatcherID.Unmarshal(buf.Next(dispatcherIDSize))
112+
if err := dispatcherID.Unmarshal(buf.Next(dispatcherIDSize)); err != nil {
113+
return err
114+
}
111115

112116
if buf.Len() < 8 {
113117
return fmt.Errorf("invalid AvailableMemory payload: insufficient bytes for dispatcher available, need %d, got %d", 8, buf.Len())
@@ -122,7 +126,9 @@ func (m *AvailableMemory) unmarshalV2(buf *bytes.Buffer) error {
122126
if buf.Len() < gidSize {
123127
return fmt.Errorf("invalid AvailableMemory payload: insufficient bytes for gid, need %d, got %d", gidSize, buf.Len())
124128
}
125-
m.Gid.Unmarshal(buf.Next(gidSize))
129+
if err := m.Gid.Unmarshal(buf.Next(gidSize)); err != nil {
130+
return err
131+
}
126132

127133
if buf.Len() < 8 {
128134
return fmt.Errorf("invalid AvailableMemory payload: insufficient bytes for available, need %d, got %d", 8, buf.Len())
@@ -145,7 +151,9 @@ func (m *AvailableMemory) unmarshalV2(buf *bytes.Buffer) error {
145151
if buf.Len() < dispatcherIDSize {
146152
return fmt.Errorf("invalid AvailableMemory payload: insufficient bytes for dispatcher id, need %d, got %d", dispatcherIDSize, buf.Len())
147153
}
148-
dispatcherID.Unmarshal(buf.Next(dispatcherIDSize))
154+
if err := dispatcherID.Unmarshal(buf.Next(dispatcherIDSize)); err != nil {
155+
return err
156+
}
149157

150158
if buf.Len() < 8 {
151159
return fmt.Errorf("invalid AvailableMemory payload: insufficient bytes for dispatcher available, need %d, got %d", 8, buf.Len())
@@ -377,7 +385,9 @@ func (c *CongestionControl) decodeV2(data []byte) error {
377385
releaseByGid := make(map[common.GID]uint32, releaseEntryCount)
378386
for i := uint32(0); i < releaseEntryCount; i++ {
379387
gid := common.GID{}
380-
gid.Unmarshal(buf.Next(gidSize))
388+
if err := gid.Unmarshal(buf.Next(gidSize)); err != nil {
389+
return err
390+
}
381391
releaseByGid[gid] = binary.BigEndian.Uint32(buf.Next(4))
382392
}
383393

0 commit comments

Comments
 (0)