You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

credentials.h 16 kB

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