Search in sources :

Example 1 with CommandParameters

use of com.microsoft.identity.common.internal.commands.parameters.CommandParameters in project microsoft-authentication-library-common-for-android by AzureAD.

the class CommandDispatcher method beginInteractive.

public static void beginInteractive(final InteractiveTokenCommand command) {
    final String methodName = ":beginInteractive";
    synchronized (sLock) {
        final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(command.getParameters().getAndroidApplicationContext());
        // Cancel interactive request if authorizationInCurrentTask() returns true OR this is a broker request.
        if (LibraryConfiguration.getInstance().isAuthorizationInCurrentTask() || command.getParameters() instanceof BrokerInteractiveTokenCommandParameters) {
            // Send a broadcast to cancel if any active auth request is present.
            localBroadcastManager.sendBroadcast(new Intent(CANCEL_INTERACTIVE_REQUEST));
        }
        sInteractiveExecutor.execute(new Runnable() {

            @Override
            public void run() {
                final CommandParameters commandParameters = command.getParameters();
                final String correlationId = initializeDiagnosticContext(commandParameters.getCorrelationId(), commandParameters.getSdkType() == null ? SdkType.UNKNOWN.getProductName() : commandParameters.getSdkType().getProductName(), commandParameters.getSdkVersion());
                try {
                    // set correlation id on parameters as it may not already be set
                    commandParameters.setCorrelationId(correlationId);
                    logParameters(TAG + methodName, correlationId, commandParameters, command.getPublicApiId());
                    EstsTelemetry.getInstance().initTelemetryForCommand(command);
                    EstsTelemetry.getInstance().emitApiId(command.getPublicApiId());
                    final BroadcastReceiver resultReceiver = new BroadcastReceiver() {

                        @Override
                        public void onReceive(Context context, Intent intent) {
                            completeInteractive(intent);
                        }
                    };
                    CommandResult commandResult;
                    Handler handler = new Handler(Looper.getMainLooper());
                    localBroadcastManager.registerReceiver(resultReceiver, new IntentFilter(RETURN_INTERACTIVE_REQUEST_RESULT));
                    sCommand = command;
                    // Try executing request
                    commandResult = executeCommand(command);
                    sCommand = null;
                    localBroadcastManager.unregisterReceiver(resultReceiver);
                    // set correlation id on Local Authentication Result
                    setCorrelationIdOnResult(commandResult, correlationId);
                    Logger.info(TAG + methodName, "Completed interactive request for correlation id : **" + correlationId + ", with the status : " + commandResult.getStatus().getLogStatus());
                    EstsTelemetry.getInstance().flush(command, commandResult);
                    Telemetry.getInstance().flush(correlationId);
                    returnCommandResult(command, commandResult, handler);
                } finally {
                    DiagnosticContext.clear();
                }
            }
        });
    }
}
Also used : DiagnosticContext(com.microsoft.identity.common.logging.DiagnosticContext) Context(android.content.Context) IntentFilter(android.content.IntentFilter) Handler(android.os.Handler) Intent(android.content.Intent) CommandParameters(com.microsoft.identity.common.internal.commands.parameters.CommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) BroadcastReceiver(android.content.BroadcastReceiver) LocalBroadcastManager(androidx.localbroadcastmanager.content.LocalBroadcastManager) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters)

Example 2 with CommandParameters

use of com.microsoft.identity.common.internal.commands.parameters.CommandParameters in project microsoft-authentication-library-common-for-android by AzureAD.

the class CommandDispatcher method submitSilentReturningFuture.

/**
 * submitSilent - Run a command using the silent thread pool, and return the future governing it.
 *
 * @param command
 */
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
public static FinalizableResultFuture<CommandResult> submitSilentReturningFuture(@SuppressWarnings(WarningType.rawtype_warning) @NonNull final BaseCommand command) {
    final String methodName = ":submitSilent";
    final CommandParameters commandParameters = command.getParameters();
    final String correlationId = initializeDiagnosticContext(commandParameters.getCorrelationId(), commandParameters.getSdkType() == null ? SdkType.UNKNOWN.getProductName() : commandParameters.getSdkType().getProductName(), commandParameters.getSdkVersion());
    // set correlation id on parameters as it may not already be set
    commandParameters.setCorrelationId(correlationId);
    logParameters(TAG + methodName, correlationId, commandParameters, command.getPublicApiId());
    final Handler handler = new Handler(Looper.getMainLooper());
    synchronized (mapAccessLock) {
        final FinalizableResultFuture<CommandResult> finalFuture;
        if (command.isEligibleForCaching()) {
            FinalizableResultFuture<CommandResult> future = sExecutingCommandMap.get(command);
            if (null == future) {
                future = new FinalizableResultFuture<>();
                final FinalizableResultFuture<CommandResult> putValue = sExecutingCommandMap.putIfAbsent(command, future);
                if (null == putValue) {
                    // our value was inserted.
                    future.whenComplete(getCommandResultConsumer(command, handler));
                } else {
                    // Our value was not inserted, grab the one that was and hang a new listener off it
                    putValue.whenComplete(getCommandResultConsumer(command, handler));
                    return putValue;
                }
            } else {
                future.whenComplete(getCommandResultConsumer(command, handler));
                return future;
            }
            finalFuture = future;
        } else {
            finalFuture = new FinalizableResultFuture<>();
            finalFuture.whenComplete(getCommandResultConsumer(command, handler));
        }
        sSilentExecutor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    // initializing again since the request is transferred to a different thread pool
                    initializeDiagnosticContext(correlationId, commandParameters.getSdkType() == null ? SdkType.UNKNOWN.getProductName() : commandParameters.getSdkType().getProductName(), commandParameters.getSdkVersion());
                    EstsTelemetry.getInstance().initTelemetryForCommand(command);
                    EstsTelemetry.getInstance().emitApiId(command.getPublicApiId());
                    CommandResult commandResult = null;
                    // Log operation parameters
                    if (command.getParameters() instanceof SilentTokenCommandParameters) {
                        EstsTelemetry.getInstance().emitForceRefresh(((SilentTokenCommandParameters) command.getParameters()).isForceRefresh());
                    }
                    // If nothing in cache, execute the command and cache the result
                    if (commandResult == null) {
                        commandResult = executeCommand(command);
                        // Disabling throttling ADO:1383033
                        // cacheCommandResult(command, commandResult);
                        Logger.info(TAG + methodName, "Completed silent request as owner for correlation id : **" + correlationId + ", with the status : " + commandResult.getStatus().getLogStatus() + " is cacheable : " + command.isEligibleForCaching());
                    } else {
                        Logger.info(TAG + methodName, "Silent command result returned from cache for correlation id : " + correlationId + " having status : " + commandResult.getStatus().getLogStatus());
                        // Added to keep the original correlation id intact, and to not let it mutate with the cascading requests hitting the cache.
                        commandResult = new CommandResult(commandResult.getStatus(), commandResult.getResult(), commandResult.getCorrelationId());
                    }
                    // TODO 1309671 : change required to stop the LocalAuthenticationResult object from mutating in cases of cached command.
                    // set correlation id on Local Authentication Result
                    setCorrelationIdOnResult(commandResult, correlationId);
                    Telemetry.getInstance().flush(correlationId);
                    EstsTelemetry.getInstance().flush(command, commandResult);
                    finalFuture.setResult(commandResult);
                } catch (final Throwable t) {
                    Logger.info(TAG + methodName, "Request encountered an exception with correlation id : **" + correlationId);
                    finalFuture.setException(new ExecutionException(t));
                } finally {
                    synchronized (mapAccessLock) {
                        if (command.isEligibleForCaching()) {
                            final FinalizableResultFuture mapFuture = sExecutingCommandMap.remove(command);
                            if (mapFuture == null) {
                                // If this has happened, the command that we started with has mutated.  We will
                                // examine every entry in the map, find the one with the same object identity
                                // and remove it.
                                // ADO:TODO:1153495 - Rekey this map with stable string keys.
                                Logger.error(TAG, "The command in the map has mutated " + command.getClass().getCanonicalName() + " the calling application was " + command.getParameters().getApplicationName(), null);
                                cleanMap(command);
                            }
                        }
                        finalFuture.setCleanedUp();
                    }
                    DiagnosticContext.clear();
                }
            }
        });
        return finalFuture;
    }
}
Also used : SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) Handler(android.os.Handler) FinalizableResultFuture(com.microsoft.identity.common.internal.result.FinalizableResultFuture) CommandParameters(com.microsoft.identity.common.internal.commands.parameters.CommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) ExecutionException(java.util.concurrent.ExecutionException) VisibleForTesting(androidx.annotation.VisibleForTesting)

Example 3 with CommandParameters

use of com.microsoft.identity.common.internal.commands.parameters.CommandParameters in project microsoft-authentication-library-common-for-android by AzureAD.

the class HelloCacheTests method testHelloShouldOnlyTriggerOnce.

@Test
public void testHelloShouldOnlyTriggerOnce() {
    final String minimumVer = "1.0";
    final String negotiatedVer = "2.5";
    class MockStrategy implements IIpcStrategy {

        int triggered = 0;

        @Nullable
        @Override
        public Bundle communicateToBroker(@NonNull BrokerOperationBundle bundle) throws BrokerCommunicationException {
            triggered += 1;
            if (triggered == 2) {
                Assert.fail("Should never be triggered");
            }
            final Bundle resultBundle = new Bundle();
            resultBundle.putString(NEGOTIATED_BP_VERSION_KEY, negotiatedVer);
            return resultBundle;
        }

        @Override
        public Type getType() {
            return Type.CONTENT_PROVIDER;
        }
    }
    class MockController extends BrokerMsalController {

        public MockController(Context applicationContext) {
            super(applicationContext);
        }

        @Override
        public HelloCache getHelloCache() {
            return HelloCacheTests.this.getHelloCache(protocolA);
        }

        @Override
        public String getActiveBrokerPackageName() {
            return brokerAppName;
        }
    }
    final MockController controller = new MockController(ApplicationProvider.getApplicationContext());
    final MockStrategy strategy = new MockStrategy();
    final CommandParameters parameters = CommandParameters.builder().requiredBrokerProtocolVersion(minimumVer).build();
    try {
        final String negotiatedProtocolVersion = controller.hello(strategy, parameters.getRequiredBrokerProtocolVersion());
        final String negotiatedProtocolVersion2 = controller.hello(strategy, parameters.getRequiredBrokerProtocolVersion());
        Assert.assertEquals(negotiatedProtocolVersion, negotiatedProtocolVersion2);
    } catch (BaseException e) {
        Assert.fail();
    }
}
Also used : Context(android.content.Context) BaseException(com.microsoft.identity.common.exception.BaseException) BrokerOperationBundle(com.microsoft.identity.common.internal.broker.ipc.BrokerOperationBundle) Bundle(android.os.Bundle) BrokerOperationBundle(com.microsoft.identity.common.internal.broker.ipc.BrokerOperationBundle) NonNull(androidx.annotation.NonNull) IIpcStrategy(com.microsoft.identity.common.internal.broker.ipc.IIpcStrategy) CommandParameters(com.microsoft.identity.common.internal.commands.parameters.CommandParameters) BrokerMsalController(com.microsoft.identity.common.internal.controllers.BrokerMsalController) Test(org.junit.Test)

Aggregations

CommandParameters (com.microsoft.identity.common.internal.commands.parameters.CommandParameters)3 Context (android.content.Context)2 Handler (android.os.Handler)2 BrokerInteractiveTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters)2 SilentTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters)2 BroadcastReceiver (android.content.BroadcastReceiver)1 Intent (android.content.Intent)1 IntentFilter (android.content.IntentFilter)1 Bundle (android.os.Bundle)1 NonNull (androidx.annotation.NonNull)1 VisibleForTesting (androidx.annotation.VisibleForTesting)1 LocalBroadcastManager (androidx.localbroadcastmanager.content.LocalBroadcastManager)1 BaseException (com.microsoft.identity.common.exception.BaseException)1 BrokerOperationBundle (com.microsoft.identity.common.internal.broker.ipc.BrokerOperationBundle)1 IIpcStrategy (com.microsoft.identity.common.internal.broker.ipc.IIpcStrategy)1 BrokerMsalController (com.microsoft.identity.common.internal.controllers.BrokerMsalController)1 FinalizableResultFuture (com.microsoft.identity.common.internal.result.FinalizableResultFuture)1 DiagnosticContext (com.microsoft.identity.common.logging.DiagnosticContext)1 ExecutionException (java.util.concurrent.ExecutionException)1 Test (org.junit.Test)1