1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/android/http_auth_negotiate_android.h"
6 
7 #include "base/android/jni_string.h"
8 #include "base/android/scoped_java_ref.h"
9 #include "base/bind.h"
10 #include "base/callback_helpers.h"
11 #include "base/location.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/threading/thread_task_runner_handle.h"
14 #include "net/base/auth.h"
15 #include "net/base/net_errors.h"
16 #include "net/http/http_auth.h"
17 #include "net/http/http_auth_challenge_tokenizer.h"
18 #include "net/http/http_auth_multi_round_parse.h"
19 #include "net/http/http_auth_preferences.h"
20 #include "net/log/net_log_with_source.h"
21 #include "net/net_jni_headers/HttpNegotiateAuthenticator_jni.h"
22 
23 using base::android::AttachCurrentThread;
24 using base::android::ConvertUTF8ToJavaString;
25 using base::android::ConvertJavaStringToUTF8;
26 using base::android::JavaParamRef;
27 using base::android::ScopedJavaLocalRef;
28 
29 namespace net {
30 namespace android {
31 
JavaNegotiateResultWrapper(const scoped_refptr<base::TaskRunner> & callback_task_runner,base::OnceCallback<void (int,const std::string &)> thread_safe_callback)32 JavaNegotiateResultWrapper::JavaNegotiateResultWrapper(
33     const scoped_refptr<base::TaskRunner>& callback_task_runner,
34     base::OnceCallback<void(int, const std::string&)> thread_safe_callback)
35     : callback_task_runner_(callback_task_runner),
36       thread_safe_callback_(std::move(thread_safe_callback)) {}
37 
~JavaNegotiateResultWrapper()38 JavaNegotiateResultWrapper::~JavaNegotiateResultWrapper() {
39 }
40 
SetResult(JNIEnv * env,const JavaParamRef<jobject> & obj,int result,const JavaParamRef<jstring> & token)41 void JavaNegotiateResultWrapper::SetResult(JNIEnv* env,
42                                            const JavaParamRef<jobject>& obj,
43                                            int result,
44                                            const JavaParamRef<jstring>& token) {
45   // This will be called on the UI thread, so we have to post a task back to the
46   // correct thread to actually save the result
47   std::string raw_token;
48   if (token.obj())
49     raw_token = ConvertJavaStringToUTF8(env, token);
50   // Always post, even if we are on the same thread. This guarantees that the
51   // result will be delayed until after the request has completed, which
52   // simplifies the logic. In practice the result will only ever come back on
53   // the original thread in an obscure error case.
54   callback_task_runner_->PostTask(
55       FROM_HERE,
56       base::BindOnce(std::move(thread_safe_callback_), result, raw_token));
57   // We will always get precisely one call to set result for each call to
58   // getNextAuthToken, so we can now delete the callback object, and must
59   // do so to avoid a memory leak.
60   delete this;
61 }
62 
HttpAuthNegotiateAndroid(const HttpAuthPreferences * prefs)63 HttpAuthNegotiateAndroid::HttpAuthNegotiateAndroid(
64     const HttpAuthPreferences* prefs)
65     : prefs_(prefs) {
66   JNIEnv* env = AttachCurrentThread();
67   java_authenticator_.Reset(Java_HttpNegotiateAuthenticator_create(
68       env, ConvertUTF8ToJavaString(env, GetAuthAndroidNegotiateAccountType())));
69 }
70 
~HttpAuthNegotiateAndroid()71 HttpAuthNegotiateAndroid::~HttpAuthNegotiateAndroid() {
72 }
73 
Init(const NetLogWithSource & net_log)74 bool HttpAuthNegotiateAndroid::Init(const NetLogWithSource& net_log) {
75   return true;
76 }
77 
NeedsIdentity() const78 bool HttpAuthNegotiateAndroid::NeedsIdentity() const {
79   return false;
80 }
81 
AllowsExplicitCredentials() const82 bool HttpAuthNegotiateAndroid::AllowsExplicitCredentials() const {
83   return false;
84 }
85 
ParseChallenge(net::HttpAuthChallengeTokenizer * tok)86 HttpAuth::AuthorizationResult HttpAuthNegotiateAndroid::ParseChallenge(
87     net::HttpAuthChallengeTokenizer* tok) {
88   if (first_challenge_) {
89     first_challenge_ = false;
90     return net::ParseFirstRoundChallenge(HttpAuth::AUTH_SCHEME_NEGOTIATE, tok);
91   }
92   std::string decoded_auth_token;
93   return net::ParseLaterRoundChallenge(HttpAuth::AUTH_SCHEME_NEGOTIATE, tok,
94                                        &server_auth_token_,
95                                        &decoded_auth_token);
96 }
97 
GenerateAuthTokenAndroid(const AuthCredentials * credentials,const std::string & spn,const std::string & channel_bindings,std::string * auth_token,net::CompletionOnceCallback callback)98 int HttpAuthNegotiateAndroid::GenerateAuthTokenAndroid(
99     const AuthCredentials* credentials,
100     const std::string& spn,
101     const std::string& channel_bindings,
102     std::string* auth_token,
103     net::CompletionOnceCallback callback) {
104   return GenerateAuthToken(credentials, spn, channel_bindings, auth_token,
105                            NetLogWithSource(), std::move(callback));
106 }
107 
GenerateAuthToken(const AuthCredentials * credentials,const std::string & spn,const std::string & channel_bindings,std::string * auth_token,const NetLogWithSource & net_log,net::CompletionOnceCallback callback)108 int HttpAuthNegotiateAndroid::GenerateAuthToken(
109     const AuthCredentials* credentials,
110     const std::string& spn,
111     const std::string& channel_bindings,
112     std::string* auth_token,
113     const NetLogWithSource& net_log,
114     net::CompletionOnceCallback callback) {
115   if (GetAuthAndroidNegotiateAccountType().empty()) {
116     // This can happen if there is a policy change, removing the account type,
117     // in the middle of a negotiation.
118     return ERR_UNSUPPORTED_AUTH_SCHEME;
119   }
120   DCHECK(auth_token);
121   DCHECK(completion_callback_.is_null());
122   DCHECK(!callback.is_null());
123 
124   auth_token_ = auth_token;
125   completion_callback_ = std::move(callback);
126   scoped_refptr<base::SingleThreadTaskRunner> callback_task_runner =
127       base::ThreadTaskRunnerHandle::Get();
128   base::OnceCallback<void(int, const std::string&)> thread_safe_callback =
129       base::BindOnce(&HttpAuthNegotiateAndroid::SetResultInternal,
130                      weak_factory_.GetWeakPtr());
131   JNIEnv* env = AttachCurrentThread();
132   ScopedJavaLocalRef<jstring> java_server_auth_token =
133       ConvertUTF8ToJavaString(env, server_auth_token_);
134   ScopedJavaLocalRef<jstring> java_spn = ConvertUTF8ToJavaString(env, spn);
135 
136   // It is intentional that callback_wrapper is not owned or deleted by the
137   // HttpAuthNegotiateAndroid object. The Java code will call the callback
138   // asynchronously on a different thread, and needs an object to call it on. As
139   // such, the callback_wrapper must not be deleted until the callback has been
140   // called, whatever happens to the HttpAuthNegotiateAndroid object.
141   //
142   // Unfortunately we have no automated way of managing C++ objects owned by
143   // Java, so the Java code must simply be written to guarantee that the
144   // callback is, in the end, called.
145   JavaNegotiateResultWrapper* callback_wrapper = new JavaNegotiateResultWrapper(
146       callback_task_runner, std::move(thread_safe_callback));
147   Java_HttpNegotiateAuthenticator_getNextAuthToken(
148       env, java_authenticator_, reinterpret_cast<intptr_t>(callback_wrapper),
149       java_spn, java_server_auth_token, can_delegate());
150   return ERR_IO_PENDING;
151 }
152 
SetDelegation(HttpAuth::DelegationType delegation_type)153 void HttpAuthNegotiateAndroid::SetDelegation(
154     HttpAuth::DelegationType delegation_type) {
155   DCHECK_NE(delegation_type, HttpAuth::DelegationType::kByKdcPolicy);
156   can_delegate_ = delegation_type == HttpAuth::DelegationType::kUnconstrained;
157 }
158 
GetAuthAndroidNegotiateAccountType() const159 std::string HttpAuthNegotiateAndroid::GetAuthAndroidNegotiateAccountType()
160     const {
161   return prefs_->AuthAndroidNegotiateAccountType();
162 }
163 
SetResultInternal(int result,const std::string & raw_token)164 void HttpAuthNegotiateAndroid::SetResultInternal(int result,
165                                                  const std::string& raw_token) {
166   DCHECK(auth_token_);
167   DCHECK(!completion_callback_.is_null());
168   if (result == OK)
169     *auth_token_ = "Negotiate " + raw_token;
170   std::move(completion_callback_).Run(result);
171 }
172 
173 }  // namespace android
174 }  // namespace net
175