Debian Codegraph @

src/core/lib/security/credentials/jwt/jwt_credentials.cc

raw
1 /*
2 *
3 * Copyright 2016 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 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/security/credentials/jwt/jwt_credentials.h"
22
23 #include <inttypes.h>
24 #include <stdlib.h>
25
26 #include <memory>
27 #include <string>
28 #include <utility>
29
30 #include "absl/status/status.h"
31 #include "absl/strings/str_cat.h"
32
33 #include <grpc/support/alloc.h>
34 #include <grpc/support/log.h>
35 #include <grpc/support/string_util.h>
36 #include <grpc/support/sync.h>
37
38 #include "src/core/lib/debug/trace.h"
39 #include "src/core/lib/gprpp/ref_counted_ptr.h"
40 #include "src/core/lib/iomgr/exec_ctx.h"
41 #include "src/core/lib/json/json.h"
42 #include "src/core/lib/promise/promise.h"
43 #include "src/core/lib/security/credentials/call_creds_util.h"
44 #include "src/core/lib/surface/api_trace.h"
45 #include "src/core/lib/transport/metadata_batch.h"
46 #include "src/core/lib/uri/uri_parser.h"
47
48 using grpc_core::Json;
49
50 grpc_service_account_jwt_access_credentials::
51 ~grpc_service_account_jwt_access_credentials() {
52 grpc_auth_json_key_destruct(&key_);
53 gpr_mu_destroy(&cache_mu_);
54 }
55
56 grpc_core::ArenaPromise<absl::StatusOr<grpc_core::ClientMetadataHandle>>
57 grpc_service_account_jwt_access_credentials::GetRequestMetadata(
58 grpc_core::ClientMetadataHandle initial_metadata,
59 const grpc_call_credentials::GetRequestMetadataArgs* args) {
60 gpr_timespec refresh_threshold = gpr_time_from_seconds(
61 GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS, GPR_TIMESPAN);
62
63 // Remove service name from service_url to follow the audience format
64 // dictated in https://google.aip.dev/auth/4111.
65 absl::StatusOr<std::string> uri = grpc_core::RemoveServiceNameFromJwtUri(
66 grpc_core::MakeJwtServiceUrl(initial_metadata, args));
67 if (!uri.ok()) {
68 return grpc_core::Immediate(uri.status());
69 }
70 // See if we can return a cached jwt.
71 absl::optional<grpc_core::Slice> jwt_value;
72 {
73 gpr_mu_lock(&cache_mu_);
74 if (cached_.has_value() && cached_->service_url == *uri &&
75 (gpr_time_cmp(
76 gpr_time_sub(cached_->jwt_expiration, gpr_now(GPR_CLOCK_REALTIME)),
77 refresh_threshold) > 0)) {
78 jwt_value = cached_->jwt_value.Ref();
79 }
80 gpr_mu_unlock(&cache_mu_);
81 }
82
83 if (!jwt_value.has_value()) {
84 char* jwt = nullptr;
85 // Generate a new jwt.
86 gpr_mu_lock(&cache_mu_);
87 cached_.reset();
88 jwt = grpc_jwt_encode_and_sign(&key_, uri->c_str(), jwt_lifetime_, nullptr);
89 if (jwt != nullptr) {
90 std::string md_value = absl::StrCat("Bearer ", jwt);
91 gpr_free(jwt);
92 jwt_value = grpc_core::Slice::FromCopiedString(md_value);
93 cached_ = {jwt_value->Ref(), std::move(*uri),
94 gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), jwt_lifetime_)};
95 }
96 gpr_mu_unlock(&cache_mu_);
97 }
98
99 if (!jwt_value.has_value()) {
100 return grpc_core::Immediate(
101 absl::UnauthenticatedError("Could not generate JWT."));
102 }
103
104 initial_metadata->Append(
105 GRPC_AUTHORIZATION_METADATA_KEY, std::move(*jwt_value),
106 [](absl::string_view, const grpc_core::Slice&) { abort(); });
107 return grpc_core::Immediate(std::move(initial_metadata));
108 }
109
110 grpc_service_account_jwt_access_credentials::
111 grpc_service_account_jwt_access_credentials(grpc_auth_json_key key,
112 gpr_timespec token_lifetime)
113 : key_(key) {
114 gpr_timespec max_token_lifetime = grpc_max_auth_token_lifetime();
115 if (gpr_time_cmp(token_lifetime, max_token_lifetime) > 0) {
116 gpr_log(GPR_INFO,
117 "Cropping token lifetime to maximum allowed value (%d secs).",
118 static_cast<int>(max_token_lifetime.tv_sec));
119 token_lifetime = grpc_max_auth_token_lifetime();
120 }
121 jwt_lifetime_ = token_lifetime;
122 gpr_mu_init(&cache_mu_);
123 }
124
125 grpc_core::UniqueTypeName grpc_service_account_jwt_access_credentials::Type() {
126 static grpc_core::UniqueTypeName::Factory kFactory("Jwt");
127 return kFactory.Create();
128 }
129
130 grpc_core::RefCountedPtr<grpc_call_credentials>
131 grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
132 grpc_auth_json_key key, gpr_timespec token_lifetime) {
133 if (!grpc_auth_json_key_is_valid(&key)) {
134 gpr_log(GPR_ERROR, "Invalid input for jwt credentials creation");
135 return nullptr;
136 }
137 return grpc_core::MakeRefCounted<grpc_service_account_jwt_access_credentials>(
138 key, token_lifetime);
139 }
140
141 static char* redact_private_key(const char* json_key) {
142 auto json = Json::Parse(json_key);
143 if (!json.ok() || json->type() != Json::Type::OBJECT) {
144 return gpr_strdup("<Json failed to parse.>");
145 }
146 (*json->mutable_object())["private_key"] = "<redacted>";
147 return gpr_strdup(json->Dump(/*indent=*/2).c_str());
148 }
149
150 grpc_call_credentials* grpc_service_account_jwt_access_credentials_create(
151 const char* json_key, gpr_timespec token_lifetime, void* reserved) {
152 if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) {
153 char* clean_json = redact_private_key(json_key);
154 gpr_log(GPR_INFO,
155 "grpc_service_account_jwt_access_credentials_create("
156 "json_key=%s, "
157 "token_lifetime="
158 "gpr_timespec { tv_sec: %" PRId64
159 ", tv_nsec: %d, clock_type: %d }, "
160 "reserved=%p)",
161 clean_json, token_lifetime.tv_sec, token_lifetime.tv_nsec,
162 static_cast<int>(token_lifetime.clock_type), reserved);
163 gpr_free(clean_json);
164 }
165 GPR_ASSERT(reserved == nullptr);
166 grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
167 grpc_core::ExecCtx exec_ctx;
168 return grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
169 grpc_auth_json_key_create_from_string(json_key), token_lifetime)
170 .release();
171 }
172
173 namespace grpc_core {
174
175 absl::StatusOr<std::string> RemoveServiceNameFromJwtUri(absl::string_view uri) {
176 auto parsed = URI::Parse(uri);
177 if (!parsed.ok()) {
178 return parsed.status();
179 }
180 return absl::StrFormat("%s://%s/", parsed->scheme(), parsed->authority());
181 }
182
183 } // namespace grpc_core