/**
   * Secures the response message using the same {@code AsyncServerAuthModule} that authenticated
   * the incoming request message.
   *
   * <p>If no {@code AsyncServerAuthModule} authenticated the incoming request message, then this
   * method should not have been called and a failed promise will be return with an {@code
   * AuthenticationException}.
   *
   * @param context {@inheritDoc}
   * @param serviceSubject {@inheritDoc}
   * @return {@inheritDoc}
   */
  @Override
  public Promise<AuthStatus, AuthenticationException> secureResponse(
      MessageContext context, Subject serviceSubject) {
    FallbackAuthContextState state = context.getState(this);

    if (state.getAuthenticatedAuthModuleIndex() < 0) {
      return Promises.newExceptionPromise(
          new AuthenticationException(
              "No auth module authenticated the incoming request message. "
                  + "Cannot secure response message."));
    }
    AsyncServerAuthModule authModule = authModules.get(state.getAuthenticatedAuthModuleIndex());
    logger.debug(
        "Using authenticating auth module from private context map, {}, to secure the response",
        authModule.getModuleId());

    return authModule.secureResponse(context, serviceSubject);
  }
  @Test
  public void adaptedAsyncServerAuthModuleShouldAdaptSuccessfulSecureResponseCall()
      throws AuthException {

    // Given
    ServerAuthModule authModule = mock(ServerAuthModule.class);
    MessageInfoContext messageInfo = mock(MessageInfoContext.class);
    Subject serviceSubject = new Subject();

    given(authModule.secureResponse(any(MessageInfo.class), eq(serviceSubject)))
        .willReturn(AuthStatus.SEND_SUCCESS);

    // When
    AsyncServerAuthModule asyncAuthModule = JaspiAdapters.adapt(authModule);
    Promise<AuthStatus, AuthenticationException> promise =
        asyncAuthModule.secureResponse(messageInfo, serviceSubject);

    // Then
    assertThat(promise).succeeded().withObject().isEqualTo(AuthStatus.SEND_SUCCESS);
  }
  @Test
  public void adaptedAsyncServerAuthModuleShouldAdaptFailedSecureResponseCall()
      throws AuthException {

    // Given
    ServerAuthModule authModule = mock(ServerAuthModule.class);
    MessageInfoContext messageInfo = mock(MessageInfoContext.class);
    Subject serviceSubject = new Subject();

    doThrow(AuthException.class)
        .when(authModule)
        .secureResponse(any(MessageInfo.class), eq(serviceSubject));

    // When
    AsyncServerAuthModule asyncAuthModule = JaspiAdapters.adapt(authModule);
    Promise<AuthStatus, AuthenticationException> promise =
        asyncAuthModule.secureResponse(messageInfo, serviceSubject);

    // Then
    assertThat(promise).failedWithException().isInstanceOf(AuthenticationException.class);
  }