-
Notifications
You must be signed in to change notification settings - Fork 60
refactor: remove nested if statements #355
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Conversation
Test Results: Windows 2 files 2 suites 16s ⏱️ Results for commit 7acc27d. ♻️ This comment has been updated with latest results. |
Test Results: Ubuntu 2 files 2 suites 46s ⏱️ Results for commit 7acc27d. ♻️ This comment has been updated with latest results. |
Test Results: MacOS 4 files 4 suites 31s ⏱️ Results for commit 7acc27d. ♻️ This comment has been updated with latest results. |
aa5f56e to
6360c7b
Compare
6360c7b to
e7ae545
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR refactors nested if statements throughout the codebase to improve readability by combining conditions with logical operators. The changes flatten control flow by using && and || operators to merge multiple condition checks, and in several cases invert logic to handle early returns more efficiently.
Key changes:
- Nested if statements combined into single conditions using logical AND (
&&) operators - Some conditional logic inverted to enable early returns/throws, reducing nesting levels
- Dispose pattern implementations simplified by combining disposal checks
Reviewed changes
Copilot reviewed 43 out of 43 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| StaticConverters.cs | Combined nested enum parsing validation checks |
| HollowConnection.cs | Merged authentication command condition checks |
| Fido2ResetForTest.cs | Combined reset status and PIN setting checks |
| SimpleKeyCollector.cs | Merged null check and retry count validation |
| Fido2InfoTests.cs | Refactored multiple test methods to use inverted logic with early breaks |
| CredMgmtDataTests.cs | Combined credential validation checks and added LINQ for collection comparison |
| YubiOtp.cs | Inverted status check logic and reorganized error handling |
| U2fCommandTests.cs | Combined platform and elevation checks across multiple test classes |
| SimpleU2fTests.cs | Merged Windows elevation checks in test methods |
| SetDeviceInfoTests.cs | Combined platform and elevation checks in constructor |
| SessionRegisterTests.cs | Merged Windows elevation checks in constructor |
| SessionPinTests.cs | Combined platform and elevation checks in constructor |
| PinTests.cs | Merged Windows elevation checks in constructor |
| CommandTests.cs | Combined platform and elevation checks in constructor |
| X500NameBuilder.cs | Merged null check and dictionary lookup |
| BioEnrollTests.cs | Combined bio enrollment sample validation checks |
| RegistrationData.cs | Inverted length validation to enable early throws |
| TouchFingerprintTask.cs | Combined connection type and cancel loading checks |
| StaticKeys.cs | Simplified dispose pattern by combining disposal checks |
| SessionKeys.cs | Simplified dispose pattern by combining disposal checks |
| Session.cs | Simplified dispose pattern by combining disposal checks |
| Scp03Connection.cs | Simplified dispose pattern by combining disposal checks |
| ScpConnection.cs | Simplified dispose pattern by combining disposal checks |
| PivSession.Pinonly.cs | Inverted multiple condition checks to enable early returns |
| PivSession.Pin.cs | Inverted nested checks to enable early returns in retry count changes |
| PivDataObject.cs | Combined data tag validation conditions |
| CardholderUniqueId.cs | Inverted validity checks in multiple helper methods to enable early returns |
| CardCapabilityContainer.cs | Inverted validity check to enable early return |
| PutDataCommand.cs | Combined vendor tag validation and inverted encoding validation |
| GetDataCommand.cs | Combined vendor tag and special tag validation |
| CompleteAuthenticateManagementKeyResponse.cs | Combined TLV reading checks |
| Scp03ApduTransform.cs | Simplified dispose pattern by combining disposal checks |
| OathSession.Password.cs | Combined password protection and verification checks |
| SetDeviceInfoBaseCommand.cs | Combined nullable value and range validation |
| EnumerateRpsGetNextResponse.cs | Combined null checks and validation |
| EnumerateRpsBeginResponse.cs | Reorganized null checks and validation |
| U2fSampleRun.cs | Combined YubiKey selection and menu item execution checks |
| PivSampleRun.cs | Combined YubiKey selection and menu item execution checks |
| SignatureAlgIdConverter.cs | Combined PSS parameter validation conditions |
| PemOperations.cs | Combined length and header verification checks |
| DsaSignatureConverter.cs | Combined TLV reading operations |
| Fido2SampleRun.cs | Combined YubiKey selection and menu item execution checks |
| Fido2SampleRun.Operations.cs | Combined authenticator info and extension checks |
Comments suppressed due to low confidence (3)
Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs:1
- Missing closing brace for the class definition. The file ends at line 241 but the closing brace for the if statement and class are missing.
// Copyright 2025 Yubico AB
Yubico.YubiKey/src/Yubico/YubiKey/Scp03/SessionKeys.cs:65
- Missing closing brace for the class definition. The file ends at line 69 but the closing brace for the if statement and class are missing.
if (!_disposed && disposing)
{
CryptographicOperations.ZeroMemory(_sessionMacKey.AsSpan());
CryptographicOperations.ZeroMemory(_sessionEncryptionKey.AsSpan());
CryptographicOperations.ZeroMemory(_sessionRmacKey.AsSpan());
_disposed = true;
Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs:154
- Missing closing brace for the class definition. The file ends at line 158 but the closing brace for the if statement and class are missing.
if (!_disposed && disposing)
{
Scp03Keys.Dispose();
_session.Dispose();
_disposed = true;
Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs
Show resolved
Hide resolved
Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs
Outdated
Show resolved
Hide resolved
|
|
||
| using TripleDES tripleDes = CryptographyProviders.TripleDesCreator(); | ||
|
|
||
| tripleDes.Mode = CipherMode.ECB; |
Check failure
Code scanning / CodeQL
Encryption using ECB High test
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI about 1 month ago
To fix the flagged issue, replace the use of CipherMode.ECB with CipherMode.CBC in line 97. CBC (Cipher Block Chaining) mode is more secure for general encryption, as it adds randomness through an Initialization Vector (IV). You must supply a valid IV to the encryptor. This requires generating an IV of the correct size for TripleDES (which is 8 bytes). For deterministic testing, you may use a constant IV; for more realistic yet varying tests, generate a random IV.
In this code, the encryptor is created (line 99) with keyBytes and null as the IV (the second argument). For CBC, the IV argument must be a non-null, 8-byte array.
Therefore, in file Yubico.YubiKey/tests/utilities/Yubico/YubiKey/TestUtilities/HollowConnection.cs, update:
- Line 97: Change
CipherMode.ECBtoCipherMode.CBC. - Line 99: Pass an IV of length 8 (e.g., a static IV:
byte[] iv = new byte[8]; // All zero IV for determinism in tests), so replacenullwithiv.
No additional imports are needed, as usage is within the scope of System.Security.Cryptography.
-
Copy modified lines R96-R97 -
Copy modified lines R99-R100
| @@ -93,10 +93,11 @@ | ||
| Array.Copy(data, 14, responseData, 4, 8); | ||
|
|
||
| using TripleDES tripleDes = CryptographyProviders.TripleDesCreator(); | ||
|
|
||
| tripleDes.Mode = CipherMode.ECB; | ||
| tripleDes.Mode = CipherMode.CBC; // Use CBC mode for better security | ||
| tripleDes.Padding = PaddingMode.None; | ||
| using ICryptoTransform encryptor = tripleDes.CreateEncryptor(keyBytes, null); | ||
| byte[] iv = new byte[8]; // Use zero IV for determinism in test code | ||
| using ICryptoTransform encryptor = tripleDes.CreateEncryptor(keyBytes, iv); | ||
| _ = encryptor.TransformBlock(data, 14, 8, responseData, 4); | ||
|
|
||
| var responseApdu = new ResponseApdu(responseData); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't really understand why this comes up now. Nothing was changed inside the if statement
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No worries. It comes up every once in a while with Copilot / CodeQL analysis.
ECB is a part of the TripleDES implementation and critical to certain YubiKey operations, such as within the PIV standard (more)
8655ead to
7acc27d
Compare
Description
Refactors many if statements to make them more readable
Fixes: # https://yubico.atlassian.net/jira/software/c/projects/YESDK/boards/1466?issueType=10004&selectedIssue=YESDK-1494>
Type of change