Skip to content
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

Validate for a valid cluster path when Invoke is called #37207

Merged
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
262a1f1
Fix invoke verification of data existence of cluster and endpoint
andy31415 Jan 27, 2025
0f28292
Add unit test for codegen logic issue
andy31415 Jan 27, 2025
796fd14
Add integration test for return codes
andy31415 Jan 27, 2025
6979ebd
Restule
andy31415 Jan 27, 2025
325ac8a
Remove odd comment
andy31415 Jan 27, 2025
31e5ee7
Remove unused import
andy31415 Jan 27, 2025
f8cff5e
Use asserts fail
andy31415 Jan 27, 2025
4be2502
Add unit test that checks invalid cluster return code as well
andy31415 Jan 27, 2025
63fcea0
Fix comment
andy31415 Jan 27, 2025
b7406d3
Code review feedback: listing of commands should fail if the cluster …
andy31415 Jan 27, 2025
583c6a8
Update src/data-model-providers/codegen/CodegenDataModelProvider.cpp
andy31415 Jan 27, 2025
e94b6a7
Update src/data-model-providers/codegen/CodegenDataModelProvider.cpp
andy31415 Jan 27, 2025
a605a2c
Update src/data-model-providers/codegen/CodegenDataModelProvider.cpp
andy31415 Jan 27, 2025
b26b721
Merge branch 'master' into check_cluster_validity_on_invoke
andreilitvin Jan 28, 2025
7052ac5
Updated comment
andreilitvin Jan 28, 2025
d837c7f
Try to reduce amount of code overhead for extra validation check
andreilitvin Jan 30, 2025
9fb74d2
Merge branch 'master' into check_cluster_validity_on_invoke
andreilitvin Jan 30, 2025
8b0ef03
Update logic yet again since just checking for null fails unit tests …
andreilitvin Jan 30, 2025
0961de7
Restyle
andreilitvin Jan 30, 2025
47d9f5f
Update src/data-model-providers/codegen/EmberMetadata.h
andy31415 Jan 30, 2025
7ddeb65
Update src/data-model-providers/codegen/EmberMetadata.h
andy31415 Jan 30, 2025
acede66
Update src/data-model-providers/codegen/CodegenDataModelProvider.cpp
andy31415 Jan 30, 2025
ceb4685
Update comment
andreilitvin Jan 30, 2025
5119c75
Update comment
andreilitvin Jan 30, 2025
2b20eed
Merge branch 'master' into check_cluster_validity_on_invoke
andreilitvin Jan 31, 2025
5abb6eb
Update based on code review ... if we cannot enforce an interface, we…
andreilitvin Jan 31, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/data-model-providers/codegen/CodegenDataModelProvider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,17 @@ std::optional<DataModel::ActionReturnStatus> CodegenDataModelProvider::Invoke(co
TLV::TLVReader & input_arguments,
CommandHandler * handler)
{
// Some commands are registered of ALL endpoints, so make sure first that
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
// the cluster actually exists on this endpoint before trying command handling
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
const EmberAfCluster * cluster = FindServerCluster(request.path);
if (cluster == nullptr)
{
// This is not a valid cluster. Return the right error code depending on what is valid.
std::optional<unsigned> endpoint_index = TryFindEndpointIndex(request.path.mEndpointId);
return endpoint_index.has_value() ? Protocols::InteractionModel::Status::UnsupportedCluster
: Protocols::InteractionModel::Status::UnsupportedEndpoint;
}

CommandHandlerInterface * handler_interface =
CommandHandlerInterfaceRegistry::Instance().GetCommandHandler(request.path.mEndpointId, request.path.mClusterId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,44 @@ class MockAccessControl : public Access::AccessControl::Delegate, public Access:
bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override { return true; }
};

class MockCommandHandler : public CommandHandler
{
public:
CHIP_ERROR FallibleAddStatus(const ConcreteCommandPath & aRequestCommandPath,
const Protocols::InteractionModel::ClusterStatusCode & aStatus,
const char * context = nullptr) override
{
// MOCK: do not do anything here
return CHIP_NO_ERROR;
}

void AddStatus(const ConcreteCommandPath & aRequestCommandPath, const Protocols::InteractionModel::ClusterStatusCode & aStatus,
const char * context = nullptr) override
{
// MOCK: do not do anything here
}

FabricIndex GetAccessingFabricIndex() const override { return 1; }

CHIP_ERROR AddResponseData(const ConcreteCommandPath & aRequestCommandPath, CommandId aResponseCommandId,
const DataModel::EncodableToTLV & aEncodable) override
{
return CHIP_NO_ERROR;
}

void AddResponse(const ConcreteCommandPath & aRequestCommandPath, CommandId aResponseCommandId,
const DataModel::EncodableToTLV & aEncodable) override
{}

bool IsTimedInvoke() const override { return false; }

void FlushAcksRightAwayOnSlowCommand() override {}

Access::SubjectDescriptor GetSubjectDescriptor() const override { return kAdminSubjectDescriptor; }

Messaging::ExchangeContext * GetExchangeContext() const override { return nullptr; }
};

/// Overrides Enumerate*Commands in the CommandHandlerInterface to allow
/// testing of behaviors when command enumeration is done in the interace.
class CustomListCommandHandler : public CommandHandlerInterface
Expand All @@ -229,7 +267,20 @@ class CustomListCommandHandler : public CommandHandlerInterface
}
~CustomListCommandHandler() { CommandHandlerInterfaceRegistry::Instance().UnregisterCommandHandler(this); }

void InvokeCommand(HandlerContext & handlerContext) override { handlerContext.SetCommandNotHandled(); }
void InvokeCommand(HandlerContext & handlerContext) override
{
if (mHandleCommand)
{
handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, Protocols::InteractionModel::Status::Success);
handlerContext.SetCommandHandled();
}
else
{
handlerContext.SetCommandNotHandled();
}
}

void SetHandleCommands(bool handle) { mHandleCommand = handle; }

CHIP_ERROR EnumerateAcceptedCommands(const ConcreteClusterPath & cluster, CommandIdCallback callback, void * context) override
{
Expand Down Expand Up @@ -268,6 +319,7 @@ class CustomListCommandHandler : public CommandHandlerInterface
private:
bool mOverrideAccepted = false;
bool mOverrideGenerated = false;
bool mHandleCommand = false;

std::vector<CommandId> mAccepted;
std::vector<CommandId> mGenerated;
Expand Down Expand Up @@ -1156,6 +1208,48 @@ TEST_F(TestCodegenModelViaMocks, IterateOverGeneratedCommands)
ASSERT_TRUE(cmds.data_equal(Span<const CommandId>(expectedCommands3)));
}

TEST_F(TestCodegenModelViaMocks, CommandHandlerInterfaceValidity)
{
UseMockNodeConfig config(gTestNodeConfig);
CodegenDataModelProviderWithContext model;

// register a CHI on ALL endpoints
CustomListCommandHandler handler(chip::NullOptional, MockClusterId(1));
handler.SetHandleCommands(true);

MockCommandHandler commandHandler;

// Command succeeds on a valid endpoint
{
const ConcreteCommandPath kCommandPath(kMockEndpoint1, MockClusterId(1), kMockCommandId1);
const InvokeRequest kInvokeRequest{ .path = kCommandPath };
chip::TLV::TLVReader tlvReader;

// std::nullopt is returned when the command is handled
ASSERT_EQ(model.Invoke(kInvokeRequest, tlvReader, /* handler = */ &commandHandler), std::nullopt);
}

// Command fails on an invalid endpoint
{
const ConcreteCommandPath kCommandPath(kEndpointIdThatIsMissing, MockClusterId(1), kMockCommandId1);
const InvokeRequest kInvokeRequest{ .path = kCommandPath };
chip::TLV::TLVReader tlvReader;

ASSERT_EQ(model.Invoke(kInvokeRequest, tlvReader, /* handler = */ &commandHandler),
Protocols::InteractionModel::Status::UnsupportedEndpoint);
}
andy31415 marked this conversation as resolved.
Show resolved Hide resolved

// Command fails on an invalid cluster
{
const ConcreteCommandPath kCommandPath(kMockEndpoint1, MockClusterId(0x1123), kMockCommandId1);
const InvokeRequest kInvokeRequest{ .path = kCommandPath };
chip::TLV::TLVReader tlvReader;

ASSERT_EQ(model.Invoke(kInvokeRequest, tlvReader, /* handler = */ &commandHandler),
Protocols::InteractionModel::Status::UnsupportedCluster);
}
}

TEST_F(TestCodegenModelViaMocks, CommandHandlerInterfaceCommandHandling)
{

Expand Down
81 changes: 81 additions & 0 deletions src/python_testing/TestInvokeReturnCodes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#
# Copyright (c) 2025 Project CHIP Authors
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# === BEGIN CI TEST ARGUMENTS ===
# test-runner-runs:
# run1:
# app: ${ALL_CLUSTERS_APP}
# app-args: >
# --discriminator 1234
# --KVS kvs1
# --trace-to json:${TRACE_APP}.json
# script-args: >
# --storage-path admin_storage.json
# --commissioning-method on-network
# --discriminator 1234
# --passcode 20202021
# --trace-to json:${TRACE_TEST_JSON}.json
# --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto
# factory-reset: true
# quiet: true
# === END CI TEST ARGUMENTS ===

import chip.clusters as Clusters
from chip.interaction_model import InteractionModelError, Status
from chip.testing.matter_testing import MatterBaseTest, async_test_body, default_matter_test_main
from mobly import asserts


class TestInvokeReturnCodes(MatterBaseTest):
"""
Validates that the invoke action correctly refuses commands
on invalid endpoints.
"""

@async_test_body
async def test_invalid_endpoint_command(self):
self.print_step(0, "Commissioning - already done")

self.print_step(1, "Find an invalid endpoint id")
root_parts = await self.read_single_attribute_check_success(
cluster=Clusters.Descriptor,
attribute=Clusters.Descriptor.Attributes.PartsList,
endpoint=0,
)
endpoints = set(root_parts)
invalid_endpoint_id = 1
while invalid_endpoint_id in endpoints:
invalid_endpoint_id += 1

self.print_step(
2,
"Attempt to invoke SoftwareDiagnostics::ResetWatermarks on an invalid endpoint",
)
try:
await self.send_single_cmd(
cmd=Clusters.SoftwareDiagnostics.Commands.ResetWatermarks(),
endpoint=invalid_endpoint_id,
)
asserts.fail("Unexpected command success on an invalid endpoint")
except InteractionModelError as e:
asserts.assert_equal(
e.status, Status.UnsupportedEndpoint, "Unexpected error returned"
)


if __name__ == "__main__":
default_matter_test_main()
Loading