Skip to content

Commit

Permalink
Ensure that DataModel::Encode does not encode kUnknownEnumValue for e…
Browse files Browse the repository at this point in the history
…nums.

This should help prevent those values leaking out on the wire.

Fixes project-chip#24368
  • Loading branch information
bzbarsky-apple committed Apr 28, 2023
1 parent e4d000d commit 0266a76
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 26 deletions.
23 changes: 22 additions & 1 deletion src/app/data-model/Encode.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ namespace chip {
namespace app {
namespace DataModel {

namespace detail {
// A way to detect whether an enum has a kUnknownEnumValue value, for use in enable_if.
template<typename Enum, Enum value>
using VoidType = void;

template<typename, typename = void>
constexpr bool HasUnknownValue = false;

template<typename T>
constexpr bool HasUnknownValue<T, VoidType<T, T::kUnknownEnumValue>> = true;
} // namespace detail

/*
* @brief
* Set of overloaded encode methods that based on the type of cluster element passed in,
Expand All @@ -48,9 +60,18 @@ CHIP_ERROR Encode(TLV::TLVWriter & writer, TLV::Tag tag, X x)
return writer.Put(tag, x);
}

template <typename X, typename std::enable_if_t<std::is_enum<X>::value, int> = 0>
template <typename X, typename std::enable_if_t<std::is_enum<X>::value && !detail::HasUnknownValue<X>, int> = 0>
CHIP_ERROR Encode(TLV::TLVWriter & writer, TLV::Tag tag, X x)
{
return writer.Put(tag, x);
}

template <typename X, typename std::enable_if_t<std::is_enum<X>::value && detail::HasUnknownValue<X>, int> = 0>
CHIP_ERROR Encode(TLV::TLVWriter & writer, TLV::Tag tag, X x)
{
if (x == X::kUnknownEnumValue) {
return CHIP_IM_GLOBAL_STATUS(ConstraintError);
}
return writer.Put(tag, x);
}

Expand Down
7 changes: 2 additions & 5 deletions src/app/tests/suites/TestCluster.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1068,11 +1068,8 @@ tests:
- name: "arg2"
value: 101
response:
values:
- name: "arg1"
value: 20003
- name: "arg2"
value: 4
# Attempting to echo back the invalid enum value should fail.
error: FAILURE

# Tests for Struct

Expand Down
8 changes: 1 addition & 7 deletions zzz_generated/chip-tool/zap-generated/test/Commands.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 6 additions & 13 deletions zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 0266a76

Please sign in to comment.