mirror of
https://github.com/commons-app/apps-android-commons.git
synced 2025-10-27 04:43:54 +01:00
Moved the CSRF token client over into main commons code (#5471)
This commit is contained in:
parent
3d0e65c92c
commit
8b8eb84fae
18 changed files with 252 additions and 37 deletions
|
|
@ -1,247 +0,0 @@
|
|||
package org.wikipedia.csrf;
|
||||
|
||||
import android.text.TextUtils;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.VisibleForTesting;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Executors;
|
||||
import org.wikipedia.AppAdapter;
|
||||
import org.wikipedia.dataclient.Service;
|
||||
import org.wikipedia.dataclient.ServiceFactory;
|
||||
import org.wikipedia.dataclient.SharedPreferenceCookieManager;
|
||||
import org.wikipedia.dataclient.WikiSite;
|
||||
import org.wikipedia.dataclient.mwapi.MwQueryResponse;
|
||||
import org.wikipedia.login.LoginClient;
|
||||
import org.wikipedia.login.LoginResult;
|
||||
import org.wikipedia.util.log.L;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Response;
|
||||
|
||||
public class CsrfTokenClient {
|
||||
private static final String ANON_TOKEN = "+\\";
|
||||
private static final int MAX_RETRIES = 1;
|
||||
private static final int MAX_RETRIES_OF_LOGIN_BLOCKING = 2;
|
||||
@NonNull private final WikiSite csrfWikiSite;
|
||||
@NonNull private final WikiSite loginWikiSite;
|
||||
private int retries = 0;
|
||||
|
||||
@Nullable private Call<MwQueryResponse> csrfTokenCall;
|
||||
@NonNull private LoginClient loginClient = new LoginClient();
|
||||
|
||||
public CsrfTokenClient(@NonNull WikiSite csrfWikiSite, @NonNull WikiSite loginWikiSite) {
|
||||
this.csrfWikiSite = csrfWikiSite;
|
||||
this.loginWikiSite = loginWikiSite;
|
||||
}
|
||||
|
||||
public void request(@NonNull final Callback callback) {
|
||||
request(false, callback);
|
||||
}
|
||||
|
||||
public void request(boolean forceLogin, @NonNull final Callback callback) {
|
||||
cancel();
|
||||
if (forceLogin) {
|
||||
retryWithLogin(new RuntimeException("Forcing login..."), callback);
|
||||
return;
|
||||
}
|
||||
csrfTokenCall = request(ServiceFactory.get(csrfWikiSite), callback);
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
loginClient.cancel();
|
||||
if (csrfTokenCall != null) {
|
||||
csrfTokenCall.cancel();
|
||||
csrfTokenCall = null;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@NonNull
|
||||
Call<MwQueryResponse> request(@NonNull Service service, @NonNull final Callback cb) {
|
||||
return requestToken(service, new CsrfTokenClient.Callback() {
|
||||
@Override public void success(@NonNull String token) {
|
||||
if (AppAdapter.get().isLoggedIn() && token.equals(ANON_TOKEN)) {
|
||||
retryWithLogin(new RuntimeException("App believes we're logged in, but got anonymous token."), cb);
|
||||
} else {
|
||||
cb.success(token);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void failure(@NonNull Throwable caught) {
|
||||
retryWithLogin(caught, cb);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void twoFactorPrompt() {
|
||||
cb.twoFactorPrompt();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void retryWithLogin(@NonNull Throwable caught, @NonNull final Callback callback) {
|
||||
if (retries < MAX_RETRIES
|
||||
&& !TextUtils.isEmpty(AppAdapter.get().getUserName())
|
||||
&& !TextUtils.isEmpty(AppAdapter.get().getPassword())) {
|
||||
retries++;
|
||||
|
||||
SharedPreferenceCookieManager.getInstance().clearAllCookies();
|
||||
|
||||
login(AppAdapter.get().getUserName(), AppAdapter.get().getPassword(), () -> {
|
||||
L.i("retrying...");
|
||||
request(callback);
|
||||
}, callback);
|
||||
} else {
|
||||
callback.failure(caught);
|
||||
}
|
||||
}
|
||||
|
||||
private void login(@NonNull final String username, @NonNull final String password,
|
||||
@NonNull final RetryCallback retryCallback,
|
||||
@NonNull final Callback callback) {
|
||||
new LoginClient().request(loginWikiSite, username, password,
|
||||
new LoginClient.LoginCallback() {
|
||||
@Override
|
||||
public void success(@NonNull LoginResult loginResult) {
|
||||
if (loginResult.pass()) {
|
||||
AppAdapter.get().updateAccount(loginResult);
|
||||
retryCallback.retry();
|
||||
} else {
|
||||
callback.failure(new LoginClient.LoginFailedException(loginResult.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void twoFactorPrompt(@NonNull Throwable caught, @Nullable String token) {
|
||||
callback.twoFactorPrompt();
|
||||
}
|
||||
|
||||
@Override public void passwordResetPrompt(@Nullable String token) {
|
||||
// Should not happen here, but call the callback just in case.
|
||||
callback.failure(new LoginClient.LoginFailedException("Logged in with temporary password."));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(@NonNull Throwable caught) {
|
||||
callback.failure(caught);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@NonNull public String getTokenBlocking() throws Throwable {
|
||||
String token = "";
|
||||
Service service = ServiceFactory.get(csrfWikiSite);
|
||||
|
||||
for (int retry = 0; retry < MAX_RETRIES_OF_LOGIN_BLOCKING; retry++) {
|
||||
try {
|
||||
if (retry > 0) {
|
||||
// Log in explicitly
|
||||
new LoginClient().loginBlocking(loginWikiSite, AppAdapter.get().getUserName(),
|
||||
AppAdapter.get().getPassword(), "");
|
||||
}
|
||||
|
||||
// Get CSRFToken response off the main thread.
|
||||
Response<MwQueryResponse> response = Executors.newSingleThreadExecutor().submit(new CsrfTokenCallExecutor(service)).get();
|
||||
|
||||
if (response.body() == null || response.body().query() == null
|
||||
|| TextUtils.isEmpty(response.body().query().csrfToken())) {
|
||||
continue;
|
||||
}
|
||||
token = response.body().query().csrfToken();
|
||||
if (AppAdapter.get().isLoggedIn() && token.equals(ANON_TOKEN)) {
|
||||
throw new RuntimeException("App believes we're logged in, but got anonymous token.");
|
||||
}
|
||||
break;
|
||||
} catch (Throwable t) {
|
||||
L.w(t);
|
||||
}
|
||||
}
|
||||
if (TextUtils.isEmpty(token) || token.equals(ANON_TOKEN)) {
|
||||
throw new IOException("Invalid token, or login failure.");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
@VisibleForTesting @NonNull Call<MwQueryResponse> requestToken(@NonNull Service service,
|
||||
@NonNull final Callback cb) {
|
||||
Call<MwQueryResponse> call = service.getCsrfTokenCall();
|
||||
call.enqueue(new retrofit2.Callback<MwQueryResponse>() {
|
||||
@Override
|
||||
public void onResponse(@NonNull Call<MwQueryResponse> call, @NonNull Response<MwQueryResponse> response) {
|
||||
if (call.isCanceled()) {
|
||||
return;
|
||||
}
|
||||
cb.success(response.body().query().csrfToken());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(@NonNull Call<MwQueryResponse> call, @NonNull Throwable t) {
|
||||
if (call.isCanceled()) {
|
||||
return;
|
||||
}
|
||||
cb.failure(t);
|
||||
}
|
||||
});
|
||||
return call;
|
||||
}
|
||||
|
||||
public interface Callback {
|
||||
void success(@NonNull String token);
|
||||
void failure(@NonNull Throwable caught);
|
||||
void twoFactorPrompt();
|
||||
}
|
||||
|
||||
public static class DefaultCallback implements Callback {
|
||||
@Override
|
||||
public void success(@NonNull String token) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failure(@NonNull Throwable caught) {
|
||||
L.e(caught);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void twoFactorPrompt() {
|
||||
// TODO:
|
||||
}
|
||||
}
|
||||
|
||||
private interface RetryCallback {
|
||||
void retry();
|
||||
}
|
||||
|
||||
/**
|
||||
* Class CsrfTokenCallExecutor which implement callable interface to get CsrfTokenCall.
|
||||
*/
|
||||
class CsrfTokenCallExecutor implements Callable<Response<MwQueryResponse>> {
|
||||
|
||||
/**
|
||||
* Service for token call.
|
||||
*/
|
||||
private Service service;
|
||||
|
||||
/**
|
||||
* Default Constructor.
|
||||
* @param service
|
||||
*/
|
||||
public CsrfTokenCallExecutor(Service service){
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a result, or throws an exception if unable to do so.
|
||||
*
|
||||
* @return computed result
|
||||
* @throws Exception if unable to compute a result
|
||||
*/
|
||||
@Override
|
||||
public Response<MwQueryResponse> call() throws Exception {
|
||||
return service.getCsrfTokenCall().execute();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
package org.wikipedia.csrf;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.google.gson.stream.MalformedJsonException;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.wikipedia.csrf.CsrfTokenClient.Callback;
|
||||
import org.wikipedia.dataclient.Service;
|
||||
import org.wikipedia.dataclient.WikiSite;
|
||||
import org.wikipedia.dataclient.mwapi.MwException;
|
||||
import org.wikipedia.dataclient.mwapi.MwQueryResponse;
|
||||
import org.wikipedia.dataclient.okhttp.HttpStatusException;
|
||||
import org.wikipedia.test.MockWebServerTest;
|
||||
|
||||
import retrofit2.Call;
|
||||
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Matchers.isA;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
public class CsrfTokenClientTest extends MockWebServerTest {
|
||||
private static final WikiSite TEST_WIKI = new WikiSite("test.wikipedia.org");
|
||||
@NonNull private final CsrfTokenClient subject = new CsrfTokenClient(TEST_WIKI, TEST_WIKI);
|
||||
|
||||
@Test public void testRequestSuccess() throws Throwable {
|
||||
String expected = "b6f7bd58c013ab30735cb19ecc0aa08258122cba+\\";
|
||||
enqueueFromFile("csrf_token.json");
|
||||
|
||||
Callback cb = mock(Callback.class);
|
||||
request(cb);
|
||||
|
||||
server().takeRequest();
|
||||
assertCallbackSuccess(cb, expected);
|
||||
}
|
||||
|
||||
@Test public void testRequestResponseApiError() throws Throwable {
|
||||
enqueueFromFile("api_error.json");
|
||||
|
||||
Callback cb = mock(Callback.class);
|
||||
request(cb);
|
||||
|
||||
server().takeRequest();
|
||||
assertCallbackFailure(cb, MwException.class);
|
||||
}
|
||||
|
||||
@Test public void testRequestResponseFailure() throws Throwable {
|
||||
enqueue404();
|
||||
|
||||
Callback cb = mock(Callback.class);
|
||||
request(cb);
|
||||
|
||||
server().takeRequest();
|
||||
assertCallbackFailure(cb, HttpStatusException.class);
|
||||
}
|
||||
|
||||
@Test public void testRequestResponseMalformed() throws Throwable {
|
||||
enqueueMalformed();
|
||||
|
||||
Callback cb = mock(Callback.class);
|
||||
request(cb);
|
||||
|
||||
server().takeRequest();
|
||||
assertCallbackFailure(cb, MalformedJsonException.class);
|
||||
}
|
||||
|
||||
private void assertCallbackSuccess(@NonNull Callback cb,
|
||||
@NonNull String expected) {
|
||||
verify(cb).success(eq(expected));
|
||||
//noinspection unchecked
|
||||
verify(cb, never()).failure(any(Throwable.class));
|
||||
}
|
||||
|
||||
private void assertCallbackFailure(@NonNull Callback cb,
|
||||
@NonNull Class<? extends Throwable> throwable) {
|
||||
//noinspection unchecked
|
||||
verify(cb, never()).success(any(String.class));
|
||||
verify(cb).failure(isA(throwable));
|
||||
}
|
||||
|
||||
private Call<MwQueryResponse> request(@NonNull Callback cb) {
|
||||
return subject.request(service(Service.class), cb);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue