forked from oras-project/oras-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClient.java
More file actions
953 lines (864 loc) · 34 KB
/
Copy pathHttpClient.java
File metadata and controls
953 lines (864 loc) · 34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
/*-
* =LICENSE=
* ORAS Java SDK
* ===
* Copyright (C) 2024 - 2026 ORAS
* ===
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =LICENSEEND=
*/
package land.oras.auth;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.*;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedTrustManager;
import land.oras.ContainerRef;
import land.oras.OrasModel;
import land.oras.exception.OrasException;
import land.oras.utils.Const;
import land.oras.utils.JsonUtils;
import land.oras.utils.Versions;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTP client for ORAS
*/
@NullMarked
public final class HttpClient {
/**
* Logger
*/
private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class);
/**
* The pattern for the WWW-Authenticate header value
*/
private static final Pattern WWW_AUTH_VALUE_PATTERN =
Pattern.compile("Bearer realm=\"([^\"]+)\",service=\"([^\"]+)\",scope=\"([^\"]+)\"(,error=\"([^\"]+)\")?");
/**
* The HTTP client builder
*/
private final java.net.http.HttpClient.Builder builder;
/**
* The HTTP client
*/
private java.net.http.HttpClient client;
/**
* Skip TLS verification
*/
private boolean skipTlsVerify;
/**
* Path to a PEM-encoded CA certificate or bundle
*/
private @Nullable Path caFilePath;
/**
* PEM-encoded CA certificate or bundle content
*/
private @Nullable String caContent;
/**
* Timeout in seconds
*/
private Integer timeout;
/**
* The meter registry for metrics
*/
private MeterRegistry meterRegistry;
/**
* Hidden constructor
*/
private HttpClient() {
this.builder = java.net.http.HttpClient.newBuilder();
this.builder.followRedirects(
java.net.http.HttpClient.Redirect
.NEVER); // No automatic redirect, only GET and HEAD request will redirect
this.skipTlsVerify = false;
this.builder.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE));
this.setTimeout(60);
this.meterRegistry = Metrics.globalRegistry;
}
/**
* Set the timeout
* @param timeout The timeout in seconds
*/
private void setTimeout(@Nullable Integer timeout) {
if (timeout != null) {
this.timeout = timeout;
this.builder.connectTimeout(Duration.ofSeconds(timeout));
}
}
/**
* Skip the TLS verification
* @param skipTlsVerify Skip TLS verification
*/
private void setSkipTlsVerify(boolean skipTlsVerify) {
this.skipTlsVerify = skipTlsVerify;
}
/**
* Set the CA certificates for TLS verification from a file
* @param caFilePath The path to a PEM-encoded CA certificate or bundle
*/
private void setCaFile(Path caFilePath) {
this.caFilePath = caFilePath;
}
/**
* Set the CA certificates for TLS verification from PEM-encoded content
* @param caContent The PEM-encoded CA certificate or bundle content
*/
private void setCaContent(String caContent) {
this.caContent = caContent;
}
/**
* Configure SSL context from a PEM-encoded CA file
* @param caFilePath The path to a PEM-encoded CA certificate or bundle
*/
private void configureTlsFromFile(Path caFilePath) {
try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(caFilePath))) {
configureCaCertificates(inputStream, "CA file: " + caFilePath);
} catch (OrasException e) {
throw e;
} catch (Exception e) {
throw new OrasException("Unable to configure CA file: " + caFilePath, e);
}
}
/**
* Configure SSL context from PEM-encoded CA content
* @param caContent The PEM-encoded CA certificate or bundle content
*/
private void configureTlsFromContent(String caContent) {
try (InputStream inputStream = new ByteArrayInputStream(caContent.getBytes(StandardCharsets.UTF_8))) {
configureCaCertificates(inputStream, "CA content");
} catch (OrasException e) {
throw e;
} catch (Exception e) {
throw new OrasException("Unable to configure CA certificates from content", e);
}
}
/**
* Configure SSL context from PEM-encoded CA certificates read from the given input stream.
* @param inputStream The input stream containing PEM-encoded certificates
* @param source A description of the certificate source for error messages
*/
private void configureCaCertificates(InputStream inputStream, String source) throws Exception {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
int certificateIndex = 0;
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(inputStream);
if (certificates.isEmpty()) {
throw new OrasException("No certificates found in the provided " + source);
}
for (var certificate : certificates) {
trustStore.setCertificateEntry("ca-" + certificateIndex++, certificate);
}
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
builder.sslContext(sslContext);
}
/**
* Configure SSL context to skip TLS verification
*/
private void configureInsecureTls() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] {new InsecureTrustManager()}, new SecureRandom());
builder.sslContext(sslContext);
} catch (Exception e) {
throw new OrasException("Unable to skip TLS verification", e);
}
}
/**
* Create a new HTTP client
* @return The client
*/
public HttpClient build() {
if (caFilePath != null && caContent != null) {
throw new OrasException(
"Cannot configure both a CA file and CA content. Use either withCaFile() or withCaContent(), not both");
}
if (skipTlsVerify && (caFilePath != null || caContent != null)) {
throw new OrasException(
"Cannot combine skipTlsVerify with a CA file or CA content. Use either withSkipTlsVerify() or withCaFile()/withCaContent(), not both");
}
if (skipTlsVerify) {
configureInsecureTls();
} else if (caFilePath != null) {
configureTlsFromFile(caFilePath);
} else if (caContent != null) {
configureTlsFromContent(caContent);
}
this.client = this.builder.build();
return this;
}
/**
* Perform a GET request
* @param uri The URI
* @param headers The headers
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<String> get(URI uri, Map<String, String> headers, Scopes scopes, AuthProvider authProvider) {
return executeRequest(
"GET",
uri,
true,
headers,
new byte[0],
HttpResponse.BodyHandlers.ofString(),
HttpRequest.BodyPublishers.noBody(),
scopes,
authProvider);
}
/**
* Download to a file
* @param uri The URI
* @param headers The headers
* @param file The file
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<Path> download(
URI uri, Map<String, String> headers, Path file, Scopes scopes, AuthProvider authProvider) {
return executeRequest(
"GET",
uri,
true,
headers,
new byte[0],
HttpResponse.BodyHandlers.ofFile(file),
HttpRequest.BodyPublishers.noBody(),
scopes,
authProvider);
}
/**
* Download to to input stream
* @param uri The URI
* @param headers The headers
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<InputStream> download(
URI uri, Map<String, String> headers, Scopes scopes, AuthProvider authProvider) {
return executeRequest(
"GET",
uri,
true,
headers,
new byte[0],
HttpResponse.BodyHandlers.ofInputStream(),
HttpRequest.BodyPublishers.noBody(),
scopes,
authProvider);
}
/**
* Upload a file
* @param method The method (POST or PUT)
* @param uri The URI
* @param headers The headers
* @param file The file
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<String> upload(
String method, URI uri, Map<String, String> headers, Path file, Scopes scopes, AuthProvider authProvider) {
try {
return executeRequest(
method,
uri,
true,
headers,
new byte[0],
HttpResponse.BodyHandlers.ofString(),
HttpRequest.BodyPublishers.ofFile(file),
scopes,
authProvider);
} catch (FileNotFoundException e) {
throw new OrasException("Unable to upload file. File not found.", e);
}
}
/**
* Upload from an input stream.
* @param uri The URI
* @param size The size of the input stream
* @param headers The headers
* @param stream The input stream
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<String> upload(
URI uri,
long size,
Map<String, String> headers,
Supplier<InputStream> stream,
Scopes scopes,
AuthProvider authProvider) {
return executeRequest(
"PUT",
uri,
true,
headers,
new byte[0],
HttpResponse.BodyHandlers.ofString(),
HttpRequest.BodyPublishers.fromPublisher(HttpRequest.BodyPublishers.ofInputStream(stream), size),
scopes,
authProvider);
}
/**
* Perform a HEAD request
* @param uri The URI
* @param headers The headers
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<String> head(
URI uri, Map<String, String> headers, Scopes scopes, AuthProvider authProvider) {
return executeRequest(
"HEAD",
uri,
true,
headers,
new byte[0],
HttpResponse.BodyHandlers.ofString(),
HttpRequest.BodyPublishers.noBody(),
scopes,
authProvider);
}
/**
* Perform a DELETE request
* @param uri The URI
* @param headers The headers
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<String> delete(
URI uri, Map<String, String> headers, Scopes scopes, AuthProvider authProvider) {
return executeRequest(
"DELETE",
uri,
true,
headers,
new byte[0],
HttpResponse.BodyHandlers.ofString(),
HttpRequest.BodyPublishers.noBody(),
scopes,
authProvider);
}
/**
* Perform a POST request. Might not be suitable for large files. Use upload for large files.
* @param uri The URI.
* @param body The body
* @param headers The headers
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<String> post(
URI uri, byte[] body, Map<String, String> headers, Scopes scopes, AuthProvider authProvider) {
return executeRequest(
"POST",
uri,
true,
headers,
body,
HttpResponse.BodyHandlers.ofString(),
body.length == 0 ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofByteArray(body),
scopes,
authProvider);
}
/**
* Perform a Patch request
* @param uri The URI
* @param body The body
* @param headers The headers
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<String> patch(
URI uri, byte[] body, Map<String, String> headers, Scopes scopes, AuthProvider authProvider) {
return executeRequest(
"PATCH",
uri,
true,
headers,
body,
HttpResponse.BodyHandlers.ofString(),
HttpRequest.BodyPublishers.ofByteArray(body),
scopes,
authProvider);
}
/**
* Perform a PUT request
* @param uri The URI
* @param body The body
* @param headers The headers
* @param scopes The scopes
* @param authProvider The authentication provider
* @return The response
*/
public ResponseWrapper<String> put(
URI uri, byte[] body, Map<String, String> headers, Scopes scopes, AuthProvider authProvider) {
return executeRequest(
"PUT",
uri,
true,
headers,
body,
HttpResponse.BodyHandlers.ofString(),
HttpRequest.BodyPublishers.ofByteArray(body),
scopes,
authProvider);
}
/**
* Retrieve a token from the registry
* @param response The response that may contain a the WWW-Authenticate header
* @param scopes The scopes
* @param authProvider The authentication provider
* @param <T> The response type
* @return The token
*/
public <T> TokenResponse refreshToken(
HttpClient.ResponseWrapper<T> response, Scopes scopes, AuthProvider authProvider) {
String wwwAuthHeader = response.headers().getOrDefault(Const.WWW_AUTHENTICATE_HEADER.toLowerCase(), "");
LOG.debug("WWW-Authenticate header: {}", wwwAuthHeader);
if (wwwAuthHeader.isEmpty()) {
throw new OrasException(response.statusCode(), "No WWW-Authenticate header found in response");
}
Matcher matcher = WWW_AUTH_VALUE_PATTERN.matcher(wwwAuthHeader);
if (!matcher.matches()) {
throw new OrasException(response.statusCode(), "Invalid WWW-Authenticate header");
}
// Extract parts
String realm = matcher.group(1);
String service = matcher.group(2);
String scope = matcher.group(3);
String error = matcher.group(5);
// Add server scope to existing scopes
Scopes newScopes = scopes.withNewScope(scope).withService(service);
LOG.debug("New scopes with server: {}", newScopes.getScopes());
LOG.debug("WWW-Authenticate header: realm={}, service={}, scope={}, error={}", realm, service, scope, error);
String query = "scope=%s&service=%s".formatted(scope, URLEncoder.encode(service, StandardCharsets.UTF_8));
URI uri = URI.create(realm + "?" + query);
// Perform the request to get the token
Map<String, String> headers = new HashMap<>();
HttpClient.ResponseWrapper<String> responseWrapper = get(uri, headers, scopes, authProvider);
// Log the response
LOG.debug(
"Response: {}",
responseWrapper
.response()
.replaceAll("\"token\"\\s*:\\s*\"([A-Za-z0-9\\-_\\.=]+)\"", "\"token\":\"<redacted>\"")
.replaceAll(
"\"access_token\"\\s*:\\s*\"([A-Za-z0-9\\-_\\.=]+)\"",
"\"access_token\":\"<redacted>\""));
LOG.debug(
"Headers: {}",
responseWrapper.headers().entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> Const.AUTHORIZATION_HEADER.equalsIgnoreCase(entry.getKey())
? "<redacted" // Replace value with ****
: entry.getValue())));
// Put in the cache
TokenResponse token = JsonUtils.fromJson(responseWrapper.response(), TokenResponse.class)
.forService(service);
TokenCache.put(newScopes, token);
meterRegistry
.counter(Const.METRIC_TOKEN_REFRESH, Const.METRIC_TAG_SERVICE, service, Const.METRIC_TAG_REALM, realm)
.increment();
return token;
}
static boolean isSameOrigin(URI uri1, URI uri2) {
return Objects.equals(uri1.getScheme(), uri2.getScheme())
&& Objects.equals(uri1.getHost(), uri2.getHost())
&& getPort(uri1) == getPort(uri2);
}
static int getPort(URI uri) {
return uri.getPort() != -1 ? uri.getPort() : ("https".equals(uri.getScheme()) ? 443 : 80);
}
static <T> boolean shouldRedirect(HttpResponse<T> response) {
return response.statusCode() == HttpURLConnection.HTTP_MOVED_PERM
|| response.statusCode() == HttpURLConnection.HTTP_MOVED_TEMP
|| response.statusCode() == 307;
}
/**
* Execute a request
* @param method The method
* @param uri The URI
* @param headers The headers
* @param body The body
* @param handler The response handler
* @param bodyPublisher The body publisher
* @param authProvider The authentication provider
* @return The response
*/
private <T> ResponseWrapper<T> executeRequest(
String method,
URI uri,
boolean includeAuthHeader,
Map<String, String> headers,
byte[] body,
HttpResponse.BodyHandler<T> handler,
HttpRequest.BodyPublisher bodyPublisher,
Scopes scopes,
AuthProvider authProvider) {
try {
HttpRequest.Builder builder = HttpRequest.newBuilder().uri(uri).method(method, bodyPublisher);
// Get scope based on method
ContainerRef containerRef = scopes.getContainerRef();
LOG.debug("Scopes are adding registry scopes");
Scopes newScopes =
switch (method) {
case "GET", "HEAD" -> scopes.withAddedRegistryScopes(Scope.PULL);
case "POST", "PUT", "PATCH" -> scopes.withAddedRegistryScopes(Scope.PUSH);
case "DELETE" -> scopes.withAddedRegistryScopes(Scope.DELETE);
default -> throw new OrasException("Unsupported HTTP method: " + method);
};
LOG.debug("Existing scopes: {}", scopes.getScopes());
LOG.debug("New scopes: {}", newScopes.getScopes());
// Check if token is present and reuse auth instead of passing auth provider
TokenResponse cachedToken = TokenCache.get(newScopes);
if (cachedToken == null) {
LOG.trace("No token found in cache for scopes: {}", newScopes);
} else {
LOG.trace("Found token in cache for scopes: {}", newScopes.withService(cachedToken.service()));
}
// Add authentication header if any (from provider or cached token)
var authHeader = authProvider.getAuthHeader(containerRef);
if (cachedToken == null
&& authHeader != null
&& !authProvider.getAuthScheme().equals(AuthScheme.NONE)
&& includeAuthHeader) {
builder = builder.header(Const.AUTHORIZATION_HEADER, authHeader);
} else if (cachedToken != null && includeAuthHeader) {
builder = builder.header(Const.AUTHORIZATION_HEADER, "Bearer " + cachedToken.getEffectiveToken());
}
headers.forEach(builder::header);
// Add user agent
builder = builder.header(Const.USER_AGENT_HEADER, Versions.USER_AGENT_VALUE);
HttpRequest request = builder.build();
logRequest(request, body);
HttpResponse<T> response = executeAndRecordRequest(request, handler);
// Follow redirect
if (shouldRedirect(response)) {
String location = getLocationHeader(response);
URI redirectUri = URI.create(location);
LOG.debug("Redirecting to {} from domain {} to domain {}", location, uri, redirectUri);
boolean includeAuthHeaderForRedirect = isSameOrigin(uri, redirectUri);
if (!includeAuthHeaderForRedirect) {
LOG.debug("Skipping auth header for redirect from {} to {}", uri, redirectUri);
}
return executeRequest(
method,
redirectUri,
includeAuthHeaderForRedirect,
headers,
body,
handler,
bodyPublisher,
newScopes,
authProvider);
}
return redoRequest(uri, response, builder, handler, newScopes, authProvider);
} catch (Exception e) {
if (e instanceof OrasException) {
throw (OrasException) e;
}
LOG.error("Failed to execute request", e);
throw new OrasException("Unable to create HTTP request", e);
}
}
private <T> HttpResponse<T> executeAndRecordRequest(HttpRequest request, HttpResponse.BodyHandler<T> handler)
throws Exception {
long start = System.nanoTime();
HttpResponse<T> response = client.send(request, handler);
long duration = System.nanoTime() - start;
Timer.builder(Const.METRIC_HTTP_REQUESTS)
.tag("method", request.method())
.tag("host", request.uri().getHost())
.tag("status", response != null ? String.valueOf(response.statusCode()) : "IO_ERROR")
.register(meterRegistry)
.record(duration, TimeUnit.NANOSECONDS);
if (response == null) {
throw new OrasException("No response received");
}
return response;
}
private <T> String getLocationHeader(HttpResponse<T> response) {
return response.headers()
.firstValue("Location")
.orElseThrow(() -> new OrasException("No Location header found"));
}
private <T> ResponseWrapper<T> redoRequest(
URI originUri,
HttpResponse<T> response,
HttpRequest.Builder builder,
HttpResponse.BodyHandler<T> handler,
Scopes scopes,
AuthProvider authProvider) {
if ((response.statusCode() == 401 || response.statusCode() == 403)) {
LOG.debug("Requesting new token...");
HttpClient.TokenResponse token =
refreshToken(toResponseWrapper(response, scopes.getService()), scopes, authProvider);
if (token.issued_at() != null && token.expires_in() != null) {
LOG.debug(
"Received token issued_at {}, expire_id {} and expiring at {} ",
token.issued_at(),
token.expires_in(),
token.issued_at().plusSeconds(token.expires_in()));
}
String bearerToken = token.getEffectiveToken();
String service = token.service();
try {
builder = builder.setHeader(Const.AUTHORIZATION_HEADER, "Bearer " + bearerToken);
HttpResponse<T> newResponse = executeAndRecordRequest(builder.build(), handler);
// Follow redirect
if (shouldRedirect(newResponse)) {
String location = getLocationHeader(newResponse);
URI redirectUri = URI.create(location);
LOG.debug("Redirecting to {} from domain {} to domain {}", location, originUri, redirectUri);
boolean includeAuthHeaderForRedirect = isSameOrigin(originUri, redirectUri);
if (!includeAuthHeaderForRedirect) {
LOG.debug("Skipping auth header for redirect from {} to {}", originUri, redirectUri);
builder = HttpRequest.newBuilder(
builder.build(), (name, value) -> !name.equalsIgnoreCase(Const.AUTHORIZATION_HEADER));
}
return toResponseWrapper(
executeAndRecordRequest(
builder.uri(URI.create(location)).build(), handler),
service);
}
return toResponseWrapper(newResponse, service);
} catch (Exception e) {
LOG.error("Failed to redo request", e);
throw new OrasException("Unable to redo HTTP request", e);
}
}
return toResponseWrapper(response, scopes.getService());
}
private <T> ResponseWrapper<T> toResponseWrapper(HttpResponse<T> response, @Nullable String service) {
return new ResponseWrapper<>(
response.body(),
response.statusCode(),
response.headers().map().entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey, e -> e.getValue().get(0))),
service);
}
/**
* Logs the request in debug/trace mode
* @param request The request
* @param body The body
*/
private void logRequest(HttpRequest request, byte[] body) {
LOG.debug("Executing {} request to {}", request.method(), request.uri());
LOG.debug(
"Headers: {}",
request.headers().map().entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> Const.AUTHORIZATION_HEADER.equalsIgnoreCase(entry.getKey())
? List.of("<redacted>") // Replace value with ****
: entry.getValue())));
// Log the body in trace mode
if (LOG.isTraceEnabled()) {
LOG.trace("Body: {}", new String(body, StandardCharsets.UTF_8));
}
}
/**
* Response wrapper
* @param <T> The response type
* @param response The response
* @param statusCode The status code
* @param headers The headers
* @param service The service (not on response but on HTTP headers)
*/
public record ResponseWrapper<T>(
T response, int statusCode, Map<String, String> headers, @Nullable String service) {}
/**
* Insecure trust manager when skipping TLS verification
*/
@SuppressWarnings("java:S4830")
private static class InsecureTrustManager extends X509ExtendedTrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) {}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {}
}
/**
* The token response
* @param token The token
* @param service The service (not on response but on HTTP headers)
* @param access_token The access token
* @param expires_in The expires in
* @param issued_at The issued at
*/
@OrasModel
public record TokenResponse(
String token,
@Nullable String access_token,
@Nullable String service,
@Nullable Integer expires_in,
@Nullable ZonedDateTime issued_at) {
/**
* Create a new token response with the service field set
* @param service The service
* @return A new token response with the service field set
*/
public TokenResponse forService(String service) {
return new TokenResponse(token, access_token, service, expires_in, issued_at);
}
/**
* >>>>>>> 6379975 (Store token into caffeine cache (#631))
* Get the effective token
* @return The effective token, which is either the access_token or the token field depending on which one is present
*/
public String getEffectiveToken() {
return access_token != null ? access_token : token;
}
@Override
public String toString() {
return "TokenResponse{" + "expires_in=" + expires_in + ", issued_at=" + issued_at + '}';
}
}
/**
* Builder for the HTTP client
*/
public static class Builder {
private final HttpClient client = new HttpClient();
/**
* Hidden constructor
*/
private Builder() {}
/**
* Set the timeout
* @param timeout The timeout in seconds
* @return The builder
*/
public Builder withTimeout(@Nullable Integer timeout) {
client.setTimeout(timeout);
return this;
}
/**
* Skip the TLS verification
* @param skipTlsVerify Skip TLS verification
* @return The builder
*/
public Builder withSkipTlsVerify(boolean skipTlsVerify) {
client.setSkipTlsVerify(skipTlsVerify);
return this;
}
/**
* Set the meter registry for metrics. Following Micrometer best practices for libraries,
* @param meterRegistry The meter registry
* @return The builder
*/
public Builder withMeterRegistry(MeterRegistry meterRegistry) {
client.meterRegistry = meterRegistry;
return this;
}
/**
* Set the CA file for TLS verification
* @param caFilePath The path to a PEM-encoded CA certificate or bundle
* @return The builder
*/
public Builder withCaFile(Path caFilePath) {
client.setCaFile(caFilePath);
return this;
}
/**
* Set the CA file for TLS verification
* @param caFilePath The path to a PEM-encoded CA certificate or bundle
* @return The builder
*/
public Builder withCaFile(String caFilePath) {
return withCaFile(Path.of(caFilePath));
}
/**
* Set the CA certificates from PEM-encoded content
* @param caContent The PEM-encoded CA certificate or bundle content
* @return The builder
*/
public Builder withCaContent(String caContent) {
client.setCaContent(caContent);
return this;
}
/**
* Build the client
* @return The client
*/
public static Builder builder() {
return new Builder();
}
/**
* Build the client
* @return The client
*/
public HttpClient build() {
return client.build();
}
}
}