Skip to content

Commit 6118f97

Browse files
committed
Validate zigbee/zwave lock migraton indices
1 parent 62294d5 commit 6118f97

8 files changed

Lines changed: 296 additions & 9 deletions

File tree

‎drivers/SmartThings/zigbee-lock/src/legacy-handlers/init.lua‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,7 @@ end
381381

382382
local migrate = function(driver, device, command)
383383
local post_migration_consts = require "lock_utils.constants"
384+
local table_utils = require "lock_utils.tables"
384385
local LockUsers = capabilities.lockUsers
385386
local LockCredentials = capabilities.lockCredentials
386387

@@ -409,16 +410,19 @@ local migrate = function(driver, device, command)
409410
local cached_lock_codes = lock_utils.get_lock_codes(device)
410411
local ordered_code_slots = {}
411412
for code_slot_str, _ in pairs(cached_lock_codes) do
412-
table.insert(ordered_code_slots, tonumber(code_slot_str))
413+
local code_slot = tonumber(code_slot_str)
414+
if code_slot then table.insert(ordered_code_slots, code_slot) end
413415
end
414416
table.sort(ordered_code_slots)
415-
for _, code_slot in ipairs(ordered_code_slots) do
417+
-- Slots that are not valid indices (e.g. slot 0 as a userIndex) are replaced with a valid, unused one,
418+
-- without displacing any slot that is already valid.
419+
local user_indices = table_utils.resolve_indices("users", ordered_code_slots)
420+
local credential_indices = table_utils.resolve_indices("credentials", ordered_code_slots)
421+
for i, code_slot in ipairs(ordered_code_slots) do
416422
local code_name = cached_lock_codes[tostring(code_slot)]
417423
-- cached_lock_codes is formatted as { ["1"] = "Guest 1", ["2"] = "Guest 2" }, etc
418-
if code_slot then
419-
table.insert(users, { userIndex = code_slot, userType = "guest", userName = code_name })
420-
table.insert(credentials, { userIndex = code_slot, credentialIndex = code_slot, credentialType = post_migration_consts.CRED_TYPE_PIN, credentialName = code_name })
421-
end
424+
table.insert(users, { userIndex = user_indices[i], userType = "guest", userName = code_name })
425+
table.insert(credentials, { userIndex = user_indices[i], credentialIndex = credential_indices[i], credentialType = post_migration_consts.CRED_TYPE_PIN, credentialName = code_name })
422426
end
423427
-- manually ensure user/cred state is persisted, then emit events to populate the new capabilities with the migrated data.
424428
device:set_field("persistedUsers", users, { persist = true })

‎drivers/SmartThings/zigbee-lock/src/lock_utils/tables.lua‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,34 @@ function table_utils.next_index(device, table_name)
144144
return idx
145145
end
146146

147+
-- Resolve a list of candidate match_key values for the named table into valid, unique ones.
148+
-- A candidate is valid if it is an integer at or above the table's minimum and not already
149+
-- claimed by an earlier candidate. Valid candidates always keep their value, regardless of the
150+
-- order they appear in; invalid or duplicate candidates are then assigned the lowest unused
151+
-- values, starting at the minimum. Returns a list parallel to `candidates`. Used to sanitize
152+
-- indices when migrating legacy lockCodes data to lockUsers/lockCredentials.
153+
function table_utils.resolve_indices(table_name, candidates)
154+
local def = DEFS[table_name]
155+
local count = candidates.n or #candidates
156+
local occupied, resolved, needs_replacement = {}, {}, {}
157+
for i = 1, count do
158+
local idx = candidates[i]
159+
if math.type(idx) == "integer" and idx >= def.minimum and not occupied[idx] then
160+
occupied[idx] = true
161+
resolved[i] = idx
162+
else
163+
table.insert(needs_replacement, i)
164+
end
165+
end
166+
local next_free = def.minimum
167+
for _, i in ipairs(needs_replacement) do
168+
while occupied[next_free] do next_free = next_free + 1 end
169+
occupied[next_free] = true
170+
resolved[i] = next_free
171+
end
172+
return resolved
173+
end
174+
147175
function table_utils.get_max_entries(device, table_name)
148176
local def = resolve_table_def(device, table_name)
149177
if not def then return end

‎drivers/SmartThings/zigbee-lock/src/test/test_lock_code_slga_migration.lua‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,23 @@ local mock_device = test.mock_device.build_test_zigbee_device(
2929
}
3030
)
3131

32+
local zero_slot_mock_device = test.mock_device.build_test_zigbee_device(
33+
{
34+
profile = t_utils.get_profile_definition("base-lock.yml"),
35+
data = {
36+
lockCodes = json.encode({
37+
["0"] = "Zero",
38+
["1"] = "Zach"
39+
}),
40+
}
41+
}
42+
)
43+
3244
zigbee_test_utils.prepare_zigbee_env_info()
3345
local function test_init()
3446
test.disable_startup_messages()
3547
test.mock_device.add_test_device(mock_device)
48+
test.mock_device.add_test_device(zero_slot_mock_device)
3649
end
3750

3851
test.set_test_init_function(test_init)
@@ -73,4 +86,33 @@ test.register_coroutine_test(
7386
end
7487
)
7588

89+
test.register_coroutine_test(
90+
"Migrate replaces invalid user indices with valid, non-conflicting ones",
91+
function()
92+
test.socket.device_lifecycle:__queue_receive({ zero_slot_mock_device.id, "init" })
93+
test.socket.zigbee:__queue_receive({ zero_slot_mock_device.id, DoorLock.attributes.MinPINCodeLength:build_test_attr_report(zero_slot_mock_device, 5) })
94+
test.socket.zigbee:__queue_receive({ zero_slot_mock_device.id, DoorLock.attributes.MaxPINCodeLength:build_test_attr_report(zero_slot_mock_device, 10) })
95+
test.socket.zigbee:__queue_receive({ zero_slot_mock_device.id, DoorLock.attributes.NumberOfPINUsersSupported:build_test_attr_report(zero_slot_mock_device, 4) })
96+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCodes.minCodeLength(5, { visibility = { displayed = false } })))
97+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCodes.maxCodeLength(10, { visibility = { displayed = false } })))
98+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCodes.maxCodes(4, { visibility = { displayed = false } })))
99+
test.wait_for_events()
100+
test.socket.capability:__queue_receive({ zero_slot_mock_device.id, { capability = capabilities.lockCodes.ID, command = "migrate", args = {} } })
101+
-- slot 0 is a valid credentialIndex but not a valid userIndex (minimum 1). It must not displace slot 1's valid
102+
-- userIndex, so slot 0's user gets the next free value, 2.
103+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCredentials.supportedCredentials({"pin"}, { visibility = { displayed = false } })))
104+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCredentials.minPinCodeLen(5, { visibility = { displayed = false } })))
105+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCredentials.maxPinCodeLen(10, { visibility = { displayed = false } })))
106+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCredentials.pinUsersSupported(4, { visibility = { displayed = false } })))
107+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockUsers.totalUsersSupported(4, { visibility = { displayed = false } })))
108+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockUsers.users({{userIndex=2, userName="Zero", userType="guest"}, {userIndex=1, userName="Zach", userType="guest"}}, { visibility = { displayed = false } })))
109+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCredentials.credentials({{credentialIndex=0, credentialType="pin", userIndex=2, credentialName="Zero"}, {credentialIndex=1, credentialType="pin", userIndex=1, credentialName="Zach"}}, { visibility = { displayed = false } })))
110+
test.socket.capability:__expect_send( zero_slot_mock_device:generate_test_message("main", capabilities.lockCodes.migrated(true, { visibility = { displayed = false } })))
111+
test.socket.zigbee:__expect_send({ zero_slot_mock_device.id, PowerConfiguration.attributes.BatteryPercentageRemaining:read(zero_slot_mock_device) })
112+
test.socket.zigbee:__expect_send({ zero_slot_mock_device.id, DoorLock.attributes.LockState:read(zero_slot_mock_device) })
113+
test.socket.zigbee:__expect_send({ zero_slot_mock_device.id, Alarm.attributes.AlarmCount:read(zero_slot_mock_device) })
114+
test.wait_for_events()
115+
end
116+
)
117+
76118
test.run_registered_tests()

‎drivers/SmartThings/zigbee-lock/src/test/test_lock_credentials_commands.lua‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,83 @@ test.register_coroutine_test(
386386
end
387387
)
388388

389+
test.register_coroutine_test(
390+
"deleteCredential: removes a credential whose userIndex maps to no user",
391+
function()
392+
seed_credentials({ { userIndex = 7, credentialIndex = 1, credentialType = "pin" } })
393+
394+
test.socket.capability:__queue_receive({
395+
mock_device.id,
396+
{ capability = capabilities.lockCredentials.ID, command = "deleteCredential",
397+
args = { 1, "pin" } },
398+
})
399+
400+
test.socket.zigbee:__expect_send({ mock_device.id, DoorLock.attributes.SendPINOverTheAir:write(mock_device, true) })
401+
test.socket.zigbee:__expect_send({ mock_device.id, DoorLock.server.commands.ClearPINCode(mock_device, 1) })
402+
test.wait_for_events()
403+
404+
test.socket.zigbee:__queue_receive({
405+
mock_device.id,
406+
DoorLock.client.commands.ClearPINCodeResponse.build_test_rx(mock_device, ResponseStatus.PASS),
407+
})
408+
409+
test.socket.capability:__expect_send(
410+
mock_device:generate_test_message("main",
411+
capabilities.lockCredentials.credentials({}, { visibility = { displayed = false } }))
412+
)
413+
test.socket.capability:__expect_send(
414+
mock_device:generate_test_message("main",
415+
capabilities.lockCredentials.commandResult(
416+
{ commandName = "deleteCredential", statusCode = "success", credentialIndex = 1, userIndex = 7 },
417+
{ state_change = true, visibility = { displayed = false } }
418+
))
419+
)
420+
test.wait_for_events()
421+
end
422+
)
423+
424+
test.register_coroutine_test(
425+
"deleteCredential: removes a credential whose credentialIndex maps to no credential",
426+
function()
427+
-- the credential exists in state, but the lock has nothing stored in that slot
428+
seed_users({ { userIndex = 3, userName = "Alice", userType = "guest" } })
429+
seed_credentials({ { userIndex = 3, credentialIndex = 3, credentialType = "pin" } })
430+
431+
test.socket.capability:__queue_receive({
432+
mock_device.id,
433+
{ capability = capabilities.lockCredentials.ID, command = "deleteCredential",
434+
args = { 3, "pin" } },
435+
})
436+
437+
test.socket.zigbee:__expect_send({ mock_device.id, DoorLock.attributes.SendPINOverTheAir:write(mock_device, true) })
438+
test.socket.zigbee:__expect_send({ mock_device.id, DoorLock.server.commands.ClearPINCode(mock_device, 3) })
439+
test.wait_for_events()
440+
441+
-- clearing an empty slot succeeds on the lock, so the stale state entry should be removed
442+
test.socket.zigbee:__queue_receive({
443+
mock_device.id,
444+
DoorLock.client.commands.ClearPINCodeResponse.build_test_rx(mock_device, ResponseStatus.PASS),
445+
})
446+
447+
test.socket.capability:__expect_send(
448+
mock_device:generate_test_message("main",
449+
capabilities.lockCredentials.credentials({}, { visibility = { displayed = false } }))
450+
)
451+
test.socket.capability:__expect_send(
452+
mock_device:generate_test_message("main",
453+
capabilities.lockUsers.users({}, { visibility = { displayed = false } }))
454+
)
455+
test.socket.capability:__expect_send(
456+
mock_device:generate_test_message("main",
457+
capabilities.lockCredentials.commandResult(
458+
{ commandName = "deleteCredential", statusCode = "success", credentialIndex = 3, userIndex = 3 },
459+
{ state_change = true, visibility = { displayed = false } }
460+
))
461+
)
462+
test.wait_for_events()
463+
end
464+
)
465+
389466
test.register_coroutine_test(
390467
"deleteCredential: emits failure when the lock returns FAIL",
391468
function()

‎drivers/SmartThings/zwave-lock/src/legacy-handlers/init.lua‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ end
5454
--- @param cmd table
5555
local function migrate(driver, device, cmd)
5656
local LockCodesDefaults = require "st.zwave.defaults.lockCodes"
57+
local table_utils = require "lock_utils.tables"
5758
local get_lock_codes = LockCodesDefaults.get_lock_codes
5859
local lock_users = {}
5960
local lock_credentials = {}
@@ -65,10 +66,19 @@ local function migrate(driver, device, cmd)
6566
end
6667

6768
table.sort(ordered_codes)
69+
-- Slots that are not valid indices (e.g. 0, which means "all users" in Z-Wave, or non-numeric) are replaced with
70+
-- a valid, unused one, without displacing any slot that is already valid.
71+
local user_candidates, credential_candidates = { n = #ordered_codes }, { n = #ordered_codes }
6872
for index = 1, #ordered_codes do
69-
local code_slot, code_name = ordered_codes[index], lock_codes[ ordered_codes[index] ]
70-
table.insert(lock_users, {userIndex = index, userType = "guest", userName = code_name})
71-
table.insert(lock_credentials, {userIndex = index, credentialIndex = tonumber(code_slot), credentialType = "pin"})
73+
user_candidates[index] = index
74+
credential_candidates[index] = tonumber(ordered_codes[index])
75+
end
76+
local user_indices = table_utils.resolve_indices("users", user_candidates)
77+
local credential_indices = table_utils.resolve_indices("credentials", credential_candidates)
78+
for index = 1, #ordered_codes do
79+
local code_name = lock_codes[ ordered_codes[index] ]
80+
table.insert(lock_users, {userIndex = user_indices[index], userType = "guest", userName = code_name})
81+
table.insert(lock_credentials, {userIndex = user_indices[index], credentialIndex = credential_indices[index], credentialType = "pin"})
7282
end
7383
device:emit_event(capabilities.lockCredentials.credentials(lock_credentials, { visibility = { displayed = false } }))
7484
device:emit_event(capabilities.lockUsers.users(lock_users, { visibility = { displayed = false } }))

‎drivers/SmartThings/zwave-lock/src/lock_utils/tables.lua‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,34 @@ function table_utils.next_index(device, table_name)
146146
return idx
147147
end
148148

149+
-- Resolve a list of candidate match_key values for the named table into valid, unique ones.
150+
-- A candidate is valid if it is an integer at or above the table's minimum and not already
151+
-- claimed by an earlier candidate. Valid candidates always keep their value, regardless of the
152+
-- order they appear in; invalid or duplicate candidates are then assigned the lowest unused
153+
-- values, starting at the minimum. Returns a list parallel to `candidates`. Used to sanitize
154+
-- indices when migrating legacy lockCodes data to lockUsers/lockCredentials.
155+
function table_utils.resolve_indices(table_name, candidates)
156+
local def = DEFS[table_name]
157+
local count = candidates.n or #candidates
158+
local occupied, resolved, needs_replacement = {}, {}, {}
159+
for i = 1, count do
160+
local idx = candidates[i]
161+
if math.type(idx) == "integer" and idx >= def.minimum and not occupied[idx] then
162+
occupied[idx] = true
163+
resolved[i] = idx
164+
else
165+
table.insert(needs_replacement, i)
166+
end
167+
end
168+
local next_free = def.minimum
169+
for _, i in ipairs(needs_replacement) do
170+
while occupied[next_free] do next_free = next_free + 1 end
171+
occupied[next_free] = true
172+
resolved[i] = next_free
173+
end
174+
return resolved
175+
end
176+
149177
function table_utils.get_max_entries(device, table_name)
150178
local def = resolve_table_def(device, table_name)
151179
if not def then return end

‎drivers/SmartThings/zwave-lock/src/test/test_lock_code_slga_migration.lua‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,22 @@ test.register_coroutine_test(
9898
end
9999
)
100100

101+
test.register_coroutine_test(
102+
"Migrate replaces invalid credential indices with valid, non-conflicting ones",
103+
function()
104+
init_code_slot(0, "Invalid", mock_device)
105+
init_code_slot(1, "Zach", mock_device)
106+
test.socket.capability:__queue_receive({ mock_device.id, { capability = capabilities.lockCodes.ID, command = "migrate", args = {} } })
107+
-- slot 0 is below the minimum credentialIndex for Z-Wave (1). It must not displace the valid slot 1, so it gets the next free value, 2
108+
test.socket.capability:__expect_send( mock_device:generate_test_message("main", capabilities.lockCredentials.credentials({{credentialIndex=2, credentialType="pin", userIndex=1}, {credentialIndex=1, credentialType="pin", userIndex=2}}, { visibility = { displayed = false } })))
109+
test.socket.capability:__expect_send( mock_device:generate_test_message("main", capabilities.lockUsers.users({{userIndex=1, userName="Invalid", userType="guest"}, {userIndex=2, userName="Zach", userType="guest"}}, { visibility = { displayed = false } })))
110+
test.socket.zwave:__expect_send(UserCode:UsersNumberGet({}):build_test_tx(mock_device.id))
111+
test.socket.capability:__expect_send( mock_device:generate_test_message("main", capabilities.lockCredentials.supportedCredentials({"pin"}, { visibility = { displayed = false } })))
112+
test.socket.capability:__expect_send( mock_device:generate_test_message("main", capabilities.lockCodes.migrated(true, { visibility = { displayed = false } })))
113+
test.wait_for_events()
114+
end
115+
)
116+
101117
test.register_coroutine_test(
102118
"Schlage-Lock device called 'migrate' command, validate codeLength is being properly set",
103119
function()

‎drivers/SmartThings/zwave-lock/src/test/test_lock_credentials_commands.lua‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,88 @@ test.register_coroutine_test(
368368
}
369369
)
370370

371+
test.register_coroutine_test(
372+
"deleteCredential: removes a credential whose userIndex maps to no user",
373+
function()
374+
-- seed via the persistent store, which the driver falls back to when the capability state cache is empty
375+
mock_device:set_field("persistedCredentials",
376+
{ { userIndex = 7, credentialIndex = 1, credentialType = "pin" } }, { persist = true })
377+
378+
test.socket.capability:__queue_receive({
379+
mock_device.id,
380+
{ capability = capabilities.lockCredentials.ID, command = "deleteCredential",
381+
args = { 1, "pin" } },
382+
})
383+
test.socket.zwave:__expect_send(
384+
UserCode:Set({ user_identifier = 1, user_id_status = UserCode.user_id_status.AVAILABLE }):build_test_tx(mock_device.id)
385+
)
386+
test.wait_for_events()
387+
388+
test.socket.zwave:__queue_receive({
389+
mock_device.id,
390+
UserCode:Report({ user_identifier = 1, user_id_status = UserCode.user_id_status.AVAILABLE }),
391+
})
392+
test.socket.capability:__expect_send(
393+
mock_device:generate_test_message("main",
394+
capabilities.lockCredentials.credentials({}, { visibility = { displayed = false } }))
395+
)
396+
test.socket.capability:__expect_send(
397+
mock_device:generate_test_message("main",
398+
capabilities.lockCredentials.commandResult(
399+
{ commandName = "deleteCredential", statusCode = "success", credentialIndex = 1, userIndex = 7 },
400+
{ state_change = true, visibility = { displayed = false } }
401+
))
402+
)
403+
test.wait_for_events()
404+
end,
405+
{
406+
min_api_version = 15
407+
}
408+
)
409+
410+
test.register_coroutine_test(
411+
"deleteCredential: removes a credential whose credentialIndex maps to no credential",
412+
function()
413+
-- the credential exists in state, but the lock has nothing stored in that slot.
414+
-- seed via the persistent store, which the driver falls back to when the capability state cache is empty
415+
mock_device:set_field("persistedUsers",
416+
{ { userIndex = 3, userName = "Alice", userType = "guest" } }, { persist = true })
417+
mock_device:set_field("persistedCredentials",
418+
{ { userIndex = 3, credentialIndex = 3, credentialType = "pin" } }, { persist = true })
419+
420+
test.socket.capability:__queue_receive({
421+
mock_device.id,
422+
{ capability = capabilities.lockCredentials.ID, command = "deleteCredential",
423+
args = { 3, "pin" } },
424+
})
425+
test.socket.zwave:__expect_send(
426+
UserCode:Set({ user_identifier = 3, user_id_status = UserCode.user_id_status.AVAILABLE }):build_test_tx(mock_device.id)
427+
)
428+
test.wait_for_events()
429+
430+
-- the lock reports the slot as available, so the stale credential entry should be removed (the user is kept)
431+
test.socket.zwave:__queue_receive({
432+
mock_device.id,
433+
UserCode:Report({ user_identifier = 3, user_id_status = UserCode.user_id_status.AVAILABLE }),
434+
})
435+
test.socket.capability:__expect_send(
436+
mock_device:generate_test_message("main",
437+
capabilities.lockCredentials.credentials({}, { visibility = { displayed = false } }))
438+
)
439+
test.socket.capability:__expect_send(
440+
mock_device:generate_test_message("main",
441+
capabilities.lockCredentials.commandResult(
442+
{ commandName = "deleteCredential", statusCode = "success", credentialIndex = 3, userIndex = 3 },
443+
{ state_change = true, visibility = { displayed = false } }
444+
))
445+
)
446+
test.wait_for_events()
447+
end,
448+
{
449+
min_api_version = 15
450+
}
451+
)
452+
371453
test.register_coroutine_test(
372454
"deleteCredential: returns failure immediately when the credentialIndex does not exist in the table",
373455
function()

0 commit comments

Comments
 (0)