aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/linked/LinkedIdCreateGithubFragment.java
blob: 6df31a596d09ebec77dad0d0315316a19c200569 (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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/*
 * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
 *
 * 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.linked;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewAnimator;

import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import org.json.JSONObject;
import org.spongycastle.util.encoders.Hex;
import org.sufficientlysecure.keychain.BuildConfig;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.linked.LinkedAttribute;
import org.sufficientlysecure.keychain.linked.resources.GithubResource;
import org.sufficientlysecure.keychain.operations.results.EditKeyResult;
import org.sufficientlysecure.keychain.pgp.WrappedUserAttribute;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel;
import org.sufficientlysecure.keychain.ui.ViewKeyActivity;
import org.sufficientlysecure.keychain.ui.base.CryptoOperationFragment;
import org.sufficientlysecure.keychain.ui.widget.StatusIndicator;
import org.sufficientlysecure.keychain.ui.widget.StatusIndicator.Status;
import org.sufficientlysecure.keychain.util.Log;


public class LinkedIdCreateGithubFragment extends CryptoOperationFragment<SaveKeyringParcel,EditKeyResult> {

    private Button mRetryButton;

    enum State {
        IDLE, AUTH_PROCESS, AUTH_ERROR, POST_PROCESS, POST_ERROR, LID_PROCESS, LID_ERROR, DONE
    }

    public static final String GITHUB_CLIENT_ID = "7a011b66275f244d3f21";
    public static final String GITHUB_CLIENT_SECRET = "eaced8a6655719d8c6848396de97b3f5d7a89fec";

    ViewAnimator mButtonContainer;

    StatusIndicator mStatus1, mStatus2, mStatus3;

    byte[] mFingerprint;
    long mMasterKeyId;
    private SaveKeyringParcel mSaveKeyringParcel;
    private TextView mLinkedIdTitle, mLinkedIdComment;
    private boolean mFinishOnStop;

    public static LinkedIdCreateGithubFragment newInstance() {
        return new LinkedIdCreateGithubFragment();
    }

    public LinkedIdCreateGithubFragment() {
        super(null);
    }

    @Override @NonNull
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.linked_create_github_fragment, container, false);

        mButtonContainer = (ViewAnimator) view.findViewById(R.id.button_container);

        mStatus1 = (StatusIndicator) view.findViewById(R.id.linked_status_step1);
        mStatus2 = (StatusIndicator) view.findViewById(R.id.linked_status_step2);
        mStatus3 = (StatusIndicator) view.findViewById(R.id.linked_status_step3);

        mRetryButton = (Button) view.findViewById(R.id.button_retry);

        ((ImageView) view.findViewById(R.id.linked_id_type_icon)).setImageResource(R.drawable.linked_github);
        ((ImageView) view.findViewById(R.id.linked_id_certified_icon)).setImageResource(R.drawable.octo_link_24dp);
        mLinkedIdTitle = (TextView) view.findViewById(R.id.linked_id_title);
        mLinkedIdComment = (TextView) view.findViewById(R.id.linked_id_comment);

        view.findViewById(R.id.back_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinkedIdWizard activity = (LinkedIdWizard) getActivity();
                if (activity == null) {
                    return;
                }
                activity.loadFragment(null, null, LinkedIdWizard.FRAG_ACTION_TO_LEFT);
            }
        });

        view.findViewById(R.id.button_send).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                step1GetOAuthCode();
                // for animation testing
                // onCryptoOperationSuccess(null);
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        LinkedIdWizard wizard = (LinkedIdWizard) getActivity();
        mFingerprint = wizard.mFingerprint;
        mMasterKeyId = wizard.mMasterKeyId;
    }

    private void step1GetOAuthCode() {

        setState(State.AUTH_PROCESS);

        mButtonContainer.setDisplayedChild(1);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                oAuthRequest("github.com/login/oauth/authorize", GITHUB_CLIENT_ID, "gist");
            }
        }, 300);

    }

    private void step1GetOAuthToken() {

        if (mOAuthCode == null) {
            Log.d(Constants.TAG, "no code");
            return;
        }

        Activity activity = getActivity();
        if (activity == null) {
            return;
        }

        // this is only good once!
        final String oAuthCode = mOAuthCode, oAuthState = mOAuthState;
        mOAuthCode = null;
        mOAuthState = null;

        final String gistText = GithubResource.generate(activity, mFingerprint);

        new AsyncTask<Void,Void,JSONObject>() {
            @Override
            protected JSONObject doInBackground(Void... dummy) {
                try {

                    JSONObject params = new JSONObject();
                    params.put("client_id", GITHUB_CLIENT_ID);
                    params.put("client_secret", GITHUB_CLIENT_SECRET);
                    params.put("code", oAuthCode);
                    params.put("state", oAuthState);

                    return jsonHttpRequest("https://github.com/login/oauth/access_token", params, null);

                } catch (IOException e) {
                    Log.e(Constants.TAG, "error in request", e);
                } catch (JSONException e) {
                    throw new AssertionError("json error, this is a bug!");
                }
                return null;
            }

            @Override
            protected void onPostExecute(JSONObject result) {
                super.onPostExecute(result);

                Log.d(Constants.TAG, "response: " + result);

                if (result == null || !result.has("access_token")) {
                    setState(State.AUTH_ERROR);
                    return;
                }

                step2PostGist(result.optString("access_token"), gistText);

            }
        }.execute();

    }

    private void step2PostGist(final String accessToken, final String gistText) {

        setState(State.POST_PROCESS);

        new AsyncTask<Void,Void,JSONObject>() {
            @Override
            protected JSONObject doInBackground(Void... dummy) {
                try {

                    long timer = System.currentTimeMillis();

                    JSONObject file = new JSONObject();
                    file.put("content", gistText);

                    JSONObject files = new JSONObject();
                    files.put("file1.txt", file);

                    JSONObject params = new JSONObject();
                    params.put("public", true);
                    params.put("description", "OpenKeychain API Tests");
                    params.put("files", files);

                    JSONObject result = jsonHttpRequest("https://api.github.com/gists", params, accessToken);

                    // ux flow: this operation should take at last a second
                    timer = System.currentTimeMillis() -timer;
                    if (timer < 1000) try {
                        Thread.sleep(1000 -timer);
                    } catch (InterruptedException e) {
                        // never mind
                    }

                    return result;

                } catch (IOException e) {
                    Log.e(Constants.TAG, "error in request", e);
                } catch (JSONException e) {
                    throw new AssertionError("json error, this is a bug!");
                }
                return null;
            }

            @Override
            protected void onPostExecute(JSONObject result) {
                super.onPostExecute(result);

                Log.d(Constants.TAG, "response: " + result);

                if (result == null) {
                    mStatus2.setDisplayedChild(3);
                    return;
                }

                try {
                    String gistId = result.getString("id");
                    JSONObject owner = result.getJSONObject("owner");
                    String gistLogin = owner.getString("login");

                    URI uri = URI.create("https://gist.github.com/" + gistLogin + "/" + gistId);
                    GithubResource resource = GithubResource.create(uri);

                    View linkedItem = mButtonContainer.getChildAt(2);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        linkedItem.setTransitionName(resource.toUri().toString());
                    }

                    // we only need authorization for this one operation, drop it afterwards
                    revokeToken(accessToken);

                    step3EditKey(resource);

                } catch (JSONException e) {
                    setState(State.POST_ERROR);
                    e.printStackTrace();
                }

            }
        }.execute();

    }

    private void revokeToken(final String token) {

        new AsyncTask<Void,Void,Void>() {
            @Override
            protected Void doInBackground(Void... dummy) {
                try {
                    HttpsURLConnection nection = (HttpsURLConnection) new URL(
                            "https://api.github.com/applications/7a011b66275f244d3f21/tokens/" + token)
                            .openConnection();
                    nection.setRequestMethod("DELETE");
                    nection.connect();
                } catch (IOException e) {
                    // nvm
                }
                return null;
            }
        }.execute();

    }

    private void step3EditKey(final GithubResource resource) {

        // set item data while we're there
        {
            Context context = getActivity();
            mLinkedIdTitle.setText(resource.getDisplayTitle(context));
            mLinkedIdComment.setText(resource.getDisplayComment(context));
        }

        setState(State.LID_PROCESS);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                WrappedUserAttribute ua = LinkedAttribute.fromResource(resource).toUserAttribute();
                mSaveKeyringParcel = new SaveKeyringParcel(mMasterKeyId, mFingerprint);
                mSaveKeyringParcel.mAddUserAttribute.add(ua);

                cryptoOperation();

            }
        }, 250);

    }

    @Nullable
    @Override
    public SaveKeyringParcel createOperationInput() {
        // if this is null, the cryptoOperation silently aborts - which is what we want in that case
        return mSaveKeyringParcel;
    }

    @Override
    public void onCryptoOperationSuccess(EditKeyResult result) {

        setState(State.DONE);

        mButtonContainer.getInAnimation().setDuration(750);
        mButtonContainer.setDisplayedChild(2);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                FragmentActivity activity = getActivity();
                Intent intent = new Intent(activity, ViewKeyActivity.class);
                intent.setData(KeyRings.buildGenericKeyRingUri(mMasterKeyId));
                // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    intent.putExtra(ViewKeyActivity.EXTRA_LINKED_TRANSITION, true);
                    View linkedItem = mButtonContainer.getChildAt(2);

                    Bundle options = ActivityOptionsCompat.makeSceneTransitionAnimation(
                            activity, linkedItem, linkedItem.getTransitionName()).toBundle();
                    activity.startActivity(intent, options);
                    mFinishOnStop = true;
                } else {
                    activity.startActivity(intent);
                    activity.finish();
                }
            }
        }, 1000);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mFinishOnStop) {
            Activity activity = getActivity();
            activity.setResult(Activity.RESULT_OK);
            activity.finish();
        }
    }

    @Override
    public void onCryptoOperationError(EditKeyResult result) {
        result.createNotify(getActivity()).show(this);
        setState(State.LID_ERROR);
    }

    @Override
    public void onCryptoOperationCancelled() {
        mRetryButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setOnClickListener(null);
                mButtonContainer.setDisplayedChild(1);
                setState(State.LID_PROCESS);
                cryptoOperation();
            }
        });
        mButtonContainer.setDisplayedChild(3);
        setState(State.LID_ERROR);
    }

    private String mOAuthCode, mOAuthState;

    @SuppressLint("SetJavaScriptEnabled") // trusted https website, it's ok
    public void oAuthRequest(String hostAndPath, String clientId, String scope) {

        Activity activity = getActivity();
        if (activity == null) {
            return;
        }

        byte[] buf = new byte[16];
        new Random().nextBytes(buf);
        mOAuthState = new String(Hex.encode(buf));

        final Dialog auth_dialog = new Dialog(activity);
        auth_dialog.setContentView(R.layout.oauth_webview);
        WebView web = (WebView) auth_dialog.findViewById(R.id.web_view);
        web.getSettings().setSaveFormData(false);
        web.setWebViewClient(new WebViewClient() {

            boolean authComplete = false;

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                if ("oauth-openkeychain".equals(uri.getScheme()) && !authComplete) {
                    authComplete = true;

                    if (uri.getQueryParameter("error") != null) {
                        Log.i(Constants.TAG, "ACCESS_DENIED_HERE");
                        auth_dialog.dismiss();
                        return true;
                    }

                    // check if mOAuthState == queryParam[state]
                    mOAuthCode = uri.getQueryParameter("code");

                    Log.d(Constants.TAG, "got ok response, code is " + mOAuthCode);

                    CookieManager cookieManager = CookieManager.getInstance();
                    // noinspection deprecation (replacement is api lvl 21)
                    cookieManager.removeAllCookie();

                    auth_dialog.dismiss();
                    return true;
                }
                return false;
            }

        });

        auth_dialog.setTitle("GitHub Authorization");
        auth_dialog.setCancelable(true);
        auth_dialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                step1GetOAuthToken();
            }
        });
        auth_dialog.show();

        web.loadUrl("https://" + hostAndPath +
                "?client_id=" + clientId +
                "&scope=" + scope +
                "&redirect_uri=oauth-openkeychain://linked/" +
                "&state=" + mOAuthState);

    }

    public void setState(State state) {
        switch (state) {
            case IDLE:
                mStatus1.setDisplayedChild(Status.IDLE);
                mStatus2.setDisplayedChild(Status.IDLE);
                mStatus3.setDisplayedChild(Status.IDLE);
                break;
            case AUTH_PROCESS:
                mStatus1.setDisplayedChild(Status.PROGRESS);
                mStatus2.setDisplayedChild(Status.IDLE);
                mStatus3.setDisplayedChild(Status.IDLE);
                break;
            case AUTH_ERROR:
                mStatus1.setDisplayedChild(Status.ERROR);
                mStatus2.setDisplayedChild(Status.IDLE);
                mStatus3.setDisplayedChild(Status.IDLE);
                break;
            case POST_PROCESS:
                mStatus1.setDisplayedChild(Status.OK);
                mStatus2.setDisplayedChild(Status.PROGRESS);
                mStatus3.setDisplayedChild(Status.IDLE);
                break;
            case POST_ERROR:
                mStatus1.setDisplayedChild(Status.OK);
                mStatus2.setDisplayedChild(Status.ERROR);
                mStatus3.setDisplayedChild(Status.IDLE);
                break;
            case LID_PROCESS:
                mStatus1.setDisplayedChild(Status.OK);
                mStatus2.setDisplayedChild(Status.OK);
                mStatus3.setDisplayedChild(Status.PROGRESS);
                break;
            case LID_ERROR:
                mStatus1.setDisplayedChild(Status.OK);
                mStatus2.setDisplayedChild(Status.OK);
                mStatus3.setDisplayedChild(Status.ERROR);
                break;
            case DONE:
                mStatus1.setDisplayedChild(Status.OK);
                mStatus2.setDisplayedChild(Status.OK);
                mStatus3.setDisplayedChild(Status.OK);
        }
    }

    private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken)
            throws IOException {

        HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection();
        nection.setDoInput(true);
        nection.setDoOutput(true);
        nection.setRequestProperty("Content-Type", "application/json");
        nection.setRequestProperty("Accept", "application/json");
        nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME);
        if (accessToken != null) {
            nection.setRequestProperty("Authorization", "token " + accessToken);
        }

        OutputStream os = nection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(params.toString());
        writer.flush();
        writer.close();
        os.close();

        try {

            nection.connect();
            InputStream in = new BufferedInputStream(nection.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder response = new StringBuilder();
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                response.append(line);
            }

            try {
                return new JSONObject(response.toString());
            } catch (JSONException e) {
                throw new IOException(e);
            }

        } finally {
            nection.disconnect();
        }

    }

}