Imported Upstream version 1.27.0
[platform/upstream/grpc.git] / include / grpcpp / security / credentials_impl.h
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 #ifndef GRPCPP_SECURITY_CREDENTIALS_IMPL_H
20 #define GRPCPP_SECURITY_CREDENTIALS_IMPL_H
21
22 #include <map>
23 #include <memory>
24 #include <vector>
25
26 #include <grpc/grpc_security_constants.h>
27 #include <grpcpp/channel_impl.h>
28 #include <grpcpp/impl/codegen/client_interceptor.h>
29 #include <grpcpp/impl/codegen/grpc_library.h>
30 #include <grpcpp/security/auth_context.h>
31 #include <grpcpp/security/tls_credentials_options.h>
32 #include <grpcpp/support/channel_arguments_impl.h>
33 #include <grpcpp/support/status.h>
34 #include <grpcpp/support/string_ref.h>
35
36 struct grpc_call;
37
38 namespace grpc_impl {
39
40 class ChannelCredentials;
41 class CallCredentials;
42 class SecureCallCredentials;
43 class SecureChannelCredentials;
44
45 std::shared_ptr<Channel> CreateCustomChannelImpl(
46     const grpc::string& target,
47     const std::shared_ptr<ChannelCredentials>& creds,
48     const ChannelArguments& args);
49
50 namespace experimental {
51 std::shared_ptr<Channel> CreateCustomChannelWithInterceptors(
52     const grpc::string& target,
53     const std::shared_ptr<ChannelCredentials>& creds,
54     const ChannelArguments& args,
55     std::vector<
56         std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
57         interceptor_creators);
58 }
59
60 /// A channel credentials object encapsulates all the state needed by a client
61 /// to authenticate with a server for a given channel.
62 /// It can make various assertions, e.g., about the client’s identity, role
63 /// for all the calls on that channel.
64 ///
65 /// \see https://grpc.io/docs/guides/auth.html
66 class ChannelCredentials : private grpc::GrpcLibraryCodegen {
67  public:
68   ChannelCredentials();
69   ~ChannelCredentials();
70
71  protected:
72   friend std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
73       const std::shared_ptr<ChannelCredentials>& channel_creds,
74       const std::shared_ptr<CallCredentials>& call_creds);
75
76   virtual SecureChannelCredentials* AsSecureCredentials() = 0;
77
78  private:
79   friend std::shared_ptr<Channel> CreateCustomChannelImpl(
80       const grpc::string& target,
81       const std::shared_ptr<ChannelCredentials>& creds,
82       const ChannelArguments& args);
83
84   friend std::shared_ptr<Channel>
85   grpc_impl::experimental::CreateCustomChannelWithInterceptors(
86       const grpc::string& target,
87       const std::shared_ptr<ChannelCredentials>& creds,
88       const ChannelArguments& args,
89       std::vector<std::unique_ptr<
90           grpc::experimental::ClientInterceptorFactoryInterface>>
91           interceptor_creators);
92
93   virtual std::shared_ptr<Channel> CreateChannelImpl(
94       const grpc::string& target, const ChannelArguments& args) = 0;
95
96   // This function should have been a pure virtual function, but it is
97   // implemented as a virtual function so that it does not break API.
98   virtual std::shared_ptr<Channel> CreateChannelWithInterceptors(
99       const grpc::string& /*target*/, const ChannelArguments& /*args*/,
100       std::vector<std::unique_ptr<
101           grpc::experimental::ClientInterceptorFactoryInterface>>
102       /*interceptor_creators*/) {
103     return nullptr;
104   }
105 };
106
107 /// A call credentials object encapsulates the state needed by a client to
108 /// authenticate with a server for a given call on a channel.
109 ///
110 /// \see https://grpc.io/docs/guides/auth.html
111 class CallCredentials : private grpc::GrpcLibraryCodegen {
112  public:
113   CallCredentials();
114   ~CallCredentials();
115
116   /// Apply this instance's credentials to \a call.
117   virtual bool ApplyToCall(grpc_call* call) = 0;
118
119  protected:
120   friend std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
121       const std::shared_ptr<ChannelCredentials>& channel_creds,
122       const std::shared_ptr<CallCredentials>& call_creds);
123
124   friend std::shared_ptr<CallCredentials> CompositeCallCredentials(
125       const std::shared_ptr<CallCredentials>& creds1,
126       const std::shared_ptr<CallCredentials>& creds2);
127
128   virtual SecureCallCredentials* AsSecureCredentials() = 0;
129 };
130
131 /// Options used to build SslCredentials.
132 struct SslCredentialsOptions {
133   /// The buffer containing the PEM encoding of the server root certificates. If
134   /// this parameter is empty, the default roots will be used.  The default
135   /// roots can be overridden using the \a GRPC_DEFAULT_SSL_ROOTS_FILE_PATH
136   /// environment variable pointing to a file on the file system containing the
137   /// roots.
138   grpc::string pem_root_certs;
139
140   /// The buffer containing the PEM encoding of the client's private key. This
141   /// parameter can be empty if the client does not have a private key.
142   grpc::string pem_private_key;
143
144   /// The buffer containing the PEM encoding of the client's certificate chain.
145   /// This parameter can be empty if the client does not have a certificate
146   /// chain.
147   grpc::string pem_cert_chain;
148 };
149
150 // Factories for building different types of Credentials The functions may
151 // return empty shared_ptr when credentials cannot be created. If a
152 // Credentials pointer is returned, it can still be invalid when used to create
153 // a channel. A lame channel will be created then and all rpcs will fail on it.
154
155 /// Builds credentials with reasonable defaults.
156 ///
157 /// \warning Only use these credentials when connecting to a Google endpoint.
158 /// Using these credentials to connect to any other service may result in this
159 /// service being able to impersonate your client for requests to Google
160 /// services.
161 std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials();
162
163 /// Builds SSL Credentials given SSL specific options
164 std::shared_ptr<ChannelCredentials> SslCredentials(
165     const SslCredentialsOptions& options);
166
167 /// Builds credentials for use when running in GCE
168 ///
169 /// \warning Only use these credentials when connecting to a Google endpoint.
170 /// Using these credentials to connect to any other service may result in this
171 /// service being able to impersonate your client for requests to Google
172 /// services.
173 std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials();
174
175 constexpr long kMaxAuthTokenLifetimeSecs = 3600;
176
177 /// Builds Service Account JWT Access credentials.
178 /// json_key is the JSON key string containing the client's private key.
179 /// token_lifetime_seconds is the lifetime in seconds of each Json Web Token
180 /// (JWT) created with this credentials. It should not exceed
181 /// \a kMaxAuthTokenLifetimeSecs or will be cropped to this value.
182 std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
183     const grpc::string& json_key,
184     long token_lifetime_seconds = grpc_impl::kMaxAuthTokenLifetimeSecs);
185
186 /// Builds refresh token credentials.
187 /// json_refresh_token is the JSON string containing the refresh token along
188 /// with a client_id and client_secret.
189 ///
190 /// \warning Only use these credentials when connecting to a Google endpoint.
191 /// Using these credentials to connect to any other service may result in this
192 /// service being able to impersonate your client for requests to Google
193 /// services.
194 std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
195     const grpc::string& json_refresh_token);
196
197 /// Builds access token credentials.
198 /// access_token is an oauth2 access token that was fetched using an out of band
199 /// mechanism.
200 ///
201 /// \warning Only use these credentials when connecting to a Google endpoint.
202 /// Using these credentials to connect to any other service may result in this
203 /// service being able to impersonate your client for requests to Google
204 /// services.
205 std::shared_ptr<CallCredentials> AccessTokenCredentials(
206     const grpc::string& access_token);
207
208 /// Builds IAM credentials.
209 ///
210 /// \warning Only use these credentials when connecting to a Google endpoint.
211 /// Using these credentials to connect to any other service may result in this
212 /// service being able to impersonate your client for requests to Google
213 /// services.
214 std::shared_ptr<CallCredentials> GoogleIAMCredentials(
215     const grpc::string& authorization_token,
216     const grpc::string& authority_selector);
217
218 /// Combines a channel credentials and a call credentials into a composite
219 /// channel credentials.
220 std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
221     const std::shared_ptr<ChannelCredentials>& channel_creds,
222     const std::shared_ptr<CallCredentials>& call_creds);
223
224 /// Combines two call credentials objects into a composite call credentials.
225 std::shared_ptr<CallCredentials> CompositeCallCredentials(
226     const std::shared_ptr<CallCredentials>& creds1,
227     const std::shared_ptr<CallCredentials>& creds2);
228
229 /// Credentials for an unencrypted, unauthenticated channel
230 std::shared_ptr<ChannelCredentials> InsecureChannelCredentials();
231
232 /// User defined metadata credentials.
233 class MetadataCredentialsPlugin {
234  public:
235   virtual ~MetadataCredentialsPlugin() {}
236
237   /// If this method returns true, the Process function will be scheduled in
238   /// a different thread from the one processing the call.
239   virtual bool IsBlocking() const { return true; }
240
241   /// Type of credentials this plugin is implementing.
242   virtual const char* GetType() const { return ""; }
243
244   /// Gets the auth metatada produced by this plugin.
245   /// The fully qualified method name is:
246   /// service_url + "/" + method_name.
247   /// The channel_auth_context contains (among other things), the identity of
248   /// the server.
249   virtual grpc::Status GetMetadata(
250       grpc::string_ref service_url, grpc::string_ref method_name,
251       const grpc::AuthContext& channel_auth_context,
252       std::multimap<grpc::string, grpc::string>* metadata) = 0;
253 };
254
255 std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
256     std::unique_ptr<MetadataCredentialsPlugin> plugin);
257
258 namespace experimental {
259
260 /// Options for creating STS Oauth Token Exchange credentials following the IETF
261 /// draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16.
262 /// Optional fields may be set to empty string. It is the responsibility of the
263 /// caller to ensure that the subject and actor tokens are refreshed on disk at
264 /// the specified paths.
265 struct StsCredentialsOptions {
266   grpc::string token_exchange_service_uri;  // Required.
267   grpc::string resource;                    // Optional.
268   grpc::string audience;                    // Optional.
269   grpc::string scope;                       // Optional.
270   grpc::string requested_token_type;        // Optional.
271   grpc::string subject_token_path;          // Required.
272   grpc::string subject_token_type;          // Required.
273   grpc::string actor_token_path;            // Optional.
274   grpc::string actor_token_type;            // Optional.
275 };
276
277 /// Creates STS Options from a JSON string. The JSON schema is as follows:
278 /// {
279 ///   "title": "STS Credentials Config",
280 ///   "type": "object",
281 ///   "required": ["token_exchange_service_uri", "subject_token_path",
282 ///                "subject_token_type"],
283 ///    "properties": {
284 ///      "token_exchange_service_uri": {
285 ///        "type": "string"
286 ///     },
287 ///     "resource": {
288 ///       "type": "string"
289 ///     },
290 ///     "audience": {
291 ///       "type": "string"
292 ///     },
293 ///     "scope": {
294 ///       "type": "string"
295 ///     },
296 ///     "requested_token_type": {
297 ///       "type": "string"
298 ///     },
299 ///     "subject_token_path": {
300 ///       "type": "string"
301 ///     },
302 ///     "subject_token_type": {
303 ///     "type": "string"
304 ///     },
305 ///     "actor_token_path" : {
306 ///       "type": "string"
307 ///     },
308 ///     "actor_token_type": {
309 ///       "type": "string"
310 ///     }
311 ///   }
312 /// }
313 grpc::Status StsCredentialsOptionsFromJson(const grpc::string& json_string,
314                                            StsCredentialsOptions* options);
315
316 /// Creates STS credentials options from the $STS_CREDENTIALS environment
317 /// variable. This environment variable points to the path of a JSON file
318 /// comforming to the schema described above.
319 grpc::Status StsCredentialsOptionsFromEnv(StsCredentialsOptions* options);
320
321 std::shared_ptr<CallCredentials> StsCredentials(
322     const StsCredentialsOptions& options);
323
324 std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
325     std::unique_ptr<MetadataCredentialsPlugin> plugin,
326     grpc_security_level min_security_level);
327
328 /// Options used to build AltsCredentials.
329 struct AltsCredentialsOptions {
330   /// service accounts of target endpoint that will be acceptable
331   /// by the client. If service accounts are provided and none of them matches
332   /// that of the server, authentication will fail.
333   std::vector<grpc::string> target_service_accounts;
334 };
335
336 /// Builds ALTS Credentials given ALTS specific options
337 std::shared_ptr<ChannelCredentials> AltsCredentials(
338     const AltsCredentialsOptions& options);
339
340 /// Builds Local Credentials.
341 std::shared_ptr<ChannelCredentials> LocalCredentials(
342     grpc_local_connect_type type);
343
344 /// Builds TLS Credentials given TLS options.
345 std::shared_ptr<ChannelCredentials> TlsCredentials(
346     const TlsCredentialsOptions& options);
347
348 }  // namespace experimental
349 }  // namespace grpc_impl
350
351 #endif  // GRPCPP_SECURITY_CREDENTIALS_IMPL_H