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