-
Notifications
You must be signed in to change notification settings - Fork 263
Add Signal API implementation (Provider) #160
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
Open
neelanshsahai
wants to merge
2
commits into
main
Choose a base branch
from
signal_api_provider
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+409
−34
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
9 changes: 9 additions & 0 deletions
9
...rovider/MyVault/app/src/main/java/com/example/android/authentication/myvault/Constants.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package com.example.android.authentication.myvault | ||
|
||
const val NOTIFICATION_CHANNEL_ID = "channel_id" | ||
const val NOTIFICATION_ID = 135 | ||
const val CREDENTIAL_ID = "credentialId" | ||
const val USER_ID = "userId" | ||
const val ACCEPTED_CREDENTIAL_IDS = "allAcceptedCredentialIds" | ||
const val NAME = "name" | ||
const val DISPLAY_NAME = "displayName" |
74 changes: 74 additions & 0 deletions
74
...MyVault/app/src/main/java/com/example/android/authentication/myvault/NotificationUtils.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
package com.example.android.authentication.myvault | ||
|
||
import android.Manifest | ||
import android.app.NotificationChannel | ||
import android.app.NotificationManager | ||
import android.app.PendingIntent | ||
import android.content.ComponentName | ||
import android.content.Context | ||
import android.content.Intent | ||
import android.content.pm.PackageManager | ||
import androidx.core.app.ActivityCompat | ||
import androidx.core.app.NotificationCompat | ||
import androidx.core.app.NotificationManagerCompat | ||
import com.example.android.authentication.myvault.ui.MainActivity | ||
|
||
/** | ||
neelanshsahai marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* Creates and registers a notification channel with the system. | ||
* | ||
* This is a utility extension function that creates a Notification Channel with | ||
* [NotificationManager.IMPORTANCE_HIGH] to show pop-up notification on receiving | ||
* signals from the RP apps | ||
* | ||
* @param channelName The user-visible name of the channel. | ||
* This is displayed in the system's notification settings. | ||
* @param channelDescription The user-visible description of the channel. | ||
* This is displayed in the system's notification settings. | ||
*/ | ||
fun Context.createNotificationChannel( | ||
channelName: String, | ||
channelDescription: String, | ||
) { | ||
val channel = NotificationChannel( | ||
NOTIFICATION_CHANNEL_ID, | ||
channelName, | ||
NotificationManager.IMPORTANCE_HIGH | ||
).apply { | ||
description = channelDescription | ||
} | ||
|
||
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager | ||
notificationManager.createNotificationChannel(channel) | ||
} | ||
|
||
/** | ||
* Utility extension function that displays a system notification with the given title and content. | ||
* | ||
* @param title The title of the notification. | ||
* @param content The main content text of the notification. | ||
*/ | ||
fun Context.showNotification( | ||
title: String, | ||
content: String, | ||
) { | ||
val intent = Intent(this, MainActivity::class.java) | ||
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE) | ||
|
||
val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) | ||
.setSmallIcon(R.drawable.android_secure) | ||
.setContentTitle(title) | ||
.setContentText(content) | ||
.setPriority(NotificationCompat.PRIORITY_MAX) | ||
.setContentIntent(pendingIntent) | ||
.setAutoCancel(true) | ||
|
||
with(NotificationManagerCompat.from(this)) { | ||
if (ActivityCompat.checkSelfPermission( | ||
this@showNotification, | ||
Manifest.permission.POST_NOTIFICATIONS | ||
) != PackageManager.PERMISSION_GRANTED) { | ||
return@with | ||
} | ||
notify(NOTIFICATION_ID, builder.build()) | ||
} | ||
} |
225 changes: 225 additions & 0 deletions
225
...rc/main/java/com/example/android/authentication/myvault/data/CredentialProviderService.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,225 @@ | ||
package com.example.android.authentication.myvault.data | ||
neelanshsahai marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
import android.annotation.SuppressLint | ||
import android.util.Log | ||
import androidx.credentials.SignalAllAcceptedCredentialIdsRequest | ||
import androidx.credentials.SignalCurrentUserDetailsRequest | ||
import androidx.credentials.SignalUnknownCredentialRequest | ||
import androidx.credentials.providerevents.service.CredentialProviderEventsService | ||
import androidx.credentials.providerevents.signal.ProviderSignalCredentialStateCallback | ||
import androidx.credentials.providerevents.signal.ProviderSignalCredentialStateRequest | ||
import com.example.android.authentication.myvault.ACCEPTED_CREDENTIAL_IDS | ||
import com.example.android.authentication.myvault.AppDependencies | ||
import com.example.android.authentication.myvault.CREDENTIAL_ID | ||
import com.example.android.authentication.myvault.DISPLAY_NAME | ||
import com.example.android.authentication.myvault.NAME | ||
import com.example.android.authentication.myvault.R | ||
import com.example.android.authentication.myvault.USER_ID | ||
import com.example.android.authentication.myvault.showNotification | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.withContext | ||
import org.json.JSONArray | ||
import org.json.JSONObject | ||
|
||
/** | ||
* A service that listens to credential provider events triggered by the relying parties | ||
* | ||
* This service is responsible for handling signals related to credential state changes in the RPs, | ||
* such as when a credential is no longer valid, when a list of accepted credentials is accepted, | ||
* or when current user details change for credentials | ||
*/ | ||
class CredentialProviderService: CredentialProviderEventsService() { | ||
private val dataSource = AppDependencies.credentialsDataSource | ||
private val coroutineScope = AppDependencies.coroutineScope | ||
|
||
/** | ||
* Called when the system or another credential provider signals a change in credential state. | ||
* | ||
* This method inspects the type of [ProviderSignalCredentialStateRequest] and delegates | ||
* to the appropriate handler function to update the local data store and show a notification. | ||
* After processing the signal, {@link ProviderSignalCredentialStateCallback#onSignalConsumed()} | ||
* is called to acknowledge receipt of the signal. | ||
* | ||
* The {@link SuppressLint("RestrictedApi")} annotation is used because this method | ||
* interacts with APIs from the {@code androidx.credentials} library that might be | ||
* marked as restricted for extension by library developers. | ||
* | ||
* @param request The request containing details about the credential state signal. | ||
* @param callback The callback to be invoked after the signal has been processed. | ||
*/ | ||
@SuppressLint("RestrictedApi") | ||
override fun onSignalCredentialStateRequest( | ||
request: ProviderSignalCredentialStateRequest, | ||
callback: ProviderSignalCredentialStateCallback, | ||
) { | ||
when (request.callingRequest) { | ||
is SignalUnknownCredentialRequest -> { | ||
updateDataOnSignalAndShowNotification( | ||
handleRequest = ::handleUnknownCredentialRequest, | ||
requestJson = request.callingRequest.requestJson, | ||
notificationTitle = getString(R.string.credential_deletion), | ||
notificationContent = getString(R.string.unknown_signal_message) | ||
) | ||
} | ||
|
||
is SignalAllAcceptedCredentialIdsRequest -> { | ||
updateDataOnSignalAndShowNotification( | ||
handleRequest = ::handleAcceptedCredentialsRequest, | ||
requestJson = request.callingRequest.requestJson, | ||
notificationTitle = getString(R.string.credentials_list_updation), | ||
notificationContent = getString(R.string.all_accepted_signal_message) | ||
) | ||
} | ||
|
||
is SignalCurrentUserDetailsRequest -> { | ||
updateDataOnSignalAndShowNotification( | ||
handleRequest = ::handleCurrentUserDetailRequest, | ||
requestJson = request.callingRequest.requestJson, | ||
notificationTitle = getString(R.string.user_details_updation), | ||
notificationContent = getString(R.string.current_user_signal_message) | ||
) | ||
} | ||
|
||
else -> { } | ||
} | ||
|
||
callback.onSignalConsumed() | ||
} | ||
|
||
/** | ||
* A helper function to asynchronously handle a credential state update request, | ||
* update the data source, and then show a system notification on the main thread. | ||
* | ||
* @param handleRequest A suspend function that takes the request JSON string and processes it. | ||
* This function is responsible for interacting with the data source. | ||
* @param requestJson The JSON string payload from the original credential signal request. | ||
* @param notificationTitle The title to be used for the system notification. | ||
* @param notificationContent The content text for the system notification. | ||
*/ | ||
private fun updateDataOnSignalAndShowNotification( | ||
handleRequest: suspend (String) -> Boolean, | ||
requestJson: String, | ||
notificationTitle: String, | ||
notificationContent: String, | ||
) { | ||
coroutineScope.launch { | ||
val success = handleRequest(requestJson) | ||
withContext(Dispatchers.Main) { | ||
if (success) { | ||
showNotification( | ||
title = notificationTitle, | ||
content = notificationContent, | ||
) | ||
} | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Handles a [SignalUnknownCredentialRequest] by parsing the credential ID | ||
* from the request JSON and attempting to hide the corresponding passkey in the data source. | ||
* | ||
* "Hiding" a passkey typically means marking it as inactive or not to be suggested | ||
* for autofill, often because the system has indicated it's no longer valid | ||
* (e.g., deleted from the authenticator). | ||
* | ||
* @param requestJson The JSON string payload from the [SignalUnknownCredentialRequest]. | ||
* Expected to contain a {@code CREDENTIAL_ID}. | ||
*/ | ||
private suspend fun handleUnknownCredentialRequest(requestJson: String): Boolean { | ||
try { | ||
val credentialId = JSONObject(requestJson).getString(CREDENTIAL_ID) | ||
neelanshsahai marked this conversation as resolved.
Show resolved
Hide resolved
|
||
dataSource.getPasskey(credentialId)?.let { | ||
// Currently hiding the passkey on UnknownSignal for testing purpose | ||
// If the business logc requires deletion, please add deletion code instead | ||
dataSource.hidePasskey(it) | ||
} | ||
return true | ||
} catch (e: Exception) { | ||
Log.e(getString(R.string.failed_to_handle_unknowncredentialrequest), e.toString()) | ||
return false | ||
} | ||
} | ||
|
||
/** | ||
* Handles a {@link SignalAllAcceptedCredentialIdsRequest} by synchronizing the visibility | ||
* state of passkeys for a specific user. | ||
* | ||
* It retrieves all current passkeys for the user from the data source. Then, it compares | ||
* this list against the list of accepted credential IDs provided in the signal. | ||
* Passkeys whose IDs are in the accepted list are unhidden (made active). | ||
* Passkeys whose IDs are not in the accepted list are hidden (made inactive). | ||
* | ||
* This is useful for scenarios where the system provides an authoritative list of | ||
* credentials that are currently valid or preferred for a user. | ||
* | ||
* @param requestJson The JSON string payload from the {@link SignalAllAcceptedCredentialIdsRequest}. | ||
* Expected to contain a {@code USER_ID} and {@code ACCEPTED_CREDENTIAL_IDS} | ||
* (which can be a string or a JSON array of strings). | ||
*/ | ||
private suspend fun handleAcceptedCredentialsRequest(requestJson: String): Boolean { | ||
try { | ||
val request = JSONObject(requestJson) | ||
val userId = request.getString(USER_ID) | ||
val listCurrentPasskeysForUser = dataSource.getAllPasskeysForUser(userId) ?: emptyList() | ||
val listAllAcceptedCredIds = mutableListOf<String>() | ||
when (val value = request.get(ACCEPTED_CREDENTIAL_IDS)) { | ||
is String -> listAllAcceptedCredIds.add(value) | ||
is JSONArray -> { | ||
for (i in 0 until value.length()) { | ||
val item = value.get(i) | ||
if (item is String) { | ||
listAllAcceptedCredIds.add(item) | ||
} | ||
} | ||
} | ||
|
||
else -> { /*do nothing*/ } | ||
} | ||
|
||
for (key in listCurrentPasskeysForUser) { | ||
if (listAllAcceptedCredIds.contains(key.credId)) { | ||
dataSource.unhidePasskey(key) | ||
} else { | ||
dataSource.hidePasskey(key) | ||
} | ||
} | ||
return true | ||
} catch (e: Exception) { | ||
Log.e(getString(R.string.failed_to_handle_acceptedcredentialsrequest), e.toString()) | ||
return false | ||
} | ||
} | ||
|
||
/** | ||
* Handles a {@link SignalCurrentUserDetailsRequest} by updating the username and display name | ||
* for all passkeys associated with a given user ID. | ||
* | ||
* This is useful when the user's profile information (like name or display name) | ||
* changes elsewhere, and the credential provider needs to reflect these changes | ||
* in its stored passkey data. | ||
* | ||
* @param requestJson The JSON string payload from the {@link SignalCurrentUserDetailsRequest}. | ||
* Expected to contain {@code USER_ID}, {@code NAME}, and {@code DISPLAY_NAME}. | ||
*/ | ||
private suspend fun handleCurrentUserDetailRequest(requestJson: String): Boolean { | ||
try { | ||
val request = JSONObject(requestJson) | ||
val userId = request.getString(USER_ID) | ||
val updatedName = request.getString(NAME) | ||
val updatedDisplayName = request.getString(DISPLAY_NAME) | ||
val listPasskeys = dataSource.getAllPasskeysForUser(userId) ?: emptyList() | ||
// Update user details for each passkey | ||
for (key in listPasskeys) { | ||
val newPasskeyItem = | ||
key.copy(username = updatedName, displayName = updatedDisplayName) | ||
dataSource.updatePasskey(newPasskeyItem) | ||
} | ||
return true | ||
} catch (e: Exception) { | ||
Log.e(getString(R.string.failed_to_handle_currentuserdetailrequest), e.toString()) | ||
return false | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.