credentials.h 14 KB

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