Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: hasGenericPassword #642

Merged
merged 7 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions KeychainExample/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,16 @@ export default class KeychainExample extends Component {
selectedSecurityIndex: 0,
selectedAccessControlIndex: 0,
selectedRulesIndex: 0,
hasGenericPassword: false,
};

componentDidMount() {
Keychain.getSupportedBiometryType().then((biometryType) => {
this.setState({ biometryType });
});
Keychain.hasGenericPassword().then((hasGenericPassword) => {
this.setState({ hasGenericPassword });
});
}

async save() {
Expand Down Expand Up @@ -334,6 +338,9 @@ export default class KeychainExample extends Component {
</TouchableHighlight>
)}
</View>
<Text style={styles.status}>
hasGenericPassword: {String(this.state.hasGenericPassword)}
</Text>
</View>
</KeyboardAvoidingView>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ describe('Biometrics Access Control', () => {

it('should retrieve username and password after app launch', async () => {
await expect(element(by.text('Keychain Example'))).toExist();
await expect(element(by.text('hasGenericPassword: true'))).toBeVisible();
// Biometric prompt is not available in the IOS simulator
// https://github.com/oblador/react-native-keychain/issues/340
if (device.getPlatform() === 'android') {
Expand Down
1 change: 1 addition & 0 deletions KeychainExample/e2e/testCases/noneAccessControTest.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ describe('None Access Control', () => {

it('should retrieve username and password after app launch', async () => {
await expect(element(by.text('Keychain Example'))).toExist();
await expect(element(by.text('hasGenericPassword: true'))).toBeVisible();
await element(by.text('Load')).tap();
await matchLoadInfo('testUsername', 'testPassword');
});
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
- [Usage](#usage)
- [API](#api)
- [`setGenericPassword(username, password, [{ accessControl, accessible, accessGroup, service, securityLevel }])`](#setgenericpasswordusername-password--accesscontrol-accessible-accessgroup-service-securitylevel-)
- [`hasGenericPassword([{ service }])`](#hasgenericpasswordservice)
- [`getGenericPassword([{ authenticationPrompt, service, accessControl }])`](#getgenericpassword-authenticationprompt-service-accesscontrol-)
- [`resetGenericPassword([{ service }])`](#resetgenericpassword-service-)
- [`getAllGenericPasswordServices()`](#getallgenericpasswordservices)
Expand All @@ -38,7 +39,7 @@
- [`Keychain.STORAGE_TYPE` enum (Android only)](#keychainstorage_type-enum-android-only)
- [`Keychain.SECURITY_RULES` enum (Android only)](#keychainsecurity_rules-enum-android-only)
- [Important Behavior](#important-behavior)
- [Rule 1: Automatic Security Level Upgrade](#rule-1-automatic-security-level-upgrade)
- [Rule 1: Automatic Security Level](#rule-1-automatic-security-level)
- [Manual Installation](#manual-installation)
- [iOS](#ios)
- [Option: Manually](#option-manually)
Expand All @@ -55,6 +56,7 @@
- [Configuring the Android-specific behavior](#configuring-the-android-specific-behavior)
- [iOS Notes](#ios-notes)
- [macOS Catalyst](#macos-catalyst)
- [visionOS](#visionos)
- [Security](#security)
- [Maintainers](#maintainers)
- [For Developers / Contributors](#for-developers--contributors)
Expand Down Expand Up @@ -109,6 +111,10 @@ Both `setGenericPassword` and `setInternetCredentials` are limited to strings on

Will store the username/password combination in the secure storage. Resolves to `{service, storage}` or rejects in case of an error. `storage` - is a name of used internal cipher for saving secret; `service` - name used for storing secret in internal storage (empty string resolved to valid default name).

### `hasGenericPassword([{ service }])`

Will check if the username/password combination is available for service in the secure storage. Resolves to `true` if an entry exists or `false` if it doesn't.

### `getGenericPassword([{ authenticationPrompt, service, accessControl }])`

Will retrieve the username/password combination from the secure storage. Resolves to `{ username, password, service, storage }` if an entry exists or `false` if it doesn't. It will reject only if an unexpected error is encountered like lacking entitlements or permission.
Expand Down
15 changes: 15 additions & 0 deletions android/src/main/java/com/oblador/keychain/KeychainModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,21 @@ public void hasInternetCredentialsForServer(@NonNull final String server,
promise.resolve(results);
}

@ReactMethod
public void hasGenericPasswordForOptions(@Nullable final ReadableMap options,
@NonNull final Promise promise) {
final String service = getServiceOrDefault(options);
final ResultSet resultSet = prefsStorage.getEncryptedEntry(service);

if (resultSet == null) {
Log.e(KEYCHAIN_MODULE, "No entry found for service: " + service);
promise.resolve(false);
return;
}

promise.resolve(true);
}

@ReactMethod
public void setInternetCredentialsForServer(@NonNull final String server,
@NonNull final String username,
Expand Down
33 changes: 33 additions & 0 deletions ios/RNKeychainManager/RNKeychainManager.m
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,39 @@ - (OSStatus)deleteCredentialsForServer:(NSString *)server
return rejectWithError(reject, error);
}

RCT_EXPORT_METHOD(hasGenericPasswordForOptions:(NSDictionary *)options
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSString *service = serviceValue(options);

NSMutableDictionary *queryParts = [[NSMutableDictionary alloc] init];
queryParts[(__bridge NSString *)kSecClass] = (__bridge id)(kSecClassGenericPassword);
queryParts[(__bridge NSString *)kSecAttrService] = service;
queryParts[(__bridge NSString *)kSecMatchLimit] = (__bridge NSString *)kSecMatchLimitOne;

if (@available(iOS 9, *)) {
queryParts[(__bridge NSString *)kSecUseAuthenticationUI] = (__bridge NSString *)kSecUseAuthenticationUIFail;
}

NSDictionary *query = [queryParts copy];

// Look up service in the keychain
OSStatus osStatus = SecItemCopyMatching((__bridge CFDictionaryRef) query, nil);

switch (osStatus) {
case noErr:
case errSecInteractionNotAllowed:
return resolve(@(YES));

case errSecItemNotFound:
return resolve(@(NO));
}

NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:osStatus userInfo:nil];
return rejectWithError(reject, error);
}

RCT_EXPORT_METHOD(getInternetCredentialsForServer:(NSString *)server
withOptions:(NSDictionary * __nullable)options
resolver:(RCTPromiseResolveBlock)resolve
Expand Down
12 changes: 12 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,18 @@ export function getGenericPassword(
return RNKeychainManager.getGenericPasswordForOptions(options);
}

/**
* Checks if we have generic password for `service`.
* @param {string} service Service to fetch generic password for.
* @return {Promise} Resolved to `true` when successful
*/
export function hasGenericPassword(
serviceOrOptions?: string | Options
): Promise<boolean> {
const options = normalizeOptions(serviceOrOptions);
return RNKeychainManager.hasGenericPasswordForOptions(options);
}

/**
* Deletes all generic password keychain entries for `service`.
* @param {object} options An Keychain options object.
Expand Down