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

Move ::WriteAttribute validation inside Interaction Model Write Handling #37322

Merged
merged 32 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
39dece4
Move write validity inside the write handler rather than requesting t…
andreilitvin Jan 30, 2025
0b37533
Restyle
andreilitvin Jan 30, 2025
345fffe
A bit of code cleanup and reuse, to minimize flash impact
andreilitvin Jan 30, 2025
963a235
Restyle
andreilitvin Jan 30, 2025
9f0ba20
Drop the mPreviousSuccessPath, making objects smaller and saving yet …
andreilitvin Jan 30, 2025
d00c1ba
Cleanup some includes
andreilitvin Jan 30, 2025
a5fc51a
Restyle
andreilitvin Jan 30, 2025
cc77d33
Remove obsolete tests from codgen, as we do not do more validation now
andreilitvin Jan 30, 2025
30670c8
Test write interaction passes
andreilitvin Jan 30, 2025
556d06b
Test write passes
andreilitvin Jan 30, 2025
299e75a
Slight clarity of code update
andreilitvin Jan 30, 2025
d6cb071
Fix comment
andreilitvin Jan 30, 2025
9d38910
Manual check for last written saves 16 bytes of flash on QPG.
andreilitvin Jan 30, 2025
77ba731
Status success is 2 bytes smaller in code generation than CHIP_NO_ERROR
andreilitvin Jan 30, 2025
abb61d3
Not using endpoint finder saves flash
andreilitvin Jan 30, 2025
f51eb31
Clean up code. We now save flash
andreilitvin Jan 30, 2025
714e7bf
More flash savings by reusing the server cluster finder
andreilitvin Jan 30, 2025
8346610
Update src/app/data-model-provider/MetadataLookup.cpp
andy31415 Jan 30, 2025
bc00cfd
Update src/app/data-model-provider/MetadataLookup.h
andy31415 Jan 30, 2025
266c8b9
Update src/app/data-model-provider/Provider.h
andy31415 Jan 30, 2025
ca7e6cf
Update src/app/data-model-provider/MetadataLookup.h
andy31415 Jan 30, 2025
3090732
Updated comment
andreilitvin Jan 30, 2025
d36e731
Hoist "writing" log up in processing, to preserve similar functionality
andreilitvin Jan 30, 2025
61d7ac7
Code clarity updates
andreilitvin Jan 31, 2025
b5d9035
Fix includes and update the code AGAIN because it does seem we use mo…
andreilitvin Jan 31, 2025
70ca917
Fix unsupported write on global attributes
andreilitvin Jan 31, 2025
ea2daaf
Fix includes
andreilitvin Jan 31, 2025
1d34e06
Update src/app/WriteHandler.cpp
andy31415 Feb 1, 2025
5509caf
Merge branch 'master' into write_handler_validation
andreilitvin Feb 6, 2025
3e224f4
Post merge cleanup
andreilitvin Feb 6, 2025
b0111d9
Fix merge error
andreilitvin Feb 6, 2025
17dbfe0
Merge branch 'master' into write_handler_validation
andreilitvin Feb 7, 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
24 changes: 2 additions & 22 deletions src/app/InteractionModelEngine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1801,28 +1801,8 @@ Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandExistenc
}
}

{
DataModel::ServerClusterFinder finder(provider);
if (finder.Find(aCommandPath).has_value())
{
// cluster exists, so command is invalid
return Protocols::InteractionModel::Status::UnsupportedCommand;
}
}

// At this point either cluster or endpoint does not exist. If we find the endpoint, then the cluster
// is invalid
{
DataModel::EndpointFinder finder(provider);
if (finder.Find(aCommandPath.mEndpointId))
{
// endpoint exists, so cluster is invalid
return Protocols::InteractionModel::Status::UnsupportedCluster;
}
}

// endpoint not found
return Protocols::InteractionModel::Status::UnsupportedEndpoint;
// invalid command, return the right failure status
return DataModel::ValidateClusterPath(provider, aCommandPath, Protocols::InteractionModel::Status::UnsupportedCommand);
}

DataModel::Provider * InteractionModelEngine::SetDataModelProvider(DataModel::Provider * model)
Expand Down
87 changes: 79 additions & 8 deletions src/app/WriteHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
#include <app/InteractionModelEngine.h>
#include <app/MessageDef/EventPathIB.h>
#include <app/MessageDef/StatusIB.h>
#include <app/RequiredPrivilege.h>
#include <app/StatusResponse.h>
#include <app/WriteHandler.h>
#include <app/data-model-provider/ActionReturnStatus.h>
#include <app/data-model-provider/MetadataLookup.h>
#include <app/data-model-provider/MetadataTypes.h>
#include <app/data-model-provider/OperationTypes.h>
Expand All @@ -44,6 +46,8 @@ namespace app {

namespace {

using Protocols::InteractionModel::Status;

/// Wraps a EndpointIterator and ensures that `::Release()` is called
/// for the iterator (assuming it is non-null)
class AutoReleaseGroupEndpointIterator
Expand Down Expand Up @@ -754,23 +758,90 @@ void WriteHandler::MoveToState(const State aTargetState)
ChipLogDetail(DataManagement, "IM WH moving to [%s]", GetStateStr());
}

DataModel::ActionReturnStatus WriteHandler::CheckWriteAllowed(const Access::SubjectDescriptor & aSubject,
const ConcreteDataAttributePath & aPath)
{
// TODO: ordering is to check writability/existence BEFORE ACL and this seems wrong, however
// existing unit tests (TC_AcessChecker.py) validate that we get UnsupportedWrite instead of UnsupportedAccess
//
// This should likely be fixed in spec (probably already fixed by
// https://github.com/CHIP-Specifications/connectedhomeip-spec/pull/9024)
// and tests and implementation
//
// Open issue that needs fixing: https://github.com/project-chip/connectedhomeip/issues/33735
std::optional<DataModel::AttributeEntry> attributeEntry;
DataModel::AttributeFinder finder(mDataModelProvider);

attributeEntry = finder.Find(aPath);

// if path is not valid, return a spec-compliant return code.
if (!attributeEntry.has_value())
{
return DataModel::ValidateClusterPath(mDataModelProvider, aPath, Status::UnsupportedAttribute);
}

// Allow writes on writable attributes only
VerifyOrReturnValue(attributeEntry->writePrivilege.has_value(), Status::UnsupportedWrite);

bool checkAcl = true;
if (mLastSuccessfullyWrittenPath.has_value())
{
// NOTE: explicit cast/check only for attribute path and nothing else.
//
// In particular `request.path` is a DATA path (contains a list index)
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
// and we do not want mLastSuccessfullyWrittenPath to be auto-cast to a
// data path with a empty list and fail the compare.
if ((aPath.mEndpointId == mLastSuccessfullyWrittenPath->mEndpointId) &&
(aPath.mClusterId == mLastSuccessfullyWrittenPath->mClusterId) &&
(aPath.mAttributeId == mLastSuccessfullyWrittenPath->mAttributeId))
{
checkAcl = false;
}
}

if (checkAcl)
{
Access::RequestPath requestPath{ .cluster = aPath.mClusterId,
.endpoint = aPath.mEndpointId,
.requestType = Access::RequestType::kAttributeWriteRequest,
.entityId = aPath.mAttributeId };
CHIP_ERROR err = Access::GetAccessControl().Check(aSubject, requestPath, RequiredPrivilege::ForWriteAttribute(aPath));

if (err != CHIP_NO_ERROR)
{
VerifyOrReturnValue(err != CHIP_ERROR_ACCESS_DENIED, Status::UnsupportedAccess);
VerifyOrReturnValue(err != CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL, Status::AccessRestricted);

return err;
}
}

// validate that timed write is enforced
VerifyOrReturnValue(IsTimedWrite() || !attributeEntry->flags.Has(DataModel::AttributeQualityFlags::kTimed),
Status::NeedsTimedInteraction);

return Status::Success;
}

CHIP_ERROR WriteHandler::WriteClusterData(const Access::SubjectDescriptor & aSubject, const ConcreteDataAttributePath & aPath,
TLV::TLVReader & aData)
{
// Writes do not have a checked-path. If data model interface is enabled (both checked and only version)
// the write is done via the DataModel interface
VerifyOrReturnError(mDataModelProvider != nullptr, CHIP_ERROR_INCORRECT_STATE);

DataModel::WriteAttributeRequest request;

request.path = aPath;
request.subjectDescriptor = &aSubject;
request.previousSuccessPath = mLastSuccessfullyWrittenPath;
request.writeFlags.Set(DataModel::WriteFlags::kTimed, IsTimedWrite());
DataModel::ActionReturnStatus status = CheckWriteAllowed(aSubject, aPath);
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
if (status.IsSuccess())
{
DataModel::WriteAttributeRequest request;

AttributeValueDecoder decoder(aData, aSubject);
request.path = aPath;
request.subjectDescriptor = &aSubject;
request.writeFlags.Set(DataModel::WriteFlags::kTimed, IsTimedWrite());
andy31415 marked this conversation as resolved.
Show resolved Hide resolved

DataModel::ActionReturnStatus status = mDataModelProvider->WriteAttribute(request, decoder);
AttributeValueDecoder decoder(aData, aSubject);
status = mDataModelProvider->WriteAttribute(request, decoder);
}

mLastSuccessfullyWrittenPath = status.IsSuccess() ? std::make_optional(aPath) : std::nullopt;

Expand Down
9 changes: 9 additions & 0 deletions src/app/WriteHandler.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <app/ConcreteAttributePath.h>
#include <app/InteractionModelDelegatePointers.h>
#include <app/MessageDef/WriteResponseMessage.h>
#include <app/data-model-provider/ActionReturnStatus.h>
#include <app/data-model-provider/Provider.h>
#include <lib/core/CHIPCore.h>
#include <lib/core/TLVDebug.h>
Expand Down Expand Up @@ -185,6 +186,14 @@ class WriteHandler : public Messaging::ExchangeDelegate
System::PacketBufferHandle && aPayload) override;
void OnResponseTimeout(Messaging::ExchangeContext * apExchangeContext) override;

/// Validate that a write is acceptable on the given path.
///
/// Validates that ACL, writability and Timed interaction settings are ok.
///
/// Returns a success status if all is ok, failure otherwise.
DataModel::ActionReturnStatus CheckWriteAllowed(const Access::SubjectDescriptor & aSubject,
const ConcreteDataAttributePath & aPath);

// Write the given data to the given path
CHIP_ERROR WriteClusterData(const Access::SubjectDescriptor & aSubject, const ConcreteDataAttributePath & aPath,
TLV::TLVReader & aData);
Expand Down
25 changes: 15 additions & 10 deletions src/app/data-model-provider/MetadataLookup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ namespace chip {
namespace app {
namespace DataModel {

using Protocols::InteractionModel::Status;

std::optional<ServerClusterEntry> ServerClusterFinder::Find(const ConcreteClusterPath & path)
{
VerifyOrReturnValue(mProvider != nullptr, std::nullopt);
Expand Down Expand Up @@ -63,23 +65,26 @@ std::optional<AttributeEntry> AttributeFinder::Find(const ConcreteAttributePath
return std::nullopt;
}

EndpointFinder::EndpointFinder(ProviderMetadataTree * provider) : mProvider(provider)
Protocols::InteractionModel::Status ValidateClusterPath(ProviderMetadataTree * provider, const ConcreteClusterPath & path,
Protocols::InteractionModel::Status successStatus)
{
VerifyOrReturn(mProvider != nullptr);
mEndpoints = mProvider->EndpointsIgnoreError();
}
if (ServerClusterFinder(provider).Find(path).has_value())
{
return successStatus;
}

std::optional<EndpointEntry> EndpointFinder::Find(EndpointId endpointId)
{
for (auto & endpointEntry : mEndpoints)
// if we get here, the path is invalid.
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
auto endpoints = provider->EndpointsIgnoreError();
for (auto & endpointEntry : endpoints)
{
if (endpointEntry.id == endpointId)
if (endpointEntry.id == path.mEndpointId)
{
return endpointEntry;
// endpoint is valid
return Protocols::InteractionModel::Status::UnsupportedCluster;
}
}

return std::nullopt;
return Protocols::InteractionModel::Status::UnsupportedEndpoint;
}

} // namespace DataModel
Expand Down
21 changes: 8 additions & 13 deletions src/app/data-model-provider/MetadataLookup.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <app/data-model-provider/ProviderMetadataTree.h>
#include <lib/core/DataModelTypes.h>
#include <lib/support/CodeUtils.h>
#include <protocols/interaction_model/StatusCode.h>

#include <optional>

Expand Down Expand Up @@ -65,20 +66,14 @@ class AttributeFinder
ReadOnlyBuffer<AttributeEntry> mAttributes;
};

/// Helps search for a specific server endpoint in the given
/// metadata provider.
/// Validates that `path` exists within the given provider
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
///
/// Facilitates the operation of "find an endpoint with a given ID".
class EndpointFinder
{
public:
EndpointFinder(ProviderMetadataTree * provider);
std::optional<EndpointEntry> Find(EndpointId endpointId);

private:
ProviderMetadataTree * mProvider;
ReadOnlyBuffer<EndpointEntry> mEndpoints;
};
/// If `endpointID` is not valid, will return Status::UnsupportedEndpoint
/// If `clusterId` is not valid, will return Status::UnsupportedCluster
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
///
/// otherwise, it will return successStatus.
Protocols::InteractionModel::Status ValidateClusterPath(ProviderMetadataTree * provider, const ConcreteClusterPath & path,
Protocols::InteractionModel::Status successStatus);

} // namespace DataModel
} // namespace app
Expand Down
11 changes: 0 additions & 11 deletions src/app/data-model-provider/OperationTypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -88,17 +88,6 @@ struct WriteAttributeRequest : OperationRequest
{
ConcreteDataAttributePath path; // NOTE: this also contains LIST operation options (i.e. "data" path type)
BitFlags<WriteFlags> writeFlags;

// The path of the previous successful write in the same write transaction, if any.
//
// In particular this means that a write to this path has succeeded before (i.e. it passed required ACL checks).
// The intent for this is to allow short-cutting ACL checks when ACL is in progress of being updated:
// - During write chunking, list writes can be of the form "reset list" followed by "append item by item"
// - When ACL is updating, a reset to empty would result in the entire ACL being deny and the "append"
// would fail.
// callers are expected to keep track of a `previousSuccessPath` whenever a write succeeds (otherwise ACL
// checks may fail)
std::optional<ConcreteAttributePath> previousSuccessPath;
};

enum class InvokeFlags : uint32_t
Expand Down
7 changes: 1 addition & 6 deletions src/app/data-model-provider/Provider.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,7 @@ class Provider : public ProviderMetadataTree
///
/// When this is invoked, caller is expected to have already done some validations:
/// - cluster `data version` has been checked for the incoming request if applicable
///
/// TEMPORARY/TRANSITIONAL requirement for transitioning from ember-specific code
/// WriteAttribute is REQUIRED to perform:
/// - ACL validation (see notes on OperationFlags::kInternal)
/// - Validation of readability/writability (also controlled by OperationFlags::kInternal)
/// - Validation of timed interaction required (also controlled by OperationFlags::kInternal)
/// - validation of ACL/timed interaction flags/writability
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
virtual ActionReturnStatus WriteAttribute(const WriteAttributeRequest & request, AttributeValueDecoder & decoder) = 0;

/// `handler` is used to send back the reply.
Expand Down
6 changes: 0 additions & 6 deletions src/app/data-model-provider/tests/WriteTesting.h
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,6 @@ class WriteOperation
return *this;
}

WriteOperation & SetPreviousSuccessPath(std::optional<ConcreteAttributePath> path)
{
mRequest.previousSuccessPath = path;
return *this;
}

WriteOperation & SetDataVersion(Optional<DataVersion> version)
{
mRequest.path.mDataVersion = version;
Expand Down
18 changes: 3 additions & 15 deletions src/app/reporting/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,6 @@ namespace {

using Protocols::InteractionModel::Status;

Status EventPathValid(DataModel::Provider * model, const ConcreteEventPath & eventPath)
{
{
DataModel::ServerClusterFinder serverClusterFinder(model);
if (serverClusterFinder.Find(eventPath).has_value())
{
return Status::Success;
}
}

DataModel::EndpointFinder endpointFinder(model);
return endpointFinder.Find(eventPath.mEndpointId).has_value() ? Status::UnsupportedCluster : Status::UnsupportedEndpoint;
}

/// Returns the status of ACL validation.
/// If the return value has a status set, that means the ACL check failed,
/// the read must not be performed, and the returned status (which may
Expand Down Expand Up @@ -517,7 +503,9 @@ CHIP_ERROR Engine::CheckAccessDeniedEventPaths(TLV::TLVWriter & aWriter, bool &
}

ConcreteEventPath path(current->mValue.mEndpointId, current->mValue.mClusterId, current->mValue.mEventId);
Status status = EventPathValid(mpImEngine->GetDataModelProvider(), path);

// A event path is valid only if the cluster is valid
Status status = DataModel::ValidateClusterPath(mpImEngine->GetDataModelProvider(), path, Status::Success);

if (status != Status::Success)
{
Expand Down
Loading
Loading