测试 BroadcastReceiver 不接收受保护的广播

Testing that BroadcastReceiver does not receive protected broadcast

我会尽可能地概述这个场景。主要问题是:我如何动态声明 2 个接收器,它们都接收相同的广播,但只有一个接收器具有接收它的正确权限? 到目前为止,在我的测试中,两个接收器都获得了由于我的应用持有声明的许可而不仅仅是一个许可,因此广播。

在应用程序 A 中,我正在发送一个广播,我正在使用我定义的新权限对其进行保护。

在应用程序 B 中,我想确保来自应用程序 A 的广播实际上受到保护。因此,我为同一个 IntentFilter 动态声明了 2 个接收者,一个持有新权限,一个没有。但是,在 App B 的清单中,我当然声明 <uses-permission android:name="new permission" />

然而,两个接收者都得到了它,而不仅仅是持有许可的那个。我假设这是因为 App B 本身被声明为使用该权限。这是我的代码:

应用 A 清单:

<permission
    android:name="com.my.custom.permission"
    android:label="my_permission"
    android:protectionLevel="signature" />

应用A来源:

Intent intent = new Intent(SOME_CUSTOM_ACTION);
...
sendBroadcast(intent, "com.my.custom.permission");

应用程序 B 清单:

<uses-permission android:name="com.my.custom.permission" />

应用程序 B 服务:

private BroadcastReceiver rNoPermission = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (SOME_CUSTOM_ACTION.equals(intent.getAction())) {
            Log.d(TAG, "receiver was able to receive without permission");
        }
    }
};

private BroadcastReceiver rYesPermission = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (SOME_CUSTOM_ACTION.equals(intent.getAction())) {
            Log.d(TAG, "receiver was able to receive properly with permission");
        }
    }
};

public void start() {
    IntentFilter filter = new IntentFilter(SOME_CUSTOM_ACTION);
    registerReceiver(rNoPermission, filter); // purposely don't register with permission
    registerReceiver(rYesPermission, filter, "com.my.custom.permission", null);
}

public void end() {
    unregisterReceiver(rNoPermission);
    unregisterReceiver(rYesPermission);
}

流量:

  1. 已为 Android 安装应用 A 以学习新权限
  2. 已安装应用程序 B 并且 运行
  3. App B start()方法被调用
  4. 切换到App A触发发送广播
  5. 在日志中看到两个 BroadcastReceiver 都被调用了
  6. 调用end()方法结束测试

有什么想法吗?

意识到我的错误在哪里了。权限是在应用程序级别而非组件级别授予的。根据 Android 文档:

To enforce a permission when sending, you supply a non-null permission argument to sendBroadcast(Intent, String) or sendOrderedBroadcast(Intent, String, BroadcastReceiver, android.os.Handler, int, String, Bundle). Only receivers who have been granted this permission (by requesting it with the tag in their AndroidManifest.xml) will be able to receive the broadcast.

(来源:http://developer.android.com/reference/android/content/BroadcastReceiver.html

和:

Senders of an intent can verify that the recipient has a permission specifying a non-Null permission with the method call. Only applications with that permission will receive the intent.

(来源:http://developer.android.com/training/articles/security-tips.html

所以到目前为止,似乎没有办法在不将 BroadcastReceiver 分成 2 个单独的应用程序的情况下执行我上面提到的操作,一个使用权限,一个没有。