diff --git a/.vscode/launch.json b/.vscode/launch.json index afe60953d9f1bd..bd196941ce60d1 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,8 +10,7 @@ "request": "launch", "expressions": "native", "sourceMap": { - "${workspaceFolder}/examples/all-clusters-app/": "${workspaceFolder}/examples/all-clusters-app/", - "${workspaceFolder}/examples/all-clusters-app/linux/third_party/connectedhomeip/": "${workspaceFolder}/" + "${workspaceFolder}/examples/all-clusters-app/linux/third_party/connectedhomeip": "${workspaceFolder}" }, "relativePathBase": "${workspaceFolder}", "breakpointMode": "path", @@ -21,20 +20,6 @@ "program": "${workspaceFolder}/out/linux-x64-all-clusters-no-ble-no-wifi/chip-all-clusters-app", "args": ["--KVS=/tmp/kvs.bin", "--trace_decode=1"], "cwd": "${workspaceFolder}/out/linux-x64-all-clusters-no-ble-no-wifi", - "env": { - "_PW_ACTUAL_ENVIRONMENT_ROOT": "${workspaceFolder}/.environment", - "_PW_ENVIRONMENT_CONFIG_FILE": "${workspaceFolder}/scripts/setup/environment.json", - "_PW_ROSETTA": "0", - "PW_ARM_CIPD_INSTALL_DIR": "${workspaceFolder}/.environment/cipd/packages/arm", - "PW_BRANDING_BANNER": "${workspaceFolder}/scripts/setup/banner.txt", - "PW_PACKAGE_ROOT": "${workspaceFolder}/.environment/packages", - "PW_PIGWEED_CIPD_INSTALL_DIR": "${workspaceFolder}/.environment/cipd/packages/pigweed", - "PW_PROJECT_ROOT": "${workspaceFolder}", - "PW_PYTHON_CIPD_INSTALL_DIR": "${workspaceFolder}/.environment/cipd/packages/python", - "PW_ROOT": "${workspaceFolder}/third_party/pigweed/repo", - "PW_ZAP_CIPD_INSTALL_DIR": "${workspaceFolder}/.environment/cipd/packages/zap", - "PATH": "${workspaceFolder}/third_party/pigweed/repo/out/host/host_tools:${workspaceFolder}/.environment/pigweed-venv/bin:${workspaceFolder}/.environment/cipd/packages/arm/bin:${workspaceFolder}/.environment/cipd/packages/arm:${workspaceFolder}/.environment/cipd/packages/zap:${workspaceFolder}/.environment/cipd/packages/pigweed/bin:${workspaceFolder}/.environment/cipd/packages/pigweed:${workspaceFolder}/.environment/cip:${containerEnv:PATH}" - }, "stdio": [null, null, null], "terminal": "integrated", "stopOnEntry": true @@ -69,6 +54,24 @@ "terminal": "console", "stopOnEntry": false }, + { + "name": "LLDB Debugger: Unit Test", + "type": "lldb", // [vadimcn/codelldb](https://github.com/vadimcn/codelldb) + "request": "launch", + "expressions": "native", + "sourceMap": {}, + "relativePathBase": "${workspaceFolder}", + "breakpointMode": "path", + "sourceLanguages": ["cpp"], + "reverseDebugging": true, + "program": "/workspace/connectedhomeip/out/unified/linux_x64_clang/tests/TestDefaultTermsAndConditionsProvider", + "args": [], + "cwd": "/workspace/connectedhomeip/out/unified", + "env": {}, + "stdio": [null, null, null], + "terminal": "console", + "stopOnEntry": false + }, { "name": "Attach to running process", "type": "lldb", diff --git a/config/standalone/CHIPProjectConfig.h b/config/standalone/CHIPProjectConfig.h index 27abcbb247b322..c27b6c49f1d083 100644 --- a/config/standalone/CHIPProjectConfig.h +++ b/config/standalone/CHIPProjectConfig.h @@ -74,6 +74,31 @@ #define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" #endif +/** + * @brief Configures the required terms and conditions acknowledgements. + * + * This macro defines the required terms and conditions acknowledgements bitmask. The bit-field is 16 bits long, so the possible + * value range is [0, 65535). This setting can be used to require that terms and conditions are presented to the user during + * commissioning. + */ +#ifndef CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS +#define CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS 0 +#endif + +/** + * @brief Configures the latest known version of the terms and conditions. + * + * This macro defines the version number of the latest terms and conditions. It allows the application to iterate on revisions of + * the terms and conditions. A value of 0 indicates that no specific version is required. This setting can be used to enforce + * version-specific terms and conditions acknowledgements in the application. When the set of terms and conditions needs to be + * changes, the version number should be monotomically increased. If the lateast terms and conditions version is updated (most + * likely during an OTA) then this may signal to the Administrator that updated terms and conditions should be presented to the + * user. + */ +#ifndef CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION +#define CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION 0 +#endif + // // Default of 8 ECs is not sufficient for some of the unit tests // that try to validate multiple simultaneous interactions. diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap b/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap index aec4d4601390e4..167aeaf983037b 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap @@ -2171,6 +2171,22 @@ "source": "server", "isIncoming": 0, "isEnabled": 1 + }, + { + "name": "SetTCAcknowledgements", + "code": 6, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "SetTCAcknowledgementsResponse", + "code": 7, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 } ], "attributes": [ @@ -2254,6 +2270,70 @@ "maxInterval": 65534, "reportableChange": 0 }, + { + "name": "TCAcceptedVersion", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TCMinRequiredVersion", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TCAcknowledgements", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "bitmap16", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0000", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TCAcknowledgementsRequired", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "true", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, { "name": "GeneratedCommandList", "code": 65528, @@ -2328,7 +2408,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "1", "reportable": 1, "minInterval": 1, "maxInterval": 65534, diff --git a/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h b/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h index 440ba53f4ee3ba..18894eeeb327cd 100644 --- a/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h +++ b/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2022-2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -27,6 +27,12 @@ #pragma once +// Require that terms and conditions ordinal 1 must be accepted. +#define CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS 1 + +// The current terms and conditions revision is 1. +#define CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION 1 + // include the CHIPProjectConfig from config/standalone #include diff --git a/examples/chip-tool/BUILD.gn b/examples/chip-tool/BUILD.gn index 10d03c02ee295d..40b1a308bb068a 100644 --- a/examples/chip-tool/BUILD.gn +++ b/examples/chip-tool/BUILD.gn @@ -105,7 +105,6 @@ static_library("chip-tool-utils") { "${chip_root}/examples/common/tracing:commandline", "${chip_root}/src/app/icd/client:handler", "${chip_root}/src/app/icd/client:manager", - "${chip_root}/src/app/server", "${chip_root}/src/app/tests/suites/commands/interaction_model", "${chip_root}/src/controller/data_model", "${chip_root}/src/credentials:file_attestation_trust_store", diff --git a/examples/chip-tool/commands/pairing/PairingCommand.cpp b/examples/chip-tool/commands/pairing/PairingCommand.cpp index ed80bc007df796..b673507bb1de07 100644 --- a/examples/chip-tool/commands/pairing/PairingCommand.cpp +++ b/examples/chip-tool/commands/pairing/PairingCommand.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -118,6 +118,17 @@ CommissioningParameters PairingCommand::GetCommissioningParameters() params.SetCountryCode(CharSpan::fromCharString(mCountryCode.Value())); } + // mTCAcknowledgements and mTCAcknowledgementVersion are optional, but related. When one is missing, default the value to 0, to + // increase the test tools ability to test the applications. + if (mTCAcknowledgements.HasValue() || mTCAcknowledgementVersion.HasValue()) + { + TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement = { + .acceptedTermsAndConditions = mTCAcknowledgements.ValueOr(0), + .acceptedTermsAndConditionsVersion = mTCAcknowledgementVersion.ValueOr(0), + }; + params.SetTermsAndConditionsAcknowledgement(termsAndConditionsAcknowledgement); + } + // mTimeZoneList is an optional argument managed by TypedComplexArgument mComplex_TimeZones. // Since optional Complex arguments are not currently supported via the class, // we will use mTimeZoneList.data() value to determine if the argument was provided. diff --git a/examples/chip-tool/commands/pairing/PairingCommand.h b/examples/chip-tool/commands/pairing/PairingCommand.h index 0baf70128531b8..467bd9b30c3f57 100644 --- a/examples/chip-tool/commands/pairing/PairingCommand.h +++ b/examples/chip-tool/commands/pairing/PairingCommand.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -182,6 +182,14 @@ class PairingCommand : public CHIPCommand, AddArgument("dst-offset", &mComplex_DSTOffsets, "DSTOffset list to use when setting Time Synchronization cluster's DSTOffset attribute", Argument::kOptional); + + AddArgument("tc-acknowledgements", 0, UINT16_MAX, &mTCAcknowledgements, + "Terms and Conditions acknowledgements to use to set the General Commissioning cluster's TC " + "Acknowledgements bit-field"); + + AddArgument("tc-acknowledgements-version", 0, UINT16_MAX, &mTCAcknowledgementVersion, + "Terms and Conditions acknowledgement version to use to set the General Commissioning cluster's TC " + "Acknowledgement version"); } AddArgument("timeout", 0, UINT16_MAX, &mTimeout); @@ -233,6 +241,8 @@ class PairingCommand : public CHIPCommand, chip::Optional mBypassAttestationVerifier; chip::Optional> mCASEAuthTags; chip::Optional mCountryCode; + chip::Optional mTCAcknowledgements; + chip::Optional mTCAcknowledgementVersion; chip::Optional mSkipICDRegistration; chip::Optional mICDCheckInNodeId; chip::Optional mICDSymmetricKey; diff --git a/src/app/BUILD.gn b/src/app/BUILD.gn index 4cf96b3a1a84c8..30de9a85c368ad 100644 --- a/src/app/BUILD.gn +++ b/src/app/BUILD.gn @@ -214,6 +214,7 @@ static_library("interaction-model") { "${chip_root}/src/lib/address_resolve", "${chip_root}/src/lib/support", "${chip_root}/src/lib/support:static-support", + "${chip_root}/src/messaging:messaging", "${chip_root}/src/protocols/interaction_model", "${chip_root}/src/protocols/secure_channel", "${chip_root}/src/system", diff --git a/src/app/clusters/general-commissioning-server/general-commissioning-server.cpp b/src/app/clusters/general-commissioning-server/general-commissioning-server.cpp index 536ac205454862..8932c56822ac8c 100644 --- a/src/app/clusters/general-commissioning-server/general-commissioning-server.cpp +++ b/src/app/clusters/general-commissioning-server/general-commissioning-server.cpp @@ -1,6 +1,6 @@ /** * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2021-2024 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -95,9 +96,32 @@ CHIP_ERROR GeneralCommissioningAttrAccess::Read(const ConcreteReadAttributePath case SupportsConcurrentConnection::Id: { return ReadSupportsConcurrentConnection(aEncoder); } - default: { - break; + case TCAcceptedVersion::Id: { + uint16_t tcAcceptedVersion; + const EnhancedSetupFlowProvider * const enhancedSetupFlowProvider = Server::GetInstance().GetEnhancedSetupFlowProvider(); + CHIP_ERROR err = enhancedSetupFlowProvider->GetTermsAndConditionsAcceptedAcknowledgementsVersion(tcAcceptedVersion); + return (CHIP_NO_ERROR != err) ? err : aEncoder.Encode(tcAcceptedVersion); + } + case TCMinRequiredVersion::Id: { + uint16_t tcRequiredVersion; + const EnhancedSetupFlowProvider * const enhancedSetupFlowProvider = Server::GetInstance().GetEnhancedSetupFlowProvider(); + CHIP_ERROR err = enhancedSetupFlowProvider->GetTermsAndConditionsRequiredAcknowledgementsVersion(tcRequiredVersion); + return (CHIP_NO_ERROR != err) ? err : aEncoder.Encode(tcRequiredVersion); } + case TCAcknowledgements::Id: { + uint16_t tcAcknowledgements; + const EnhancedSetupFlowProvider * const enhancedSetupFlowProvider = Server::GetInstance().GetEnhancedSetupFlowProvider(); + CHIP_ERROR err = enhancedSetupFlowProvider->GetTermsAndConditionsAcceptedAcknowledgements(tcAcknowledgements); + return (CHIP_NO_ERROR != err) ? err : aEncoder.Encode(tcAcknowledgements); + } + case TCAcknowledgementsRequired::Id: { + uint16_t tcAcknowledgementsRequired; + const EnhancedSetupFlowProvider * const enhancedSetupFlowProvider = Server::GetInstance().GetEnhancedSetupFlowProvider(); + CHIP_ERROR err = enhancedSetupFlowProvider->GetTermsAndConditionsRequiredAcknowledgements(tcAcknowledgementsRequired); + return (CHIP_NO_ERROR != err) ? err : aEncoder.Encode(tcAcknowledgementsRequired); + } + default: + break; } return CHIP_NO_ERROR; } @@ -214,9 +238,10 @@ bool emberAfGeneralCommissioningClusterCommissioningCompleteCallback( { MATTER_TRACE_SCOPE("CommissioningComplete", "GeneralCommissioning"); - DeviceControlServer * devCtrl = &DeviceLayer::DeviceControlServer::DeviceControlSvr(); - auto & failSafe = Server::GetInstance().GetFailSafeContext(); - auto & fabricTable = Server::GetInstance().GetFabricTable(); + const EnhancedSetupFlowProvider * const enhancedSetupFlowProvider = Server::GetInstance().GetEnhancedSetupFlowProvider(); + DeviceControlServer * const devCtrl = &DeviceLayer::DeviceControlServer::DeviceControlSvr(); + auto & failSafe = Server::GetInstance().GetFailSafeContext(); + auto & fabricTable = Server::GetInstance().GetFabricTable(); ChipLogProgress(FailSafe, "GeneralCommissioning: Received CommissioningComplete"); @@ -239,34 +264,50 @@ bool emberAfGeneralCommissioningClusterCommissioningCompleteCallback( } else { - if (failSafe.NocCommandHasBeenInvoked()) + CHIP_ERROR err; + bool hasTermsAndConditionsRequiredAcknowledgementsBeenAccepted; + bool hasTermsAndConditionsRequiredAcknowledgementsVersionBeenAccepted; + + enhancedSetupFlowProvider->HasTermsAndConditionsRequiredAcknowledgementsBeenAccepted( + hasTermsAndConditionsRequiredAcknowledgementsBeenAccepted); + enhancedSetupFlowProvider->HasTermsAndConditionsRequiredAcknowledgementsVersionBeenAccepted( + hasTermsAndConditionsRequiredAcknowledgementsVersionBeenAccepted); + + if (!hasTermsAndConditionsRequiredAcknowledgementsBeenAccepted) { - CHIP_ERROR err = fabricTable.CommitPendingFabricData(); - if (err != CHIP_NO_ERROR) - { - // No need to revert on error: CommitPendingFabricData always reverts if not fully successful. - ChipLogError(FailSafe, "GeneralCommissioning: Failed to commit pending fabric data: %" CHIP_ERROR_FORMAT, - err.Format()); - } - else + ChipLogError(AppServer, "Required terms and conditions have not been accepted"); + Breadcrumb::Set(commandPath.mEndpointId, 0); + response.errorCode = CommissioningErrorEnum::kRequiredTCNotAccepted; + } + + else if (!hasTermsAndConditionsRequiredAcknowledgementsVersionBeenAccepted) + { + ChipLogError(AppServer, "Minimum terms and conditions version has not been accepted"); + Breadcrumb::Set(commandPath.mEndpointId, 0); + response.errorCode = CommissioningErrorEnum::kTCMinVersionNotMet; + } + + else + { + if (failSafe.NocCommandHasBeenInvoked()) { + err = fabricTable.CommitPendingFabricData(); + CheckSuccess(err, Failure); ChipLogProgress(FailSafe, "GeneralCommissioning: Successfully commited pending fabric data"); } - CheckSuccess(err, Failure); - } - /* - * Pass fabric of commissioner to DeviceControlSvr. - * This allows device to send messages back to commissioner. - * Once bindings are implemented, this may no longer be needed. - */ - failSafe.DisarmFailSafe(); - CheckSuccess( - devCtrl->PostCommissioningCompleteEvent(handle->AsSecureSession()->GetPeerNodeId(), handle->GetFabricIndex()), - Failure); + /* + * Pass fabric of commissioner to DeviceControlSvr. + * This allows device to send messages back to commissioner. + * Once bindings are implemented, this may no longer be needed. + */ + failSafe.DisarmFailSafe(); + err = devCtrl->PostCommissioningCompleteEvent(handle->AsSecureSession()->GetPeerNodeId(), handle->GetFabricIndex()); + CheckSuccess(err, Failure); - Breadcrumb::Set(commandPath.mEndpointId, 0); - response.errorCode = CommissioningErrorEnum::kOk; + Breadcrumb::Set(commandPath.mEndpointId, 0); + response.errorCode = CommissioningErrorEnum::kOk; + } } } @@ -328,13 +369,35 @@ bool emberAfGeneralCommissioningClusterSetRegulatoryConfigCallback(app::CommandH return true; } +bool emberAfGeneralCommissioningClusterSetTCAcknowledgementsCallback( + chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, + const chip::app::Clusters::GeneralCommissioning::Commands::SetTCAcknowledgements::DecodableType & commandData) +{ + MATTER_TRACE_SCOPE("SetTCAcknowledgements", "GeneralCommissioning"); + Commands::SetTCAcknowledgementsResponse::Type response; + EnhancedSetupFlowProvider * const enhancedSetupFlowProvider = Server::GetInstance().GetEnhancedSetupFlowProvider(); + uint16_t acknowledgements = commandData.TCUserResponse; + uint16_t acknowledgementsVersion = commandData.TCVersion; + CheckSuccess(enhancedSetupFlowProvider->SetTermsAndConditionsAcceptance(acknowledgements, acknowledgementsVersion), Failure); + response.errorCode = CommissioningErrorEnum::kOk; + + commandObj->AddResponse(commandPath, response); + return true; +} + namespace { void OnPlatformEventHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg) { - if (event->Type == DeviceLayer::DeviceEventType::kFailSafeTimerExpired) + switch (event->Type) { + case DeviceLayer::DeviceEventType::kFailSafeTimerExpired: { // Spec says to reset Breadcrumb attribute to 0. Breadcrumb::Set(0, 0); + break; + } + default: { + break; + } } } diff --git a/src/app/server/BUILD.gn b/src/app/server/BUILD.gn index 7c661464bbaea3..cd957ed5cbe1f8 100644 --- a/src/app/server/BUILD.gn +++ b/src/app/server/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2020 Project CHIP Authors +# Copyright (c) 2020-2024 Project CHIP Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -24,8 +24,40 @@ config("server_config") { } } -static_library("server") { - output_name = "libCHIPAppServer" +source_set("enhanced-setup-sources") { + sources = [ + "EnhancedSetupFlowProvider.h", + "TermsAndConditionsProvider.h", + ] + + public_deps = [ "${chip_root}/src/lib/core:error" ] +} + +config("enhanced-setup-config") { +} + +static_library("enhanced-setup") { + output_name = "libCHIPAppServerEnhancedSetup" + + sources = [ + "DefaultEnhancedSetupFlowProvider.cpp", + "DefaultEnhancedSetupFlowProvider.h", + "DefaultTermsAndConditionsProvider.cpp", + "DefaultTermsAndConditionsProvider.h", + ] + + public_configs = [ ":enhanced-setup-config" ] + + cflags = [ "-Wconversion" ] + + public_deps = [ + ":enhanced-setup-sources", + "${chip_root}/src/platform:platform", + ] +} + +static_library("server-core") { + output_name = "libCHIPAppServerCore" sources = [ "AclStorage.cpp", @@ -42,7 +74,6 @@ static_library("server") { "EchoHandler.h", "OnboardingCodesUtil.cpp", "OnboardingCodesUtil.h", - "Server.cpp", "Server.h", ] @@ -51,6 +82,7 @@ static_library("server") { cflags = [ "-Wconversion" ] public_deps = [ + ":enhanced-setup-sources", "${chip_root}/src/app", "${chip_root}/src/app/icd/server:icd-server-config", "${chip_root}/src/app/icd/server:observer", @@ -63,6 +95,22 @@ static_library("server") { "${chip_root}/src/setup_payload", "${chip_root}/src/transport", ] +} + +static_library("server") { + output_name = "libCHIPAppServer" + + sources = [ "Server.cpp" ] + + public_configs = [ ":server_config" ] + + cflags = [ "-Wconversion" ] + + public_deps = [ + ":enhanced-setup", + ":enhanced-setup-sources", + ":server-core", + ] # TODO: Server.cpp uses TestGroupData.h. Unsure why test code would be in such a central place # This dependency is split since it should probably be removed (or naming should diff --git a/src/app/server/DefaultEnhancedSetupFlowProvider.cpp b/src/app/server/DefaultEnhancedSetupFlowProvider.cpp new file mode 100644 index 00000000000000..0b7a9fe34dcc04 --- /dev/null +++ b/src/app/server/DefaultEnhancedSetupFlowProvider.cpp @@ -0,0 +1,115 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#include "DefaultEnhancedSetupFlowProvider.h" + +#include +#include + +CHIP_ERROR chip::app::DefaultEnhancedSetupFlowProvider::Init(TermsAndConditionsProvider * const inTermsAndConditionsProvider) +{ + mTermsAndConditionsProvider = inTermsAndConditionsProvider; + return CHIP_NO_ERROR; +} + +CHIP_ERROR +chip::app::DefaultEnhancedSetupFlowProvider::HasTermsAndConditionsRequiredAcknowledgementsBeenAccepted(bool & outAccepted) const +{ + uint16_t requiredAcknowledgements; + uint16_t requiredAcknowledgementsVersion; + uint16_t acceptedAcknowledgements; + uint16_t acceptedAcknowledgementsVersion; + + mTermsAndConditionsProvider->GetRequirements(requiredAcknowledgements, requiredAcknowledgementsVersion); + mTermsAndConditionsProvider->GetAcceptance(acceptedAcknowledgements, acceptedAcknowledgementsVersion); + + outAccepted = ((requiredAcknowledgements & acceptedAcknowledgements) == requiredAcknowledgements); + return CHIP_NO_ERROR; +} + +CHIP_ERROR chip::app::DefaultEnhancedSetupFlowProvider::HasTermsAndConditionsRequiredAcknowledgementsVersionBeenAccepted( + bool & outAccepted) const +{ + uint16_t requiredAcknowledgements; + uint16_t requiredAcknowledgementsVersion; + uint16_t acceptedAcknowledgements; + uint16_t acceptedAcknowledgementsVersion; + + mTermsAndConditionsProvider->GetRequirements(requiredAcknowledgements, requiredAcknowledgementsVersion); + mTermsAndConditionsProvider->GetAcceptance(acceptedAcknowledgements, acceptedAcknowledgementsVersion); + + outAccepted = (acceptedAcknowledgementsVersion >= requiredAcknowledgementsVersion); + return CHIP_NO_ERROR; +} + +CHIP_ERROR chip::app::DefaultEnhancedSetupFlowProvider::GetTermsAndConditionsRequiredAcknowledgements(uint16_t & outValue) const +{ + uint16_t requiredAcknowledgements; + uint16_t requiredAcknowledgementsVersion; + + mTermsAndConditionsProvider->GetRequirements(requiredAcknowledgements, requiredAcknowledgementsVersion); + + outValue = requiredAcknowledgements; + return CHIP_NO_ERROR; +} + +CHIP_ERROR +chip::app::DefaultEnhancedSetupFlowProvider::GetTermsAndConditionsRequiredAcknowledgementsVersion(uint16_t & outValue) const +{ + uint16_t requiredAcknowledgements; + uint16_t requiredAcknowledgementsVersion; + + mTermsAndConditionsProvider->GetRequirements(requiredAcknowledgements, requiredAcknowledgementsVersion); + + outValue = requiredAcknowledgementsVersion; + return CHIP_NO_ERROR; +} + +CHIP_ERROR chip::app::DefaultEnhancedSetupFlowProvider::GetTermsAndConditionsAcceptedAcknowledgements(uint16_t & outValue) const +{ + uint16_t acceptedAcknowledgements; + uint16_t acceptedAcknowledgementsVersion; + + mTermsAndConditionsProvider->GetAcceptance(acceptedAcknowledgements, acceptedAcknowledgementsVersion); + + outValue = acceptedAcknowledgements; + return CHIP_NO_ERROR; +} + +CHIP_ERROR +chip::app::DefaultEnhancedSetupFlowProvider::GetTermsAndConditionsAcceptedAcknowledgementsVersion(uint16_t & outValue) const +{ + uint16_t acceptedAcknowledgements; + uint16_t acceptedAcknowledgementsVersion; + + mTermsAndConditionsProvider->GetAcceptance(acceptedAcknowledgements, acceptedAcknowledgementsVersion); + + outValue = acceptedAcknowledgementsVersion; + return CHIP_NO_ERROR; +} + +CHIP_ERROR chip::app::DefaultEnhancedSetupFlowProvider::SetTermsAndConditionsAcceptance(uint16_t inTCAcknowledgementsValue, + uint16_t inTCAcknowledgementsVersionValue) +{ + return mTermsAndConditionsProvider->SetAcceptance(inTCAcknowledgementsValue, inTCAcknowledgementsVersionValue); +} + +CHIP_ERROR chip::app::DefaultEnhancedSetupFlowProvider::ClearTermsAndConditionsAcceptance() +{ + return mTermsAndConditionsProvider->ClearAcceptance(); +} diff --git a/src/app/server/DefaultEnhancedSetupFlowProvider.h b/src/app/server/DefaultEnhancedSetupFlowProvider.h new file mode 100644 index 00000000000000..eb9d145d6221d4 --- /dev/null +++ b/src/app/server/DefaultEnhancedSetupFlowProvider.h @@ -0,0 +1,87 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#pragma once + +#include "EnhancedSetupFlowProvider.h" + +#include + +#include + +#include "TermsAndConditionsProvider.h" + +namespace chip { +namespace app { +class DefaultEnhancedSetupFlowProvider : public EnhancedSetupFlowProvider +{ +public: + /** + * @brief Initializes the EnhancedSetupFlowProvider. + * + * @param[in] inTermsAndConditionsProvider The terms and conditions provide dependency. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + CHIP_ERROR Init(TermsAndConditionsProvider * const inTermsAndConditionsProvider); + + /** + * @copydoc EnhancedSetupFlowProvider::HasTermsAndConditionsRequiredAcknowledgementsBeenAccepted + */ + CHIP_ERROR HasTermsAndConditionsRequiredAcknowledgementsBeenAccepted(bool & outAccepted) const override; + + /** + * @copydoc EnhancedSetupFlowProvider::HasTermsAndConditionsRequiredAcknowledgementsVersionBeenAccepted + */ + CHIP_ERROR HasTermsAndConditionsRequiredAcknowledgementsVersionBeenAccepted(bool & outAccepted) const override; + + /** + * @copydoc EnhancedSetupFlowProvider::GetTermsAndConditionsRequiredAcknowledgements + */ + CHIP_ERROR GetTermsAndConditionsRequiredAcknowledgements(uint16_t & outValue) const override; + + /** + * @copydoc EnhancedSetupFlowProvider::GetTermsAndConditionsRequiredAcknowledgementsVersion + */ + CHIP_ERROR GetTermsAndConditionsRequiredAcknowledgementsVersion(uint16_t & outValue) const override; + + /** + * @copydoc EnhancedSetupFlowProvider::GetTermsAndConditionsAcceptedAcknowledgements + */ + CHIP_ERROR GetTermsAndConditionsAcceptedAcknowledgements(uint16_t & outValue) const override; + + /** + * @copydoc EnhancedSetupFlowProvider::GetTermsAndConditionsAcceptedAcknowledgementsVersion + */ + CHIP_ERROR GetTermsAndConditionsAcceptedAcknowledgementsVersion(uint16_t & outValue) const override; + + /** + * @copydoc EnhancedSetupFlowProvider::SetTermsAndConditionsAcceptance + */ + CHIP_ERROR SetTermsAndConditionsAcceptance(uint16_t aTCAcknowledgements, uint16_t aTCAcknowledgementsVersion) override; + + /** + * @copydoc EnhancedSetupFlowProvider::ClearTermsAndConditionsAcceptance + */ + CHIP_ERROR ClearTermsAndConditionsAcceptance() override; + +private: + TermsAndConditionsProvider * mTermsAndConditionsProvider; /**< TermsAndConditionsProvider instance. */ +}; + +}; // namespace app +}; // namespace chip diff --git a/src/app/server/DefaultTermsAndConditionsProvider.cpp b/src/app/server/DefaultTermsAndConditionsProvider.cpp new file mode 100644 index 00000000000000..d85bb361b41ef1 --- /dev/null +++ b/src/app/server/DefaultTermsAndConditionsProvider.cpp @@ -0,0 +1,142 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#include "DefaultTermsAndConditionsProvider.h" + +#include +#include +#include +#include +#include + +enum Tag : uint32_t +{ + kAcceptedAcknowledgements = 1, + kAcceptedAcknowledgementsVersion = 2, +}; + +#ifndef CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS +#error "CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS is not defined!" +#endif + +#ifndef CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION +#error "CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION is not defined!" +#endif + +CHIP_ERROR +chip::app::DefaultTermsAndConditionsProvider::Init(chip::PersistentStorageDelegate * inPersistentStorageDelegate) +{ + mPersistentStorageDelegate = inPersistentStorageDelegate; + return CHIP_NO_ERROR; +} + +CHIP_ERROR chip::app::DefaultTermsAndConditionsProvider::GetAcceptance(uint16_t & outAcknowledgementsValue, + uint16_t & outAcknowledgementsVersionValue) +{ + CHIP_ERROR err; + + chip::TLV::Tag kAcceptedAcknowledgementsTag = chip::TLV::ContextTag(Tag::kAcceptedAcknowledgements); + chip::TLV::Tag kAcceptedAcknowledgementsVersionTag = chip::TLV::ContextTag(Tag::kAcceptedAcknowledgementsVersion); + + uint16_t acknowledgements = 0; + uint16_t acknowledgementsVersion = 0; + + constexpr size_t kSizeOfAcknowledgementsValue = sizeof(uint16_t); + constexpr size_t kSizeOfAcknowledgementsVersionValue = sizeof(uint16_t); + constexpr size_t kEstimatedTLVSize = + chip::TLV::EstimateStructOverhead(kSizeOfAcknowledgementsValue, kSizeOfAcknowledgementsVersionValue); + + uint8_t buffer[kEstimatedTLVSize] = { 0 }; + uint16_t bufferSize = sizeof(buffer); + chip::TLV::TLVReader reader; + + const char * acknowledgementsVersionKey = + DefaultStorageKeyAllocator::TermsAndConditionsAcceptance(CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION).KeyName(); + + mPersistentStorageDelegate->SyncGetKeyValue(acknowledgementsVersionKey, &buffer, bufferSize); + + reader.Init(buffer); + err = reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); + + chip::TLV::TLVType outerContainerType; + err = reader.EnterContainer(outerContainerType); + + while ((err = reader.Next()) == CHIP_NO_ERROR) + { + if (kAcceptedAcknowledgementsTag == reader.GetTag()) + { + reader.Get(acknowledgements); + } + + if (kAcceptedAcknowledgementsVersionTag == reader.GetTag()) + { + reader.Get(acknowledgementsVersion); + } + } + + err = reader.ExitContainer(outerContainerType); + + outAcknowledgementsValue = acknowledgements; + outAcknowledgementsVersionValue = acknowledgementsVersion; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR chip::app::DefaultTermsAndConditionsProvider::GetRequirements(uint16_t & outAcknowledgementsValue, + uint16_t & outAcknowledgementsVersionValue) +{ + outAcknowledgementsValue = CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS; + outAcknowledgementsVersionValue = CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION; + return CHIP_NO_ERROR; +} + +CHIP_ERROR chip::app::DefaultTermsAndConditionsProvider::SetAcceptance(uint16_t inAcceptedAcknowledgementsValue, + uint16_t inAcceptedAcknowledgementsVersionValue) +{ + constexpr size_t kSizeOfAcknowledgementsValue = sizeof(uint16_t); + constexpr size_t kSizeOfAcknowledgementsVersionValue = sizeof(uint16_t); + constexpr size_t kEstimatedTLVSize = + chip::TLV::EstimateStructOverhead(kSizeOfAcknowledgementsValue, kSizeOfAcknowledgementsVersionValue); + uint8_t buffer[kEstimatedTLVSize] = { 0 }; + chip::TLV::TLVWriter tlvWriter; + chip::TLV::TLVType containerType; + + chip::TLV::Tag kAcceptedAcknowledgementsTag = chip::TLV::ContextTag(Tag::kAcceptedAcknowledgements); + chip::TLV::Tag kAcceptedAcknowledgementsVersionTag = chip::TLV::ContextTag(Tag::kAcceptedAcknowledgementsVersion); + + tlvWriter.Init(buffer, sizeof(buffer)); + ReturnErrorOnFailure(tlvWriter.StartContainer(chip::TLV::AnonymousTag(), chip::TLV::kTLVType_Structure, containerType)); + ReturnErrorOnFailure(tlvWriter.Put(kAcceptedAcknowledgementsTag, inAcceptedAcknowledgementsValue)); + ReturnErrorOnFailure(tlvWriter.Put(kAcceptedAcknowledgementsVersionTag, inAcceptedAcknowledgementsVersionValue)); + ReturnErrorOnFailure(tlvWriter.EndContainer(containerType)); + ReturnErrorOnFailure(tlvWriter.Finalize()); + + const char * acknowledgementsVersionKey = + DefaultStorageKeyAllocator::TermsAndConditionsAcceptance(CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION).KeyName(); + mPersistentStorageDelegate->SyncSetKeyValue(acknowledgementsVersionKey, buffer, sizeof(buffer)); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR chip::app::DefaultTermsAndConditionsProvider::ClearAcceptance() +{ + const char * acknowledgementsVersionKey = + DefaultStorageKeyAllocator::TermsAndConditionsAcceptance(CHIP_CONFIG_TC_REQUIRED_ACKNOWLEDGEMENTS_VERSION).KeyName(); + mPersistentStorageDelegate->SyncDeleteKeyValue(acknowledgementsVersionKey); + return CHIP_NO_ERROR; +} diff --git a/src/app/server/DefaultTermsAndConditionsProvider.h b/src/app/server/DefaultTermsAndConditionsProvider.h new file mode 100644 index 00000000000000..e3bd8d422b82da --- /dev/null +++ b/src/app/server/DefaultTermsAndConditionsProvider.h @@ -0,0 +1,66 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#pragma once + +#include "TermsAndConditionsProvider.h" + +#include + +#include +#include + +namespace chip { +namespace app { +class DefaultTermsAndConditionsProvider : public TermsAndConditionsProvider +{ +public: + /** + * @brief Initializes the TermsAndConditionsProvider. + * + * @param[in] inPersistentStorageDelegate Persistent storage delegate dependency. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + CHIP_ERROR Init(chip::PersistentStorageDelegate * inPersistentStorageDelegate); + + /** + * @copydoc TermsAndConditionsProvider::GetAcceptance + */ + CHIP_ERROR GetAcceptance(uint16_t & outAcknowledgementsValue, uint16_t & outAcknowledgementsVersionValue) override; + + /** + * @copydoc TermsAndConditionsProvider::GetRequirements + */ + CHIP_ERROR GetRequirements(uint16_t & outAcknowledgementsValue, uint16_t & outAcknowledgementsVersionValue) override; + + /** + * @copydoc TermsAndConditionsProvider::SetAcceptance + */ + CHIP_ERROR SetAcceptance(uint16_t inAcknowledgementsValue, uint16_t inAcknowledgementsVersionValue) override; + + /** + * @copydoc TermsAndConditionsProvider::ClearAcceptance + */ + CHIP_ERROR ClearAcceptance() override; + +private: + chip::PersistentStorageDelegate * mPersistentStorageDelegate; +}; + +}; // namespace app +}; // namespace chip diff --git a/src/app/server/EnhancedSetupFlowProvider.h b/src/app/server/EnhancedSetupFlowProvider.h new file mode 100644 index 00000000000000..6db950b87e7fa5 --- /dev/null +++ b/src/app/server/EnhancedSetupFlowProvider.h @@ -0,0 +1,108 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#pragma once + +#include + +#include + +namespace chip { +namespace app { + +/** + * @brief Feature state access layer for the EnhancedSetupFlowProvider. + * + * This class provides access to the state of the feature through the TermsAndConditionsProvider. + */ +class EnhancedSetupFlowProvider +{ +public: + /** + * @brief Destructor. + */ + virtual ~EnhancedSetupFlowProvider() = default; + + /** + * @brief Checks if the required terms and conditions acknowledgements have been accepted. + * + * @param[out] outAccepted true if the required acknowledgements have been accepted, false otherwise. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR HasTermsAndConditionsRequiredAcknowledgementsBeenAccepted(bool & outAccepted) const = 0; + + /** + * @brief Checks if the required terms and conditions acknowledgements version has been accepted. + * + * @param[out] outAccepted true if the required acknowledgements version has been accepted, false otherwise. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR HasTermsAndConditionsRequiredAcknowledgementsVersionBeenAccepted(bool & outAccepted) const = 0; + + /** + * @brief Retrieves the required terms and conditions acknowledgements. + * + * @param[out] outValue The version of the required acknowledgements. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR GetTermsAndConditionsRequiredAcknowledgements(uint16_t & outValue) const = 0; + + /** + * @brief Retrieves the required terms and conditions acknowledgements version. + * + * @param[out] outValue The outValue of the required acknowledgements version. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR GetTermsAndConditionsRequiredAcknowledgementsVersion(uint16_t & outValue) const = 0; + + /** + * @brief Retrieves the accepted terms and conditions acknowledgements. + * + * @param[out] outValue The outValue of the accepted acknowledgements. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR GetTermsAndConditionsAcceptedAcknowledgements(uint16_t & outValue) const = 0; + + /** + * @brief Retrieves the accepted terms and conditions acknowledgements version. + * + * @param[out] outValue The outValue of the accepted acknowledgements version. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR GetTermsAndConditionsAcceptedAcknowledgementsVersion(uint16_t & outValue) const = 0; + + /** + * @brief Sets the acceptance status of the terms and conditions. + * + * @param[in] inTCAcknowledgements The acknowledgements to accept. + * @param[in] inTCAcknowledgementsoutValue The version of the acknowledgements to accept. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR SetTermsAndConditionsAcceptance(uint16_t inTCAcknowledgementsValue, + uint16_t inTCAcknowledgementsoutValue) = 0; + + /** + * @brief Clears the acceptance status of the terms and conditions. + * + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR ClearTermsAndConditionsAcceptance() = 0; +}; + +}; // namespace app +}; // namespace chip diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index d2983636450691..14cb938259d9aa 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -21,6 +21,8 @@ #include #include +#include +#include #include #include #include @@ -98,6 +100,97 @@ static ::chip::PersistedCounter sGlobalEventIdCounter; static ::chip::app::CircularEventBuffer sLoggingBuffer[CHIP_NUM_EVENT_LOGGING_BUFFERS]; #endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT +app::DefaultEnhancedSetupFlowProvider sDefaultEnhancedSetupFlowProviderInstance; +app::EnhancedSetupFlowProvider * CommonCaseDeviceServerInitParams::sDefaultEnhancedSetupFlowProvider = + &sDefaultEnhancedSetupFlowProviderInstance; + +app::DefaultTermsAndConditionsProvider sDefaultTermsAndConditionsProviderInstance; +app::TermsAndConditionsProvider * CommonCaseDeviceServerInitParams::sDefaultTermsAndConditionsProvider = + &sDefaultTermsAndConditionsProviderInstance; + +CHIP_ERROR CommonCaseDeviceServerInitParams::InitializeStaticResourcesBeforeServerInit() +{ + chip::DeviceLayer::PersistedStorage::KeyValueStoreManager & kvsManager = DeviceLayer::PersistedStorage::KeyValueStoreMgr(); + + // KVS-based persistent storage delegate injection + if (persistentStorageDelegate == nullptr) + { + ReturnErrorOnFailure(sKvsPersistenStorageDelegate.Init(&kvsManager)); + this->persistentStorageDelegate = &sKvsPersistenStorageDelegate; + } + + // PersistentStorageDelegate "software-based" operational key access injection + if (this->operationalKeystore == nullptr) + { + // WARNING: PersistentStorageOperationalKeystore::Finish() is never called. It's fine for + // for examples and for now. + ReturnErrorOnFailure(sPersistentStorageOperationalKeystore.Init(this->persistentStorageDelegate)); + this->operationalKeystore = &sPersistentStorageOperationalKeystore; + } + + // OpCertStore can be injected but default to persistent storage default + // for simplicity of the examples. + if (this->opCertStore == nullptr) + { + // WARNING: PersistentStorageOpCertStore::Finish() is never called. It's fine for + // for examples and for now, since all storage is immediate for that impl. + ReturnErrorOnFailure(sPersistentStorageOpCertStore.Init(this->persistentStorageDelegate)); + this->opCertStore = &sPersistentStorageOpCertStore; + } + + // Injection of report scheduler WILL lead to two schedulers being allocated. As recommended above, this should only be used + // for IN-TREE examples. If a default scheduler is desired, the basic ServerInitParams should be used by the application and + // CommonCaseDeviceServerInitParams should not be allocated. + if (this->reportScheduler == nullptr) + { + reportScheduler = &sReportScheduler; + } + + if (this->termsAndConditionsProvider == nullptr) + { + ReturnErrorOnFailure(sDefaultTermsAndConditionsProviderInstance.Init(this->persistentStorageDelegate)); + this->termsAndConditionsProvider = sDefaultTermsAndConditionsProvider; + } + + if (this->enhancedSetupFlowProvider == nullptr) + { + ReturnErrorOnFailure(sDefaultEnhancedSetupFlowProviderInstance.Init(this->termsAndConditionsProvider)); + this->enhancedSetupFlowProvider = sDefaultEnhancedSetupFlowProvider; + } + + // Session Keystore injection + this->sessionKeystore = &sSessionKeystore; + + // Group Data provider injection + sGroupDataProvider.SetStorageDelegate(this->persistentStorageDelegate); + sGroupDataProvider.SetSessionKeystore(this->sessionKeystore); + ReturnErrorOnFailure(sGroupDataProvider.Init()); + this->groupDataProvider = &sGroupDataProvider; + +#if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION + ReturnErrorOnFailure(sSessionResumptionStorage.Init(this->persistentStorageDelegate)); + this->sessionResumptionStorage = &sSessionResumptionStorage; +#else + this->sessionResumptionStorage = nullptr; +#endif + + // Inject access control delegate + this->accessDelegate = Access::Examples::GetAccessControlDelegate(); + + // Inject ACL storage. (Don't initialize it.) + this->aclStorage = &sAclStorage; + +#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS + ChipLogProgress(AppServer, "Initializing subscription resumption storage..."); + ReturnErrorOnFailure(sSubscriptionResumptionStorage.Init(this->persistentStorageDelegate)); + this->subscriptionResumptionStorage = &sSubscriptionResumptionStorage; +#else + ChipLogProgress(AppServer, "Subscription persistence not supported"); +#endif + + return CHIP_NO_ERROR; +} + CHIP_ERROR Server::Init(const ServerInitParams & initParams) { ChipLogProgress(AppServer, "Server initializing..."); @@ -122,6 +215,8 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams) VerifyOrExit(initParams.operationalKeystore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(initParams.opCertStore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(initParams.reportScheduler != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrExit(initParams.enhancedSetupFlowProvider != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrExit(initParams.termsAndConditionsProvider != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); // TODO(16969): Remove chip::Platform::MemoryInit() call from Server class, it belongs to outer code chip::Platform::MemoryInit(); @@ -178,6 +273,9 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams) mReportScheduler = initParams.reportScheduler; + mTermsAndConditionsProvider = initParams.termsAndConditionsProvider; + mEnhancedSetupFlowProvider = initParams.enhancedSetupFlowProvider; + mTestEventTriggerDelegate = initParams.testEventTriggerDelegate; deviceInfoprovider = DeviceLayer::GetDeviceInfoProvider(); diff --git a/src/app/server/Server.h b/src/app/server/Server.h index 302471b8bebb89..c0d6c7065a5d0b 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -33,6 +33,8 @@ #include #include #include +#include +#include #include #include #include @@ -153,7 +155,9 @@ struct ServerInitParams // must not be null at timne of Server::Init(). Credentials::OperationalCertificateStore * opCertStore = nullptr; // Required, if not provided, the Server::Init() WILL fail. - app::reporting::ReportScheduler * reportScheduler = nullptr; + app::reporting::ReportScheduler * reportScheduler = nullptr; + app::EnhancedSetupFlowProvider * enhancedSetupFlowProvider = nullptr; + app::TermsAndConditionsProvider * termsAndConditionsProvider = nullptr; }; /** @@ -200,76 +204,7 @@ struct CommonCaseDeviceServerInitParams : public ServerInitParams * @return CHIP_NO_ERROR on success or a CHIP_ERROR value from APIs called to initialize * resources on failure. */ - CHIP_ERROR InitializeStaticResourcesBeforeServerInit() - { - // KVS-based persistent storage delegate injection - if (persistentStorageDelegate == nullptr) - { - chip::DeviceLayer::PersistedStorage::KeyValueStoreManager & kvsManager = - DeviceLayer::PersistedStorage::KeyValueStoreMgr(); - ReturnErrorOnFailure(sKvsPersistenStorageDelegate.Init(&kvsManager)); - this->persistentStorageDelegate = &sKvsPersistenStorageDelegate; - } - - // PersistentStorageDelegate "software-based" operational key access injection - if (this->operationalKeystore == nullptr) - { - // WARNING: PersistentStorageOperationalKeystore::Finish() is never called. It's fine for - // for examples and for now. - ReturnErrorOnFailure(sPersistentStorageOperationalKeystore.Init(this->persistentStorageDelegate)); - this->operationalKeystore = &sPersistentStorageOperationalKeystore; - } - - // OpCertStore can be injected but default to persistent storage default - // for simplicity of the examples. - if (this->opCertStore == nullptr) - { - // WARNING: PersistentStorageOpCertStore::Finish() is never called. It's fine for - // for examples and for now, since all storage is immediate for that impl. - ReturnErrorOnFailure(sPersistentStorageOpCertStore.Init(this->persistentStorageDelegate)); - this->opCertStore = &sPersistentStorageOpCertStore; - } - - // Injection of report scheduler WILL lead to two schedulers being allocated. As recommended above, this should only be used - // for IN-TREE examples. If a default scheduler is desired, the basic ServerInitParams should be used by the application and - // CommonCaseDeviceServerInitParams should not be allocated. - if (this->reportScheduler == nullptr) - { - reportScheduler = &sReportScheduler; - } - - // Session Keystore injection - this->sessionKeystore = &sSessionKeystore; - - // Group Data provider injection - sGroupDataProvider.SetStorageDelegate(this->persistentStorageDelegate); - sGroupDataProvider.SetSessionKeystore(this->sessionKeystore); - ReturnErrorOnFailure(sGroupDataProvider.Init()); - this->groupDataProvider = &sGroupDataProvider; - -#if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION - ReturnErrorOnFailure(sSessionResumptionStorage.Init(this->persistentStorageDelegate)); - this->sessionResumptionStorage = &sSessionResumptionStorage; -#else - this->sessionResumptionStorage = nullptr; -#endif - - // Inject access control delegate - this->accessDelegate = Access::Examples::GetAccessControlDelegate(); - - // Inject ACL storage. (Don't initialize it.) - this->aclStorage = &sAclStorage; - -#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS - ChipLogProgress(AppServer, "Initializing subscription resumption storage..."); - ReturnErrorOnFailure(sSubscriptionResumptionStorage.Init(this->persistentStorageDelegate)); - this->subscriptionResumptionStorage = &sSubscriptionResumptionStorage; -#else - ChipLogProgress(AppServer, "Subscription persistence not supported"); -#endif - - return CHIP_NO_ERROR; - } + CHIP_ERROR InitializeStaticResourcesBeforeServerInit(); private: static KvsPersistentStorageDelegate sKvsPersistenStorageDelegate; @@ -287,6 +222,8 @@ struct CommonCaseDeviceServerInitParams : public ServerInitParams #endif static app::DefaultAclStorage sAclStorage; static Crypto::DefaultSessionKeystore sSessionKeystore; + static app::EnhancedSetupFlowProvider * sDefaultEnhancedSetupFlowProvider; + static app::TermsAndConditionsProvider * sDefaultTermsAndConditionsProvider; }; /** @@ -367,6 +304,8 @@ class Server app::reporting::ReportScheduler * GetReportScheduler() { return mReportScheduler; } + app::EnhancedSetupFlowProvider * GetEnhancedSetupFlowProvider() { return mEnhancedSetupFlowProvider; } + #if CHIP_CONFIG_ENABLE_ICD_SERVER app::ICDManager & GetICDManager() { return mICDManager; } #endif // CHIP_CONFIG_ENABLE_ICD_SERVER @@ -628,6 +567,8 @@ class Server GroupDataProviderListener mListener; ServerFabricDelegate mFabricDelegate; app::reporting::ReportScheduler * mReportScheduler; + app::EnhancedSetupFlowProvider * mEnhancedSetupFlowProvider; + app::TermsAndConditionsProvider * mTermsAndConditionsProvider; Access::AccessControl mAccessControl; app::AclStorage * mAclStorage; diff --git a/src/app/server/TermsAndConditionsProvider.h b/src/app/server/TermsAndConditionsProvider.h new file mode 100644 index 00000000000000..4fb723852b2c45 --- /dev/null +++ b/src/app/server/TermsAndConditionsProvider.h @@ -0,0 +1,75 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#pragma once + +#include + +#include + +namespace chip { +namespace app { + +/** + * @brief Data access layer for the required terms and conditions and the store for the user acceptance. + */ +class TermsAndConditionsProvider +{ +public: + /** + * @brief Destructor. + */ + virtual ~TermsAndConditionsProvider() = default; + + /** + * @brief Retrieves the acceptance status of the required terms and conditions. + * + * @param[out] outAcknowledgementsValue The number of acknowledgements accepted. + * @param[out] outAcknowledgementsVersionValue The version of the accepted acknowledgements. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR GetAcceptance(uint16_t & outAcknowledgementsValue, uint16_t & outAcknowledgementsVersionValue) = 0; + + /** + * @brief Retrieves the requirements of the terms and conditions. + * + * @param[out] outAcknowledgementsValue The number of required acknowledgements. + * @param[out] outAcknowledgementsVersionValue The version of the required acknowledgements. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR GetRequirements(uint16_t & outAcknowledgementsValue, uint16_t & outAcknowledgementsVersionValue) = 0; + + /** + * @brief Sets the acceptance status of the required terms and conditions. + * + * @param[in] inAcknowledgementsValue The number of acknowledgements to accept. + * @param[in] inAcknowledgementsVersionValue The version of the acknowledgements to accept. + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR SetAcceptance(uint16_t inAcknowledgementsValue, uint16_t inAcknowledgementsVersionValue) = 0; + + /** + * @brief Sets the acceptance status of the required terms and conditions. + * + * @return CHIP_ERROR On success returns CHIP_NO_ERROR, otherwise returns an error code. + */ + virtual CHIP_ERROR ClearAcceptance() = 0; +}; + +}; // namespace app +}; // namespace chip diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 78b9c8f69e87df..6ec7c58cf42314 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -138,7 +138,9 @@ chip_test_suite_using_nltest("tests") { "TestCommandPathParams.cpp", "TestConcreteAttributePath.cpp", "TestDataModelSerialization.cpp", + "TestDefaultEnhancedSetupFlowProvider.cpp", "TestDefaultOTARequestorStorage.cpp", + "TestDefaultTermsAndConditionsProvider.cpp", "TestEventLoggingNoUTCTime.cpp", "TestEventOverflow.cpp", "TestEventPathParams.cpp", diff --git a/src/app/tests/TestDefaultEnhancedSetupFlowProvider.cpp b/src/app/tests/TestDefaultEnhancedSetupFlowProvider.cpp new file mode 100644 index 00000000000000..7cf55aec4bd738 --- /dev/null +++ b/src/app/tests/TestDefaultEnhancedSetupFlowProvider.cpp @@ -0,0 +1,67 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#include + +#include + +static int Setup(void * inContext) +{ + return SUCCESS; +} + +static int TearDown(void * inContext) +{ + return SUCCESS; +} + +static int Initialize(void * inContext) +{ + return SUCCESS; +} + +static int Terminate(void * inContext) +{ + return SUCCESS; +} + +static void TestDefaultEnhancedSetupFlowProvider(struct _nlTestSuite * inSuite, void * inContext) +{ + NL_TEST_ASSERT(inSuite, true); +} + +static nlTestSuite sEnhancedSetupFlowProviderTestSuite = { + .name = (const char *) "Enhanced Setup Flow Provider Test Suite", + .tests = + (const nlTest[]){ + NL_TEST_DEF("Enhanced Setup Flow Provider Test", TestDefaultEnhancedSetupFlowProvider), + NL_TEST_SENTINEL(), + }, + .setup = (int (*)(void *)) Setup, + .tear_down = (int (*)(void *)) TearDown, + .initialize = (int (*)(void *)) Initialize, + .terminate = (int (*)(void *)) Terminate, +}; + +int TestDefaultEnhancedSetupFlowProvider() +{ + nlTestRunner(&sEnhancedSetupFlowProviderTestSuite, nullptr); + return nlTestRunnerStats(&sEnhancedSetupFlowProviderTestSuite); +} + +CHIP_REGISTER_TEST_SUITE(TestDefaultEnhancedSetupFlowProvider) diff --git a/src/app/tests/TestDefaultTermsAndConditionsProvider.cpp b/src/app/tests/TestDefaultTermsAndConditionsProvider.cpp new file mode 100644 index 00000000000000..85a17a27cf146d --- /dev/null +++ b/src/app/tests/TestDefaultTermsAndConditionsProvider.cpp @@ -0,0 +1,218 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#include +#include + +#include +#include + +#include "app/server/DefaultTermsAndConditionsProvider.h" +#include "lib/core/CHIPError.h" + +/** + * @brief Setup function for the test suite. + * + * This function is called before running the test suite. + * It performs any necessary setup steps. + * + * @param inContext A pointer to the context (not used in this function). + * @return SUCCESS if setup succeeds, an error code otherwise. + */ +static int Setup(void * inContext) +{ + return SUCCESS; +} + +/** + * @brief Tear down function for the test suite. + * + * This function is called after running the test suite. + * It performs any necessary cleanup steps. + * + * @param inContext A pointer to the context (not used in this function). + * @return SUCCESS if teardown succeeds, an error code otherwise. + */ +static int TearDown(void * inContext) +{ + return SUCCESS; +} + +/** + * @brief Initialization function for the test suite. + * + * This function is called before running each test case. + * It performs any necessary initialization steps. + * + * @param inContext A pointer to the context (not used in this function). + * @return SUCCESS if initialization succeeds, an error code otherwise. + */ +static int Initialize(void * inContext) +{ + return SUCCESS; +} + +/** + * @brief Termination function for the test suite. + * + * This function is called after running each test case. + * It performs any necessary termination steps. + * + * @param inContext A pointer to the context (not used in this function). + * @return SUCCESS if termination succeeds, an error code otherwise. + */ +static int Terminate(void * inContext) +{ + return SUCCESS; +} + +/** + * @brief Test case for initializing the DefaultTermsAndConditionsProvider. + * + * This test case verifies that the DefaultTermsAndConditionsProvider initializes successfully. + * It initializes the provider with a mock key-value store manager and checks for success. + */ +static void TestDefaultTermsAndConditionsProviderInitSuccess(struct _nlTestSuite * inSuite, void * inContext) +{ + chip::TestPersistentStorageDelegate testPersistentStorageDelegate; + + chip::app::DefaultTermsAndConditionsProvider uut; + CHIP_ERROR err = uut.Init(&testPersistentStorageDelegate); + + NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err); +} + +/** + * @brief Test case for retrieving acceptance from the DefaultTermsAndConditionsProvider. + * + * This test case verifies that the DefaultTermsAndConditionsProvider retrieves acceptance successfully. + * It initializes the provider with a mock key-value store manager, sets up expectations for Get method calls, + * calls the GetAcceptance method, and checks for expected values. + */ +static void TestDefaultTermsAndConditionsProviderGetAcceptanceSuccess(struct _nlTestSuite * inSuite, void * inContext) +{ + CHIP_ERROR err; + uint16_t acknowledgements; + uint16_t acknowledgementsVersion; + + chip::TestPersistentStorageDelegate testPersistentStorageDelegate; + chip::app::DefaultTermsAndConditionsProvider uut; + + err = uut.Init(&testPersistentStorageDelegate); + NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err); + + uut.SetAcceptance(1, 1); + + err = uut.GetAcceptance(acknowledgements, acknowledgementsVersion); + NL_TEST_ASSERT(inSuite, 1 == acknowledgements); + NL_TEST_ASSERT(inSuite, 1 == acknowledgementsVersion); +} + +/** + * @brief Test case for getting requirements from the DefaultTermsAndConditionsProvider. + * + * This test case verifies that getting requirements from the DefaultTermsAndConditionsProvider succeeds. + * It checks for successful execution without any assertions. + */ +static void TestGetRequirementsSuccess(struct _nlTestSuite * inSuite, void * inContext) +{ + // Test implementation goes here... +} + +/** + * @brief Test case for setting acceptance in the DefaultTermsAndConditionsProvider. + * + * This test case verifies that setting acceptance in the DefaultTermsAndConditionsProvider succeeds. + * It checks for successful execution without any assertions. + */ +static void TestSetAcceptanceSuccess(struct _nlTestSuite * inSuite, void * inContext) +{ + // Test implementation goes here... +} + +/** + * @brief Test case for initialization failure of the DefaultTermsAndConditionsProvider. + * + * This test case verifies that the DefaultTermsAndConditionsProvider fails to initialize. + * It checks for failure conditions without any assertions. + */ +static void TestInitFailure(struct _nlTestSuite * inSuite, void * inContext) +{ + // Test implementation goes here... +} + +/** + * @brief Test case for failure in retrieving acceptance from the DefaultTermsAndConditionsProvider. + * + * This test case verifies that retrieving acceptance from the DefaultTermsAndConditionsProvider fails. + * It checks for failure conditions without any assertions. + */ +static void TestGetAcceptanceFailure(struct _nlTestSuite * inSuite, void * inContext) +{ + // Test implementation goes here... +} + +/** + * @brief Test case for failure in getting requirements from the DefaultTermsAndConditionsProvider. + * + * This test case verifies that getting requirements from the DefaultTermsAndConditionsProvider fails. + * It checks for failure conditions without any assertions. + */ +static void TestGetRequirementsFailure(struct _nlTestSuite * inSuite, void * inContext) +{ + // Test implementation goes here... +} + +/** + * @brief Test case for failure in setting acceptance in the DefaultTermsAndConditionsProvider. + * + * This test case verifies that setting acceptance in the DefaultTermsAndConditionsProvider fails. + * It checks for failure conditions without any assertions. + */ +static void TestSetAcceptanceFailure(struct _nlTestSuite * inSuite, void * inContext) +{ + // Test implementation goes here... +} + +static nlTestSuite sDefaultTermsAndConditionsProviderTestSuite = { + .name = (const char *) "Terms and Conditions Provider Test Suite", + .tests = + (const nlTest[]){ + NL_TEST_DEF("TestInitSuccess", TestDefaultTermsAndConditionsProviderInitSuccess), + NL_TEST_DEF("TestGetAcceptanceSuccess", TestDefaultTermsAndConditionsProviderGetAcceptanceSuccess), + NL_TEST_DEF("TestGetRequirementsSuccess", TestGetRequirementsSuccess), + NL_TEST_DEF("TestSetAcceptanceSuccess", TestSetAcceptanceSuccess), + NL_TEST_DEF("TestInitFailure", TestInitFailure), + NL_TEST_DEF("TestGetAcceptanceFailure", TestGetAcceptanceFailure), + NL_TEST_DEF("TestGetRequirementsFailure", TestGetRequirementsFailure), + NL_TEST_DEF("TestSetAcceptanceFailure", TestSetAcceptanceFailure), + NL_TEST_SENTINEL(), + }, + .setup = (int (*)(void *)) Setup, + .tear_down = (int (*)(void *)) TearDown, + .initialize = (int (*)(void *)) Initialize, + .terminate = (int (*)(void *)) Terminate, +}; + +int TestDefaultTermsAndConditionsProvider() +{ + nlTestRunner(&sDefaultTermsAndConditionsProviderTestSuite, nullptr); + return nlTestRunnerStats(&sDefaultTermsAndConditionsProviderTestSuite); +} + +CHIP_REGISTER_TEST_SUITE(TestDefaultTermsAndConditionsProvider) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index 42b39a10c7ab48..1c1473326b12b0 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2021-2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -343,13 +343,14 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio case CommissioningStage::kArmFailsafe: return CommissioningStage::kConfigRegulatory; case CommissioningStage::kConfigRegulatory: + return CommissioningStage::kConfigureTCAcknowledgments; + case CommissioningStage::kConfigureTCAcknowledgments: if (mDeviceCommissioningInfo.requiresUTC) { return CommissioningStage::kConfigureUTCTime; } else { - // Time cluster is not supported, move right to DA return CommissioningStage::kSendPAICertificateRequest; } case CommissioningStage::kConfigureUTCTime: diff --git a/src/controller/BUILD.gn b/src/controller/BUILD.gn index b06b2defecb8f2..c8eddf9bf465af 100644 --- a/src/controller/BUILD.gn +++ b/src/controller/BUILD.gn @@ -113,10 +113,11 @@ static_library("controller") { public_deps = [ "${chip_root}/src/app", - "${chip_root}/src/app/server", + "${chip_root}/src/app/server:server-core", "${chip_root}/src/lib/core", "${chip_root}/src/lib/dnssd", "${chip_root}/src/lib/support", + "${chip_root}/src/lib/support:testing", "${chip_root}/src/messaging", "${chip_root}/src/platform", "${chip_root}/src/protocols", diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index af0a66ea834da3..0a6831173d3ce2 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-2024 Project CHIP Authors * Copyright (c) 2013-2017 Nest Labs, Inc. * All rights reserved. * @@ -2426,6 +2426,22 @@ void DeviceCommissioner::OnSetRegulatoryConfigResponse( commissioner->CommissioningStageComplete(err, report); } +void DeviceCommissioner::OnSetTCAcknowledgementsResponse( + void * context, const GeneralCommissioning::Commands::SetTCAcknowledgementsResponse::DecodableType & data) +{ + CommissioningDelegate::CommissioningReport report; + CHIP_ERROR err = CHIP_NO_ERROR; + + ChipLogProgress(Controller, "Received SetTCAcknowledgements response errorCode=%u", to_underlying(data.errorCode)); + if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk) + { + err = CHIP_ERROR_INTERNAL; + report.Set(data.errorCode); + } + DeviceCommissioner * commissioner = static_cast(context); + commissioner->CommissioningStageComplete(err, report); +} + void DeviceCommissioner::OnSetTimeZoneResponse(void * context, const TimeSynchronization::Commands::SetTimeZoneResponse::DecodableType & data) { @@ -2874,6 +2890,29 @@ void DeviceCommissioner::PerformCommissioningStep(DeviceProxy * proxy, Commissio } } break; + case CommissioningStage::kConfigureTCAcknowledgments: { + ChipLogProgress(Controller, "Setting Terms and Conditions"); + + if (!params.GetTermsAndConditionsAcknowledgement().HasValue()) + { + CommissioningStageComplete(CHIP_NO_ERROR); + } + + GeneralCommissioning::Commands::SetTCAcknowledgements::Type request; + TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement = params.GetTermsAndConditionsAcknowledgement().Value(); + request.TCUserResponse = termsAndConditionsAcknowledgement.acceptedTermsAndConditions; + request.TCVersion = termsAndConditionsAcknowledgement.acceptedTermsAndConditionsVersion; + CHIP_ERROR err = + SendCommissioningCommand(proxy, request, OnSetTCAcknowledgementsResponse, OnBasicFailure, endpoint, timeout); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Failed to send SetTCAcknowledgements command: %" CHIP_ERROR_FORMAT, err.Format()); + CommissioningStageComplete(err); + return; + } + + break; + } case CommissioningStage::kSendPAICertificateRequest: { ChipLogProgress(Controller, "Sending request for PAI certificate"); CHIP_ERROR err = SendCertificateChainRequestCommand(proxy, CertificateType::kPAI, timeout); diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index dd7b5bc31eec46..d6effac7ad4434 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-2024 Project CHIP Authors * Copyright (c) 2013-2017 Nest Labs, Inc. * All rights reserved. * @@ -893,6 +893,9 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, static void OnSetRegulatoryConfigResponse( void * context, const chip::app::Clusters::GeneralCommissioning::Commands::SetRegulatoryConfigResponse::DecodableType & data); + static void OnSetTCAcknowledgementsResponse( + void * context, + const chip::app::Clusters::GeneralCommissioning::Commands::SetTCAcknowledgementsResponse::DecodableType & data); static void OnSetUTCError(void * context, CHIP_ERROR error); static void OnSetTimeZoneResponse(void * context, diff --git a/src/controller/CommissioningDelegate.h b/src/controller/CommissioningDelegate.h index 4b1040fcd79690..c6d69dd689eebf 100644 --- a/src/controller/CommissioningDelegate.h +++ b/src/controller/CommissioningDelegate.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2021-2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,6 +23,7 @@ #include #include #include +#include #include namespace chip { @@ -38,6 +39,7 @@ enum CommissioningStage : uint8_t kReadCommissioningInfo2, ///< Query SupportsConcurrentConnection, ICD state, check for matching fabric kArmFailsafe, ///< Send ArmFailSafe (0x30:0) command to the device kConfigRegulatory, ///< Send SetRegulatoryConfig (0x30:2) command to the device + kConfigureTCAcknowledgments, ///< Send SetTCAcknowledgements (0x30:6) command to the device kConfigureUTCTime, ///< SetUTCTime if the DUT has a time cluster kConfigureTimeZone, ///< Configure a time zone if one is required and available kConfigureDSTOffset, ///< Configure DST offset if one is required and available @@ -94,6 +96,12 @@ struct WiFiCredentials WiFiCredentials(ByteSpan newSsid, ByteSpan newCreds) : ssid(newSsid), credentials(newCreds) {} }; +struct TermsAndConditionsAcknowledgement +{ + uint16_t acceptedTermsAndConditions; + uint16_t acceptedTermsAndConditionsVersion; +}; + struct NOCChainGenerationParameters { ByteSpan nocsrElements; @@ -158,6 +166,11 @@ class CommissioningParameters // The country code to be used for the node, if set. Optional GetCountryCode() const { return mCountryCode; } + Optional GetTermsAndConditionsAcknowledgement() const + { + return mTermsAndConditionsAcknowledgement; + } + // Time zone to set for the node // If required, this will be truncated to fit the max size allowable on the node Optional> GetTimeZone() const @@ -330,6 +343,13 @@ class CommissioningParameters return *this; } + CommissioningParameters & + SetTermsAndConditionsAcknowledgement(TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement) + { + mTermsAndConditionsAcknowledgement.SetValue(termsAndConditionsAcknowledgement); + return *this; + } + // The lifetime of the list buffer needs to exceed the lifetime of the CommissioningParameters object. CommissioningParameters & SetTimeZone(app::DataModel::List timeZone) @@ -594,6 +614,7 @@ class CommissioningParameters Optional mAttestationNonce; Optional mWiFiCreds; Optional mCountryCode; + Optional mTermsAndConditionsAcknowledgement; Optional mThreadOperationalDataset; Optional mNOCChainGenerationParameters; Optional mRootCert; diff --git a/src/lib/support/DefaultStorageKeyAllocator.h b/src/lib/support/DefaultStorageKeyAllocator.h index 04825c9ca4d719..5f70b847582ab7 100644 --- a/src/lib/support/DefaultStorageKeyAllocator.h +++ b/src/lib/support/DefaultStorageKeyAllocator.h @@ -94,6 +94,12 @@ class DefaultStorageKeyAllocator DefaultStorageKeyAllocator() = default; public: + // Terms and Conditions Acceptance + static StorageKeyName TermsAndConditionsAcceptance(uint16_t acknowledgementsVersion) + { + return StorageKeyName::Formatted("g/tc/%" PRIu16 "/a", acknowledgementsVersion); + } + // Fabric Table static StorageKeyName FabricIndexInfo() { return StorageKeyName::FromConst("g/fidx"); } static StorageKeyName FabricNOC(FabricIndex fabric) { return StorageKeyName::Formatted("f/%x/n", fabric); }