aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/androidTest/java/org/sufficientlysecure/keychain/ui/AsymmetricFileOperationTests.java
blob: 406e40ba6ca2d4487a8496e7a35abc7b055043c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
 * Copyright (C) 2015 Vincent Breitmoser <look@my.amazin.horse>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.sufficientlysecure.keychain.ui;


import java.io.File;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Instrumentation.ActivityResult;
import android.content.Intent;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.support.test.espresso.intent.Intents;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.widget.AdapterView;

import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.TestHelpers;
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
import org.sufficientlysecure.keychain.ui.util.Notify.Style;

import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.espresso.Espresso.onData;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
import static android.support.test.espresso.Espresso.pressBack;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasCategories;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasExtra;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasExtraWithKey;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasType;
import static android.support.test.espresso.matcher.ViewMatchers.assertThat;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDescendantOfA;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.sufficientlysecure.keychain.TestHelpers.checkSnackbar;
import static org.sufficientlysecure.keychain.TestHelpers.getImageNames;
import static org.sufficientlysecure.keychain.TestHelpers.importKeysFromResource;
import static org.sufficientlysecure.keychain.TestHelpers.pickRandom;
import static org.sufficientlysecure.keychain.TestHelpers.randomString;
import static org.sufficientlysecure.keychain.actions.CustomActions.tokenEncryptViewAddToken;
import static org.sufficientlysecure.keychain.matcher.CustomMatchers.isRecyclerItemView;
import static org.sufficientlysecure.keychain.matcher.CustomMatchers.withDisplayedChild;
import static org.sufficientlysecure.keychain.matcher.CustomMatchers.withEncryptionStatus;
import static org.sufficientlysecure.keychain.matcher.CustomMatchers.withKeyItemId;
import static org.sufficientlysecure.keychain.matcher.CustomMatchers.withSignatureMyKey;
import static org.sufficientlysecure.keychain.matcher.CustomMatchers.withSignatureNone;


@RunWith(AndroidJUnit4.class)
@LargeTest
public class AsymmetricFileOperationTests {

    @Rule
    public final IntentsTestRule<MainActivity> mActivity
            = new IntentsTestRule<MainActivity>(MainActivity.class) {
        @Override
        protected Intent getActivityIntent() {
            Intent intent = super.getActivityIntent();
            intent.putExtra(MainActivity.EXTRA_SKIP_FIRST_TIME, true);
            intent.putExtra(MainActivity.EXTRA_INIT_FRAG, MainActivity.ID_ENCRYPT_DECRYPT);
            return intent;
        }
    };

    @Before
    public void setUp() throws Exception {
        Activity activity = mActivity.getActivity();

        TestHelpers.copyFiles();

        // import these two, make sure they're there
        importKeysFromResource(activity, "x.sec.asc");

        // make sure no passphrases are cached
        PassphraseCacheService.clearCachedPassphrases(activity);
    }

    @Test
    public void testTextEncryptDecryptFromToken() throws Exception {

        // navigate to 'encrypt text'
        onView(withId(R.id.encrypt_files)).perform(click());

        File file = pickRandom(getImageNames());
        File outputFile = new File(getInstrumentation().getTargetContext().getFilesDir(), "output-token.gpg");

        { // encrypt

            // the EncryptKeyCompletionView is tested individually
            onView(withId(R.id.recipient_list)).perform(tokenEncryptViewAddToken(0x9D604D2F310716A3L));

            handleAddFileIntent(file);
            onView(withId(R.id.file_list_entry_add)).perform(click());

            handleSaveFileIntent(outputFile);
            onView(withId(R.id.encrypt_save)).perform(click());

            assertThat("output file has been written", true, CoreMatchers.is(outputFile.exists()));

        }

        // go to decrypt from clipboard view
        pressBack();

        handleOpenFileIntentKitKat(outputFile);
        onView(withId(R.id.decrypt_files)).perform(click());

        { // decrypt
            onView(withId(R.id.passphrase_passphrase)).perform(typeText("x"));
            onView(withText(R.string.btn_unlock)).perform(click());

            onView(isRecyclerItemView(R.id.decrypted_files_list,
                    hasDescendant(withText(file.getName()))))
                    .check(matches(allOf(withEncryptionStatus(true), withSignatureNone())));

        }

    }

    private void handleAddFileIntent(File file) {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            handleAddFileIntentKitKat(file);
        } else {
            handleAddFileIntentOlder(file);
        }
    }

    @TargetApi(VERSION_CODES.KITKAT)
    private void handleAddFileIntentKitKat(File file) {
        Intent data = new Intent();
        data.setData(Uri.fromFile(file));

        Intents.intending(allOf(
                hasAction(Intent.ACTION_OPEN_DOCUMENT),
                hasType("*/*"),
                hasCategories(hasItem(Intent.CATEGORY_OPENABLE)),
                hasExtraWithKey(Intent.EXTRA_ALLOW_MULTIPLE)
        )).respondWith(
                new ActivityResult(Activity.RESULT_OK, data)
        );
    }

    private void handleAddFileIntentOlder(File file) {
        Intent data = new Intent();
        data.setData(Uri.fromFile(file));

        Intents.intending(allOf(
                hasAction(Intent.ACTION_GET_CONTENT),
                hasType("*/*"),
                hasCategories(hasItem(Intent.CATEGORY_OPENABLE))
        )).respondWith(
                new ActivityResult(Activity.RESULT_OK, data)
        );
    }

    @TargetApi(VERSION_CODES.KITKAT)
    private void handleSaveFileIntent(File file) {

        try {
            //noinspection ResultOfMethodCallIgnored
            file.delete();
        } catch (Exception e) {
            // nvm
        }

        Intent data = new Intent();
        data.setData(Uri.fromFile(file));

        Intents.intending(allOf(
                hasAction(Intent.ACTION_CREATE_DOCUMENT),
                hasType("*/*"),
                hasExtra("android.content.extra.SHOW_ADVANCED", true),
                hasCategories(hasItem(Intent.CATEGORY_OPENABLE))
        )).respondWith(
                new ActivityResult(Activity.RESULT_OK, data)
        );
    }

    @TargetApi(VERSION_CODES.KITKAT)
    private void handleOpenFileIntentKitKat(File file) {
        Intent data = new Intent();
        data.setData(Uri.fromFile(file));

        Intents.intending(allOf(
                hasAction(Intent.ACTION_OPEN_DOCUMENT),
                hasType("*/*"),
                hasCategories(hasItem(Intent.CATEGORY_OPENABLE))
                // hasExtraWithKey(Intent.EXTRA_ALLOW_MULTIPLE)
        )).respondWith(
                new ActivityResult(Activity.RESULT_OK, data)
        );
    }

    @Test
    public void testTextEncryptDecryptFromKeyView() throws Exception {

        String cleartext = randomString(10, 30);

        // navigate to key list
        pressBack();

        { // encrypt

            // navigate to edit key dialog
            onData(withKeyItemId(0x9D604D2F310716A3L))
                    .inAdapterView(allOf(isAssignableFrom(AdapterView.class),
                            isDescendantOfA(withId(R.id.key_list_list))))
                    .perform(click());
            onView(withId(R.id.view_key_action_encrypt_text)).perform(click());

            // make sure the encrypt is correctly set
            onView(withId(R.id.result_encryption_icon)).check(matches(withDisplayedChild(1)));

        }

    }

    @Test
    public void testSignVerify() throws Exception {

        String cleartext = randomString(10, 30);

        // navigate to 'encrypt text'
        onView(withId(R.id.encrypt_text)).perform(click());

        { // sign

            onView(withId(R.id.encrypt_copy)).perform(click());
            checkSnackbar(Style.ERROR, R.string.error_empty_text);

            onView(withId(R.id.result_signature_icon)).check(matches(withDisplayedChild(0)));
            onView(withId(R.id.sign)).perform(click());
            onData(withKeyItemId(0x9D604D2F310716A3L))
                    .inAdapterView(isAssignableFrom(AdapterView.class))
                    .perform(click());
            onView(withId(R.id.result_signature_icon)).check(matches(withDisplayedChild(1)));

            onView(withId(R.id.encrypt_text_text)).perform(typeText(cleartext));

            onView(withId(R.id.encrypt_copy)).perform(click());

            onView(withId(R.id.passphrase_passphrase)).perform(typeText("x"));
            onView(withText(R.string.btn_unlock)).perform(click());

            checkSnackbar(Style.OK, R.string.msg_se_success);

        }

        // go to decrypt from clipboard view
        pressBack();

        onView(withId(R.id.decrypt_from_clipboard)).perform(click());

        { // decrypt

            onView(isRecyclerItemView(R.id.decrypted_files_list,
                    hasDescendant(withText(R.string.filename_unknown))))
                    .check(matches(allOf(withEncryptionStatus(false), withSignatureMyKey())));

            // open context menu
            onView(allOf(isDescendantOfA(isRecyclerItemView(R.id.decrypted_files_list,
                            hasDescendant(withText(R.string.filename_unknown)))),
                    withId(R.id.context_menu))).perform(click());

            // "delete file" shouldn't be there
            onView(withText(R.string.btn_delete_original)).check(doesNotExist());

            // check if log looks ok
            onView(withText(R.string.snackbar_details)).perform(click());
            onView(withText(R.string.msg_dc_clear_signature_ok)).check(matches(isDisplayed()));
            pressBack();

        }

    }

    @Test
    public void testGeneralErrorHandling() throws Exception {

        // navigate to encrypt files fragment
        onView(withId(R.id.encrypt_files)).perform(click());

        File[] files = getImageNames();

        { // encrypt screen

            onView(withId(R.id.encrypt_share)).perform(click());
            checkSnackbar(Style.ERROR, R.string.error_no_file_selected);

            handleAddFileIntent(files[0]);
            onView(withId(R.id.file_list_entry_add)).perform(click());

            handleAddFileIntent(files[1]);
            onView(withId(R.id.file_list_entry_add)).perform(click());

            onView(withId(R.id.encrypt_share)).perform(click());
            checkSnackbar(Style.ERROR, R.string.select_encryption_key);

            onView(withId(R.id.sign)).perform(click());
            onData(withKeyItemId(0x9D604D2F310716A3L))
                    .inAdapterView(isAssignableFrom(AdapterView.class))
                    .perform(click());

            onView(withId(R.id.encrypt_share)).perform(click());
            checkSnackbar(Style.ERROR, R.string.error_detached_signature);

            // the EncryptKeyCompletionView is tested individually
            onView(withId(R.id.recipient_list)).perform(tokenEncryptViewAddToken(0x9D604D2F310716A3L));

            onView(withId(R.id.encrypt_save)).perform(click());
            checkSnackbar(Style.ERROR, R.string.error_multi_files);

            openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
            onView(withText(R.string.btn_copy_encrypted_signed)).perform(click());
            checkSnackbar(Style.ERROR, R.string.error_multi_clipboard);

        }

    }

}