forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.py
1477 lines (1238 loc) · 67 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2021 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.
#
import asyncio
import copy
import ctypes
import faulthandler
import hashlib
import inspect
import logging
import os
import secrets
import struct
import sys
import threading
import time
from dataclasses import dataclass
from typing import Any
import chip.CertificateAuthority
import chip.clusters as Clusters
import chip.clusters.Attribute as Attribute
import chip.discovery
import chip.FabricAdmin
import chip.interaction_model as IM
import chip.native
from chip import ChipDeviceCtrl
from chip.ChipStack import ChipStack
from chip.crypto import p256keypair
from chip.exceptions import ChipStackException
from chip.utils import CommissioningBuildingBlocks
from cirque_restart_remote_device import restartRemoteDevice
from ecdsa import NIST256p
logger = logging.getLogger('PythonMatterControllerTEST')
logger.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setFormatter(
logging.Formatter(
'%(asctime)s [%(name)s] %(levelname)s %(message)s'))
sh.setStream(sys.stdout)
logger.addHandler(sh)
def GenerateVerifier(passcode: int, salt: bytes, iterations: int) -> bytes:
ws_len = NIST256p.baselen + 8
ws = hashlib.pbkdf2_hmac('sha256', struct.pack('<I', passcode), salt, iterations, ws_len * 2)
w0 = int.from_bytes(ws[:ws_len], byteorder='big') % NIST256p.order
w1 = int.from_bytes(ws[ws_len:], byteorder='big') % NIST256p.order
L = NIST256p.generator * w1
return w0.to_bytes(NIST256p.baselen, byteorder='big') + L.to_bytes('uncompressed')
def TestFail(message, doCrash=False):
logger.fatal("Testfail: {}".format(message))
if (doCrash):
logger.fatal("--------------------------------")
logger.fatal("Backtrace of all Python threads:")
logger.fatal("--------------------------------")
#
# Let's dump the Python backtrace for all threads, since the backtrace we'll
# get from gdb (if one is attached) won't give us good Python symbol information.
#
faulthandler.dump_traceback()
#
# Cause a crash to happen so that we can actually get a meaningful
# backtrace when run through GDB.
#
chip.native.GetLibraryHandle().pychip_CauseCrash()
else:
os._exit(1)
def FailIfNot(cond, message):
if not cond:
TestFail(message)
_configurable_tests = set()
_configurable_test_sets = set()
_enabled_tests = []
_disabled_tests = []
def SetTestSet(enabled_tests, disabled_tests):
global _enabled_tests, _disabled_tests
_enabled_tests = enabled_tests[:]
_disabled_tests = disabled_tests[:]
def TestIsEnabled(test_name: str):
enabled_len = -1
disabled_len = -1
if 'all' in _enabled_tests:
enabled_len = 0
if 'all' in _disabled_tests:
disabled_len = 0
for test_item in _enabled_tests:
if test_name.startswith(test_item) and (len(test_item) > enabled_len):
enabled_len = len(test_item)
for test_item in _disabled_tests:
if test_name.startswith(test_item) and (len(test_item) > disabled_len):
disabled_len = len(test_item)
return enabled_len > disabled_len
def test_set(cls):
_configurable_test_sets.add(cls.__qualname__)
return cls
def test_case(func):
test_name = func.__qualname__
_configurable_tests.add(test_name)
def CheckEnableBeforeRun(*args, **kwargs):
if TestIsEnabled(test_name=test_name):
return func(*args, **kwargs)
elif inspect.iscoroutinefunction(func):
# noop, so users can use await as usual
return asyncio.sleep(0)
return CheckEnableBeforeRun
def configurable_tests():
res = sorted([v for v in _configurable_test_sets])
return res
def configurable_test_cases():
res = sorted([v for v in _configurable_tests])
return res
class TestTimeout(threading.Thread):
def __init__(self, timeout: int):
threading.Thread.__init__(self)
self._timeout = timeout
self._should_stop = False
self._cv = threading.Condition()
def stop(self):
with self._cv:
self._should_stop = True
self._cv.notify_all()
self.join()
def run(self):
stop_time = time.time() + self._timeout
logger.info("Test timeout set to {} seconds".format(self._timeout))
with self._cv:
wait_time = stop_time - time.time()
while wait_time > 0 and not self._should_stop:
self._cv.wait(wait_time)
wait_time = stop_time - time.time()
if time.time() > stop_time:
TestFail("Timeout", doCrash=True)
class BaseTestHelper:
def __init__(self, nodeid: int, paaTrustStorePath: str, testCommissioner: bool = False,
keypair: p256keypair.P256Keypair = None):
chip.native.Init()
self.chipStack = ChipStack('/tmp/repl_storage.json')
self.certificateAuthorityManager = chip.CertificateAuthority.CertificateAuthorityManager(chipStack=self.chipStack)
self.certificateAuthority = self.certificateAuthorityManager.NewCertificateAuthority()
self.fabricAdmin = self.certificateAuthority.NewFabricAdmin(vendorId=0xFFF1, fabricId=1)
self.devCtrl = self.fabricAdmin.NewController(
nodeid, paaTrustStorePath, testCommissioner, keypair=keypair)
self.controllerNodeId = nodeid
self.logger = logger
self.paaTrustStorePath = paaTrustStorePath
logging.getLogger().setLevel(logging.DEBUG)
async def _GetCommissonedFabricCount(self, nodeid: int):
data = await self.devCtrl.ReadAttribute(nodeid, [(Clusters.OperationalCredentials.Attributes.CommissionedFabrics)])
return data[0][Clusters.OperationalCredentials][Clusters.OperationalCredentials.Attributes.CommissionedFabrics]
def _WaitForOneDiscoveredDevice(self, timeoutSeconds: int = 2):
print("Waiting for device responses...")
strlen = 100
addrStrStorage = ctypes.create_string_buffer(strlen)
timeout = time.time() + timeoutSeconds
while (not self.devCtrl.GetIPForDiscoveredDevice(0, addrStrStorage, strlen) and time.time() <= timeout):
time.sleep(0.2)
if time.time() > timeout:
return None
return ctypes.string_at(addrStrStorage).decode("utf-8")
def TestDiscovery(self, discriminator: int):
self.logger.info(
f"Discovering commissionable nodes with discriminator {discriminator}")
res = self.devCtrl.DiscoverCommissionableNodes(
chip.discovery.FilterType.LONG_DISCRIMINATOR, discriminator, stopOnFirst=True, timeoutSecond=3)
if not res:
self.logger.info(
"Device not found")
return False
self.logger.info(f"Found device {res[0]}")
return res[0]
def CreateNewFabricController(self):
self.logger.info("Creating 2nd Fabric Admin")
self.fabricAdmin2 = self.certificateAuthority.NewFabricAdmin(vendorId=0xFFF1, fabricId=2)
self.logger.info("Creating Device Controller on 2nd Fabric")
self.devCtrl2 = self.fabricAdmin2.NewController(
self.controllerNodeId, self.paaTrustStorePath)
return True
async def TestRevokeCommissioningWindow(self, ip: str, setuppin: int, nodeid: int):
await self.devCtrl.SendCommand(
nodeid, 0, Clusters.AdministratorCommissioning.Commands.OpenBasicCommissioningWindow(180), timedRequestTimeoutMs=10000)
if not await self.TestPaseOnly(ip=ip, setuppin=setuppin, nodeid=nodeid, devCtrl=self.devCtrl2):
return False
await self.devCtrl2.SendCommand(
nodeid, 0, Clusters.GeneralCommissioning.Commands.ArmFailSafe(expiryLengthSeconds=180, breadcrumb=0))
await self.devCtrl.SendCommand(
nodeid, 0, Clusters.AdministratorCommissioning.Commands.RevokeCommissioning(), timedRequestTimeoutMs=10000)
await self.devCtrl.SendCommand(
nodeid, 0, Clusters.AdministratorCommissioning.Commands.OpenBasicCommissioningWindow(180), timedRequestTimeoutMs=10000)
await self.devCtrl.SendCommand(
nodeid, 0, Clusters.AdministratorCommissioning.Commands.RevokeCommissioning(), timedRequestTimeoutMs=10000)
return True
async def TestEnhancedCommissioningWindow(self, ip: str, nodeid: int):
params = await self.devCtrl.OpenCommissioningWindow(nodeid=nodeid, timeout=600, iteration=10000, discriminator=3840, option=1)
return await self.TestPaseOnly(ip=ip, nodeid=nodeid, setuppin=params.setupPinCode, devCtrl=self.devCtrl2)
async def TestPaseOnly(self, ip: str, setuppin: int, nodeid: int, devCtrl=None):
if devCtrl is None:
devCtrl = self.devCtrl
self.logger.info(
"Attempting to establish PASE session with device id: {} addr: {}".format(str(nodeid), ip))
try:
await devCtrl.EstablishPASESessionIP(ip, setuppin, nodeid)
except ChipStackException:
self.logger.info(
"Failed to establish PASE session with device id: {} addr: {}".format(str(nodeid), ip))
return False
self.logger.info(
"Successfully established PASE session with device id: {} addr: {}".format(str(nodeid), ip))
return True
async def TestCommissionOnly(self, nodeid: int):
self.logger.info(
"Commissioning device with id {}".format(nodeid))
try:
await self.devCtrl.Commission(nodeid)
except ChipStackException:
self.logger.info(
"Failed to commission device with id {}".format(str(nodeid)))
return False
self.logger.info(
"Successfully commissioned device with id {}".format(str(nodeid)))
return True
async def TestKeyExchangeBLE(self, discriminator: int, setuppin: int, nodeid: int):
self.logger.info(
"Conducting key exchange with device {}".format(discriminator))
if not await self.devCtrl.ConnectBLE(discriminator, setuppin, nodeid):
self.logger.info(
"Failed to finish key exchange with device {}".format(discriminator))
return False
self.logger.info("Device finished key exchange.")
return True
async def TestCommissionFailure(self, nodeid: int, failAfter: int):
self.devCtrl.ResetTestCommissioner()
a = self.devCtrl.SetTestCommissionerSimulateFailureOnStage(failAfter)
if not a:
# We're not going to hit this stage during commissioning so no sense trying, just say it was fine.
return True
self.logger.info(
"Commissioning device, expecting failure after stage {}".format(failAfter))
await self.devCtrl.Commission(nodeid)
return self.devCtrl.CheckTestCommissionerCallbacks() and self.devCtrl.CheckTestCommissionerPaseConnection(nodeid)
async def TestCommissionFailureOnReport(self, nodeid: int, failAfter: int):
self.devCtrl.ResetTestCommissioner()
a = self.devCtrl.SetTestCommissionerSimulateFailureOnReport(failAfter)
if not a:
# We're not going to hit this stage during commissioning so no sense trying, just say it was fine.
return True
self.logger.info(
"Commissioning device, expecting failure on report for stage {}".format(failAfter))
await self.devCtrl.Commission(nodeid)
return self.devCtrl.CheckTestCommissionerCallbacks() and self.devCtrl.CheckTestCommissionerPaseConnection(nodeid)
async def TestCommissioning(self, ip: str, setuppin: int, nodeid: int):
self.logger.info("Commissioning device {}".format(ip))
try:
await self.devCtrl.CommissionIP(ip, setuppin, nodeid)
except ChipStackException:
self.logger.exception(
"Failed to finish commissioning device {}".format(ip))
return False
self.logger.info("Commissioning finished.")
return True
async def TestCommissioningWithSetupPayload(self, setupPayload: str, nodeid: int, discoveryType: int = 2):
self.logger.info("Commissioning device with setup payload {}".format(setupPayload))
try:
await self.devCtrl.CommissionWithCode(setupPayload, nodeid, chip.discovery.DiscoveryType(discoveryType))
except ChipStackException:
self.logger.exception(
"Failed to finish commissioning device {}".format(setupPayload))
return False
self.logger.info("Commissioning finished.")
return True
async def TestOnNetworkCommissioning(self, discriminator: int, setuppin: int, nodeid: int, ip_override: str = None):
self.logger.info("Testing discovery")
device = self.TestDiscovery(discriminator=discriminator)
if not device:
self.logger.info("Failed to discover any devices.")
return False
address = device.addresses[0]
if ip_override:
address = ip_override
self.logger.info("Testing commissioning")
if not await self.TestCommissioning(address, setuppin, nodeid):
self.logger.info("Failed to finish commissioning")
return False
return True
def TestUsedTestCommissioner(self):
return self.devCtrl.GetTestCommissionerUsed()
async def TestFailsafe(self, nodeid: int):
self.logger.info("Testing arm failsafe")
self.logger.info("Setting failsafe on CASE connection")
try:
resp = await self.devCtrl.SendCommand(nodeid, 0,
Clusters.GeneralCommissioning.Commands.ArmFailSafe(expiryLengthSeconds=60, breadcrumb=1))
except IM.InteractionModelError as ex:
self.logger.error(
"Failed to send arm failsafe command error is {}".format(ex.status))
return False
if resp.errorCode is not Clusters.GeneralCommissioning.Enums.CommissioningErrorEnum.kOk:
self.logger.error(
"Incorrect response received from arm failsafe - wanted OK, received {}".format(resp))
return False
self.logger.info(
"Attempting to open basic commissioning window - this should fail since the failsafe is armed")
try:
await self.devCtrl.SendCommand(
nodeid,
0,
Clusters.AdministratorCommissioning.Commands.OpenBasicCommissioningWindow(180),
timedRequestTimeoutMs=10000
)
# we actually want the exception here because we want to see a failure, so return False here
self.logger.error(
'Incorrectly succeeded in opening basic commissioning window')
return False
except IM.InteractionModelError:
pass
# TODO:
''' Pipe through the commissioning window opener so we can test enhanced properly.
The pake verifier is just garbage because none of of the functions to calculate
it or serialize it are available right now. However, this command should fail BEFORE that becomes an issue.
'''
discriminator = 1111
salt = secrets.token_bytes(16)
iterations = 2000
# not the right size or the right contents, but it won't matter
verifier = secrets.token_bytes(32)
self.logger.info(
"Attempting to open enhanced commissioning window - this should fail since the failsafe is armed")
try:
await self.devCtrl.SendCommand(
nodeid, 0, Clusters.AdministratorCommissioning.Commands.OpenCommissioningWindow(
commissioningTimeout=180,
PAKEPasscodeVerifier=verifier,
discriminator=discriminator,
iterations=iterations,
salt=salt), timedRequestTimeoutMs=10000)
# we actually want the exception here because we want to see a failure, so return False here
self.logger.error(
'Incorrectly succeeded in opening enhanced commissioning window')
return False
except IM.InteractionModelError:
pass
self.logger.info("Disarming failsafe on CASE connection")
try:
resp = await self.devCtrl.SendCommand(nodeid, 0,
Clusters.GeneralCommissioning.Commands.ArmFailSafe(expiryLengthSeconds=0, breadcrumb=1))
except IM.InteractionModelError as ex:
self.logger.error(
"Failed to send arm failsafe command error is {}".format(ex.status))
return False
self.logger.info(
"Opening Commissioning Window - this should succeed since the failsafe was just disarmed")
try:
await self.devCtrl.SendCommand(
nodeid,
0,
Clusters.AdministratorCommissioning.Commands.OpenBasicCommissioningWindow(180),
timedRequestTimeoutMs=10000
)
except Exception:
self.logger.error(
'Failed to open commissioning window after disarming failsafe')
return False
self.logger.info(
"Attempting to arm failsafe over CASE - this should fail since the commissioning window is open")
try:
resp = await self.devCtrl.SendCommand(nodeid, 0,
Clusters.GeneralCommissioning.Commands.ArmFailSafe(expiryLengthSeconds=60, breadcrumb=1))
except IM.InteractionModelError as ex:
self.logger.error(
"Failed to send arm failsafe command error is {}".format(ex.status))
return False
if resp.errorCode is Clusters.GeneralCommissioning.Enums.CommissioningErrorEnum.kBusyWithOtherAdmin:
return True
return False
async def TestControllerCATValues(self, nodeid: int):
''' This tests controllers using CAT Values
'''
# Allocate a new controller instance with a CAT tag.
newControllers = await CommissioningBuildingBlocks.CreateControllersOnFabric(
fabricAdmin=self.fabricAdmin,
adminDevCtrl=self.devCtrl,
controllerNodeIds=[300],
targetNodeId=nodeid,
privilege=None, catTags=[0x0001_0001])
# Read out an attribute using the new controller. It has no privileges, so this should fail with an UnsupportedAccess error.
res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)])
if (res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess):
self.logger.error(f"1: Received data instead of an error:{res}")
return False
# Grant the new controller privilege by adding the CAT tag to the subject.
await CommissioningBuildingBlocks.GrantPrivilege(
adminCtrl=self.devCtrl,
grantedCtrl=newControllers[0],
privilege=Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum.kAdminister,
targetNodeId=nodeid, targetCatTags=[0x0001_0001])
# Read out the attribute again - this time, it should succeed.
res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)])
if (not isinstance(res[0][
Clusters.AccessControl][
Clusters.AccessControl.Attributes.Acl][0], Clusters.AccessControl.Structs.AccessControlEntryStruct)):
self.logger.error(f"2: Received something other than data:{res}")
return False
# Reset the privilege back to pre-test.
await CommissioningBuildingBlocks.GrantPrivilege(
adminCtrl=self.devCtrl,
grantedCtrl=newControllers[0],
privilege=None,
targetNodeId=nodeid
)
newControllers[0].Shutdown()
return True
async def TestMultiControllerFabric(self, nodeid: int):
''' This tests having multiple controller instances on the same fabric.
'''
# Create two new controllers on the same fabric with no privilege on the target node.
newControllers = await CommissioningBuildingBlocks.CreateControllersOnFabric(
fabricAdmin=self.fabricAdmin,
adminDevCtrl=self.devCtrl,
controllerNodeIds=[100, 200],
targetNodeId=nodeid,
privilege=None
)
#
# Read out the ACL list from one of the newly minted controllers which has no access. This should return an IM error.
#
res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)])
if (res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess):
self.logger.error(f"1: Received data instead of an error:{res}")
return False
#
# Read out the ACL list from an existing controller with admin privileges. This should return back valid data.
# Doing this ensures that we're not somehow aliasing the CASE sessions.
#
res = await self.devCtrl.ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)])
if (not isinstance(res[0][
Clusters.AccessControl][
Clusters.AccessControl.Attributes.Acl][0], Clusters.AccessControl.Structs.AccessControlEntryStruct)):
self.logger.error(f"2: Received something other than data:{res}")
return False
#
# Re-do the previous read from the unprivileged controller
# just to do an ABA test to prove we haven't switched the CASE sessions
# under-neath.
#
res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)])
if (res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess):
self.logger.error(f"3: Received data instead of an error:{res}")
return False
#
# Grant the new controller admin privileges. Reading out the ACL cluster should now yield data.
#
await CommissioningBuildingBlocks.GrantPrivilege(
adminCtrl=self.devCtrl,
grantedCtrl=newControllers[0],
privilege=Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum.kAdminister,
targetNodeId=nodeid
)
res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)])
if (not isinstance(res[0][
Clusters.AccessControl][
Clusters.AccessControl.Attributes.Acl][0], Clusters.AccessControl.Structs.AccessControlEntryStruct)):
self.logger.error(f"4: Received something other than data:{res}")
return False
#
# Grant the second new controller admin privileges as well. Reading out the ACL cluster should now yield data.
#
await CommissioningBuildingBlocks.GrantPrivilege(
adminCtrl=self.devCtrl,
grantedCtrl=newControllers[1],
privilege=Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum.kAdminister,
targetNodeId=nodeid
)
res = await newControllers[1].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)])
if (not isinstance(res[0][
Clusters.AccessControl][
Clusters.AccessControl.Attributes.Acl][0], Clusters.AccessControl.Structs.AccessControlEntryStruct)):
self.logger.error(f"5: Received something other than data:{res}")
return False
#
# Grant the second new controller just view privilege. Reading out the ACL cluster should return no data.
#
await CommissioningBuildingBlocks.GrantPrivilege(
adminCtrl=self.devCtrl,
grantedCtrl=newControllers[1],
privilege=Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum.kView,
targetNodeId=nodeid)
res = await newControllers[1].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)])
if (res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess):
self.logger.error(f"6: Received data5 instead of an error:{res}")
return False
#
# Read the Basic cluster from the 2nd controller. This is possible with just view privileges.
#
res = await newControllers[1].ReadAttribute(nodeid=nodeid,
attributes=[(0, Clusters.BasicInformation.Attributes.ClusterRevision)])
if (not isinstance(res[0][
Clusters.BasicInformation][
Clusters.BasicInformation.Attributes.ClusterRevision], Clusters.BasicInformation.Attributes.ClusterRevision.attribute_type.Type)):
self.logger.error(f"7: Received something other than data:{res}")
return False
newControllers[0].Shutdown()
newControllers[1].Shutdown()
return True
async def TestAddUpdateRemoveFabric(self, nodeid: int):
logger.info("Testing AddNOC, UpdateNOC and RemoveFabric")
self.logger.info("Waiting for attribute read for CommissionedFabrics")
startOfTestFabricCount = await self._GetCommissonedFabricCount(nodeid)
tempCertificateAuthority = self.certificateAuthorityManager.NewCertificateAuthority()
tempFabric = tempCertificateAuthority.NewFabricAdmin(vendorId=0xFFF1, fabricId=1)
tempDevCtrl = tempFabric.NewController(self.controllerNodeId, self.paaTrustStorePath)
self.logger.info("Starting AddNOC using same node ID")
if not await CommissioningBuildingBlocks.AddNOCForNewFabricFromExisting(self.devCtrl, tempDevCtrl, nodeid, nodeid):
self.logger.error("AddNOC failed")
return False
expectedFabricCountUntilRemoveFabric = startOfTestFabricCount + 1
if expectedFabricCountUntilRemoveFabric != await self._GetCommissonedFabricCount(nodeid):
self.logger.error("Expected commissioned fabric count to change after AddNOC")
return False
self.logger.info("Starting UpdateNOC using same node ID")
if not await CommissioningBuildingBlocks.UpdateNOC(tempDevCtrl, nodeid, nodeid):
self.logger.error("UpdateNOC using same node ID failed")
return False
if expectedFabricCountUntilRemoveFabric != await self._GetCommissonedFabricCount(nodeid):
self.logger.error("Expected commissioned fabric count to remain unchanged after UpdateNOC")
return False
self.logger.info("Starting UpdateNOC using different node ID")
newNodeIdForUpdateNoc = nodeid + 1
if not await CommissioningBuildingBlocks.UpdateNOC(tempDevCtrl, nodeid, newNodeIdForUpdateNoc):
self.logger.error("UpdateNOC using different node ID failed")
return False
if expectedFabricCountUntilRemoveFabric != await self._GetCommissonedFabricCount(nodeid):
self.logger.error("Expected commissioned fabric count to remain unchanged after UpdateNOC with new node ID")
return False
# TODO Read using old node ID and expect that it fails.
currentFabricIndexResponse = await tempDevCtrl.ReadAttribute(
newNodeIdForUpdateNoc,
[(Clusters.OperationalCredentials.Attributes.CurrentFabricIndex)]
)
updatedNOCFabricIndex = currentFabricIndexResponse[0][Clusters.OperationalCredentials][
Clusters.OperationalCredentials.Attributes.CurrentFabricIndex]
# Remove Fabric Response
await tempDevCtrl.SendCommand(
newNodeIdForUpdateNoc, 0,
Clusters.OperationalCredentials.Commands.RemoveFabric(updatedNOCFabricIndex))
if startOfTestFabricCount != await self._GetCommissonedFabricCount(nodeid):
self.logger.error("Expected fabric count to be the same at the end of test as when it started")
return False
tempDevCtrl.Shutdown()
tempFabric.Shutdown()
return True
async def TestCaseEviction(self, nodeid: int):
self.logger.info("Testing CASE eviction")
minimumCASESessionsPerFabric = 3
minimumSupportedFabrics = 16
#
# This test exercises the ability to allocate more sessions than are supported in the
# pool configuration. By going beyond (minimumSupportedFabrics * minimumCASESessionsPerFabric),
# it starts to test out the eviction logic. This specific test does not validate the specifics
# of eviction, just that allocation and CASE session establishment proceeds successfully on both
# the controller and target.
#
for x in range(minimumSupportedFabrics * minimumCASESessionsPerFabric * 2):
self.devCtrl.CloseSession(nodeid)
await self.devCtrl.ReadAttribute(nodeid, [(Clusters.BasicInformation.Attributes.ClusterRevision)])
self.logger.info("Testing CASE defunct logic")
#
# This tests establishes a subscription on a given CASE session, then marks it defunct (to simulate
# encountering a transport timeout on the session).
#
# Then, we write to the attribute that was subscribed to from a *different* fabric and check to ensure we still get a report
# on the sub we established previously. Since it was just marked defunct, it should return back to being
# active and a report should get delivered.
#
sawValueChangeEvent = asyncio.Event()
loop = asyncio.get_running_loop()
def OnValueChange(path: Attribute.TypedAttributePath, transaction: Attribute.SubscriptionTransaction) -> None:
self.logger.info("Saw value change!")
if (path.AttributeType == Clusters.UnitTesting.Attributes.Int8u and path.Path.EndpointId == 1):
loop.call_soon_threadsafe(sawValueChangeEvent.set)
self.logger.info("Testing CASE defunct logic")
sub = await self.devCtrl.ReadAttribute(nodeid, [(Clusters.UnitTesting.Attributes.Int8u)], reportInterval=(0, 1))
sub.SetAttributeUpdateCallback(OnValueChange)
#
# This marks the session defunct.
#
self.devCtrl.CloseSession(nodeid)
#
# Now write the attribute from fabric2, give it some time before checking if the report
# was received.
#
await self.devCtrl2.WriteAttribute(nodeid, [(1, Clusters.UnitTesting.Attributes.Int8u(4))])
try:
await asyncio.wait_for(sawValueChangeEvent.wait(), 2)
except TimeoutError:
self.logger.error(
"Didn't see value change in time, likely because sub got terminated due to unexpected session eviction!")
return False
finally:
sub.Shutdown()
#
# In this test, we're going to setup a subscription on fabric1 through devCtl, then, constantly keep
# evicting sessions on fabric2 (devCtl2) by cycling through closing sessions followed by issuing a Read. This
# should result in evictions on the server on fabric2, but not affect any sessions on fabric1. To test this,
# we're going to setup a subscription to an attribute prior to the cycling reads, and check at the end of the
# test that it's still valid by writing to an attribute from a *different* fabric, and validating that we see
# the change on the established subscription. That proves that the session from fabric1 is still valid and untouched.
#
self.logger.info("Testing fabric-isolated CASE eviction")
sawValueChangeEvent.clear()
sub = await self.devCtrl.ReadAttribute(nodeid, [(Clusters.UnitTesting.Attributes.Int8u)], reportInterval=(0, 1))
sub.SetAttributeUpdateCallback(OnValueChange)
for x in range(minimumSupportedFabrics * minimumCASESessionsPerFabric * 2):
self.devCtrl2.CloseSession(nodeid)
await self.devCtrl2.ReadAttribute(nodeid, [(Clusters.BasicInformation.Attributes.ClusterRevision)])
#
# Now write the attribute from fabric2, give it some time before checking if the report
# was received. Use a different value from before, so there is an actual change.
#
await self.devCtrl2.WriteAttribute(nodeid, [(1, Clusters.UnitTesting.Attributes.Int8u(5))])
try:
await asyncio.wait_for(sawValueChangeEvent.wait(), 2)
except TimeoutError:
self.logger.error("Didn't see value change in time, likely because sub got terminated due to other fabric (fabric1)")
return False
finally:
sub.Shutdown()
#
# Do the same test again, but reversing the roles of fabric1 and fabric2. And again
# writing a different value, so there is an actual value change.
#
self.logger.info("Testing fabric-isolated CASE eviction (reverse)")
sawValueChangeEvent.clear()
sub = await self.devCtrl2.ReadAttribute(nodeid, [(Clusters.UnitTesting.Attributes.Int8u)], reportInterval=(0, 1))
sub.SetAttributeUpdateCallback(OnValueChange)
for x in range(minimumSupportedFabrics * minimumCASESessionsPerFabric * 2):
self.devCtrl.CloseSession(nodeid)
await self.devCtrl.ReadAttribute(nodeid, [(Clusters.BasicInformation.Attributes.ClusterRevision)])
await self.devCtrl.WriteAttribute(nodeid, [(1, Clusters.UnitTesting.Attributes.Int8u(6))])
try:
await asyncio.wait_for(sawValueChangeEvent.wait(), 2)
except TimeoutError:
self.logger.error("Didn't see value change in time, likely because sub got terminated due to other fabric (fabric2)")
return False
finally:
sub.Shutdown()
return True
async def TestMultiFabric(self, ip: str, setuppin: int, nodeid: int):
self.logger.info("Opening Commissioning Window")
await self.devCtrl.SendCommand(
nodeid,
0,
Clusters.AdministratorCommissioning.Commands.OpenBasicCommissioningWindow(180),
timedRequestTimeoutMs=10000
)
self.logger.info("Creating 2nd Fabric Admin")
self.fabricAdmin2 = self.certificateAuthority.NewFabricAdmin(vendorId=0xFFF1, fabricId=2)
self.logger.info("Creating Device Controller on 2nd Fabric")
self.devCtrl2 = self.fabricAdmin2.NewController(
self.controllerNodeId, self.paaTrustStorePath)
try:
await self.devCtrl2.CommissionIP(ip, setuppin, nodeid)
except ChipStackException:
self.logger.exception(
"Failed to finish key exchange with device {}".format(ip))
return False
#
# Shut-down all the controllers (which will free them up)
#
self.logger.info(
"Shutting down controllers & fabrics and re-initing stack...")
self.certificateAuthorityManager.Shutdown()
self.logger.info("Shutdown completed, starting new controllers...")
self.certificateAuthorityManager = chip.CertificateAuthority.CertificateAuthorityManager(chipStack=self.chipStack)
self.certificateAuthority = self.certificateAuthorityManager.NewCertificateAuthority()
self.fabricAdmin = self.certificateAuthority.NewFabricAdmin(vendorId=0xFFF1, fabricId=1)
fabricAdmin2 = self.certificateAuthority.NewFabricAdmin(vendorId=0xFFF1, fabricId=2)
self.devCtrl = self.fabricAdmin.NewController(
self.controllerNodeId, self.paaTrustStorePath)
self.devCtrl2 = fabricAdmin2.NewController(
self.controllerNodeId, self.paaTrustStorePath)
self.logger.info("Waiting for attribute reads...")
data1 = await self.devCtrl.ReadAttribute(nodeid, [(Clusters.OperationalCredentials.Attributes.NOCs)], fabricFiltered=False)
data2 = await self.devCtrl2.ReadAttribute(nodeid, [(Clusters.OperationalCredentials.Attributes.NOCs)], fabricFiltered=False)
# Read out noclist from each fabric, and each should contain two NOCs.
nocList1 = data1[0][Clusters.OperationalCredentials][Clusters.OperationalCredentials.Attributes.NOCs]
nocList2 = data2[0][Clusters.OperationalCredentials][Clusters.OperationalCredentials.Attributes.NOCs]
if (len(nocList1) != 2 or len(nocList2) != 2):
self.logger.error("Got back invalid nocList")
return False
data1 = await self.devCtrl.ReadAttribute(
nodeid,
[(Clusters.OperationalCredentials.Attributes.CurrentFabricIndex)],
fabricFiltered=False
)
data2 = await self.devCtrl2.ReadAttribute(
nodeid,
[(Clusters.OperationalCredentials.Attributes.CurrentFabricIndex)],
fabricFiltered=False
)
# Read out current fabric from each fabric, and both should be different.
self.currentFabric1 = data1[0][Clusters.OperationalCredentials][
Clusters.OperationalCredentials.Attributes.CurrentFabricIndex]
self.currentFabric2 = data2[0][Clusters.OperationalCredentials][
Clusters.OperationalCredentials.Attributes.CurrentFabricIndex]
if (self.currentFabric1 == self.currentFabric2):
self.logger.error(
"Got back fabric indices that match for two different fabrics!")
return False
self.logger.info("Attribute reads completed...")
return True
async def TestFabricSensitive(self, nodeid: int):
expectedDataFabric1 = [
Clusters.UnitTesting.Structs.TestFabricScoped(),
Clusters.UnitTesting.Structs.TestFabricScoped()
]
expectedDataFabric1[0].fabricIndex = 100
expectedDataFabric1[0].fabricSensitiveInt8u = 33
expectedDataFabric1[0].optionalFabricSensitiveInt8u = 34
expectedDataFabric1[0].nullableFabricSensitiveInt8u = 35
expectedDataFabric1[0].nullableOptionalFabricSensitiveInt8u = Clusters.Types.NullValue
expectedDataFabric1[0].fabricSensitiveCharString = "alpha1"
expectedDataFabric1[0].fabricSensitiveStruct.a = 36
expectedDataFabric1[0].fabricSensitiveInt8uList = [1, 2, 3, 4]
expectedDataFabric1[1].fabricIndex = 100
expectedDataFabric1[1].fabricSensitiveInt8u = 43
expectedDataFabric1[1].optionalFabricSensitiveInt8u = 44
expectedDataFabric1[1].nullableFabricSensitiveInt8u = 45
expectedDataFabric1[1].nullableOptionalFabricSensitiveInt8u = Clusters.Types.NullValue
expectedDataFabric1[1].fabricSensitiveCharString = "alpha2"
expectedDataFabric1[1].fabricSensitiveStruct.a = 46
expectedDataFabric1[1].fabricSensitiveInt8uList = [2, 3, 4, 5]
self.logger.info("Writing data from fabric1...")
await self.devCtrl.WriteAttribute(nodeid, [(1, Clusters.UnitTesting.Attributes.ListFabricScoped(expectedDataFabric1))])
expectedDataFabric2 = copy.deepcopy(expectedDataFabric1)
expectedDataFabric2[0].fabricSensitiveInt8u = 133
expectedDataFabric2[0].optionalFabricSensitiveInt8u = 134
expectedDataFabric2[0].nullableFabricSensitiveInt8u = 135
expectedDataFabric2[0].fabricSensitiveCharString = "beta1"
expectedDataFabric2[0].fabricSensitiveStruct.a = 136
expectedDataFabric2[0].fabricSensitiveInt8uList = [11, 12, 13, 14]
expectedDataFabric2[1].fabricSensitiveInt8u = 143
expectedDataFabric2[1].optionalFabricSensitiveInt8u = 144
expectedDataFabric2[1].nullableFabricSensitiveInt8u = 145
expectedDataFabric2[1].fabricSensitiveCharString = "beta2"
expectedDataFabric2[1].fabricSensitiveStruct.a = 146
expectedDataFabric2[1].fabricSensitiveStruct.f = 147
expectedDataFabric2[1].fabricSensitiveInt8uList = [12, 13, 14, 15]
self.logger.info("Writing data from fabric2...")
await self.devCtrl2.WriteAttribute(nodeid, [(1, Clusters.UnitTesting.Attributes.ListFabricScoped(expectedDataFabric2))])
#
# Now read the data back filtered from fabric1 and ensure it matches.
#
self.logger.info("Reading back data from fabric1...")
data = await self.devCtrl.ReadAttribute(nodeid, [(1, Clusters.UnitTesting.Attributes.ListFabricScoped)])
readListDataFabric1 = data[1][Clusters.UnitTesting][Clusters.UnitTesting.Attributes.ListFabricScoped]
#
# Update the expected data's fabric index to that we just read back
# before we attempt to compare the data
#
expectedDataFabric1[0].fabricIndex = self.currentFabric1
expectedDataFabric1[1].fabricIndex = self.currentFabric1
self.logger.info("Comparing data on fabric1...")
if (expectedDataFabric1 != readListDataFabric1):
raise AssertionError("Got back mismatched data")
self.logger.info("Reading back data from fabric2...")
data = await self.devCtrl2.ReadAttribute(nodeid, [(1, Clusters.UnitTesting.Attributes.ListFabricScoped)])
readListDataFabric2 = data[1][Clusters.UnitTesting][Clusters.UnitTesting.Attributes.ListFabricScoped]
#
# Update the expected data's fabric index to that we just read back
# before we attempt to compare the data
#
expectedDataFabric2[0].fabricIndex = self.currentFabric2
expectedDataFabric2[1].fabricIndex = self.currentFabric2
self.logger.info("Comparing data on fabric2...")
if (expectedDataFabric2 != readListDataFabric2):
raise AssertionError("Got back mismatched data")
self.logger.info(
"Reading back unfiltered data across all fabrics from fabric1...")
def CompareUnfilteredData(accessingFabric, otherFabric, expectedData):
index = 0
self.logger.info(
f"Comparing data from accessing fabric {accessingFabric}...")
for item in readListDataFabric:
if (item.fabricIndex == accessingFabric):
if (index == 2):
raise AssertionError(
"Got back more data than expected")
if (item != expectedData[index]):
raise AssertionError("Got back mismatched data")
index = index + 1
else:
#
# We should not be able to see any fabric sensitive data from the non accessing fabric.
# Aside from the fabric index, everything else in TestFabricScoped is marked sensitive so we should
# only see defaults for that data. Instantiate an instance of that struct
# which should automatically be initialized with defaults and compare that
# against what we got back.
#
expectedDefaultData = Clusters.UnitTesting.Structs.TestFabricScoped()
expectedDefaultData.fabricIndex = otherFabric
if (item != expectedDefaultData):
raise AssertionError("Got back mismatched data")
data = await self.devCtrl.ReadAttribute(nodeid,
[(1, Clusters.UnitTesting.Attributes.ListFabricScoped)], fabricFiltered=False)
readListDataFabric = data[1][Clusters.UnitTesting][Clusters.UnitTesting.Attributes.ListFabricScoped]
CompareUnfilteredData(self.currentFabric1,
self.currentFabric2, expectedDataFabric1)
data = await self.devCtrl2.ReadAttribute(nodeid,
[(1, Clusters.UnitTesting.Attributes.ListFabricScoped)], fabricFiltered=False)
readListDataFabric = data[1][Clusters.UnitTesting][Clusters.UnitTesting.Attributes.ListFabricScoped]
CompareUnfilteredData(self.currentFabric2,
self.currentFabric1, expectedDataFabric2)
self.logger.info("Writing smaller list from alpha (again)")
expectedDataFabric1[0].fabricIndex = 100
expectedDataFabric1[0].fabricSensitiveInt8u = 53
expectedDataFabric1[0].optionalFabricSensitiveInt8u = 54
expectedDataFabric1[0].nullableFabricSensitiveInt8u = 55
expectedDataFabric1[0].nullableOptionalFabricSensitiveInt8u = Clusters.Types.NullValue
expectedDataFabric1[0].fabricSensitiveCharString = "alpha3"
expectedDataFabric1[0].fabricSensitiveStruct.a = 56
expectedDataFabric1[0].fabricSensitiveInt8uList = [51, 52, 53, 54]
expectedDataFabric1.pop(1)