-
Notifications
You must be signed in to change notification settings - Fork 32
/
aws_imds_client.c
1847 lines (1594 loc) · 70.4 KB
/
aws_imds_client.c
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/auth/aws_imds_client.h>
#include <aws/auth/private/credentials_utils.h>
#include <aws/common/clock.h>
#include <aws/common/condition_variable.h>
#include <aws/common/mutex.h>
#include <aws/common/string.h>
#include <aws/http/connection.h>
#include <aws/http/request_response.h>
#include <aws/http/status_code.h>
#include <aws/io/channel_bootstrap.h>
#include <aws/io/socket.h>
#include <ctype.h>
#include <aws/common/json.h>
#if defined(_MSC_VER)
# pragma warning(disable : 4204)
# pragma warning(disable : 4232)
#endif /* _MSC_VER */
/* instance role credentials body response is currently ~ 1300 characters + name length */
#define IMDS_RESPONSE_SIZE_INITIAL 2048
#define IMDS_RESPONSE_TOKEN_SIZE_INITIAL 64
#define IMDS_RESPONSE_SIZE_LIMIT 65535
#define IMDS_CONNECT_TIMEOUT_DEFAULT_IN_SECONDS 2
#define IMDS_DEFAULT_RETRIES 1
AWS_STATIC_STRING_FROM_LITERAL(s_imds_host, "169.254.169.254");
enum imds_token_state {
AWS_IMDS_TS_INVALID,
AWS_IMDS_TS_VALID,
AWS_IMDS_TS_UPDATE_IN_PROGRESS,
};
enum imds_token_copy_result {
/* Token is valid and copied to requester */
AWS_IMDS_TCR_SUCCESS,
/* Token is updating, so requester is added in waiting queue */
AWS_IMDS_TCR_WAITING_IN_QUEUE,
/* unexpected error,like mem allocation error */
AWS_IMDS_TCR_UNEXPECTED_ERROR,
};
struct imds_token_query {
struct aws_linked_list_node node;
void *user_data;
};
struct aws_imds_client {
struct aws_allocator *allocator;
struct aws_http_connection_manager *connection_manager;
struct aws_retry_strategy *retry_strategy;
const struct aws_auth_http_system_vtable *function_table;
struct aws_imds_client_shutdown_options shutdown_options;
/* will be set to true by default, means using IMDS V2 */
bool token_required;
struct aws_byte_buf cached_token;
uint64_t cached_token_expiration_timestamp;
enum imds_token_state token_state;
struct aws_linked_list pending_queries;
struct aws_mutex token_lock;
struct aws_condition_variable token_signal;
bool ec2_metadata_v1_disabled;
struct aws_atomic_var ref_count;
};
static void s_aws_imds_client_destroy(struct aws_imds_client *client) {
if (!client) {
return;
}
/**
* s_aws_imds_client_destroy is only called after all in-flight requests are finished,
* thus nothing is going to try and access retry_strategy again at this point.
*/
aws_retry_strategy_release(client->retry_strategy);
aws_condition_variable_clean_up(&client->token_signal);
aws_mutex_clean_up(&client->token_lock);
aws_byte_buf_clean_up(&client->cached_token);
client->function_table->aws_http_connection_manager_release(client->connection_manager);
/* freeing the client takes place in the shutdown callback below */
}
static void s_on_connection_manager_shutdown(void *user_data) {
struct aws_imds_client *client = user_data;
if (client && client->shutdown_options.shutdown_callback) {
client->shutdown_options.shutdown_callback(client->shutdown_options.shutdown_user_data);
}
aws_mem_release(client->allocator, client);
}
void aws_imds_client_release(struct aws_imds_client *client) {
if (!client) {
return;
}
size_t old_value = aws_atomic_fetch_sub(&client->ref_count, 1);
if (old_value == 1) {
s_aws_imds_client_destroy(client);
}
}
void aws_imds_client_acquire(struct aws_imds_client *client) {
aws_atomic_fetch_add(&client->ref_count, 1);
}
struct aws_imds_client *aws_imds_client_new(
struct aws_allocator *allocator,
const struct aws_imds_client_options *options) {
if (!options->bootstrap) {
AWS_LOGF_ERROR(AWS_LS_AUTH_CREDENTIALS_PROVIDER, "Client bootstrap is required for querying IMDS");
aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
return NULL;
}
struct aws_imds_client *client = aws_mem_calloc(allocator, 1, sizeof(struct aws_imds_client));
if (!client) {
return NULL;
}
if (aws_mutex_init(&client->token_lock)) {
goto on_error;
}
if (aws_condition_variable_init(&client->token_signal)) {
goto on_error;
}
if (aws_byte_buf_init(&client->cached_token, allocator, IMDS_RESPONSE_TOKEN_SIZE_INITIAL)) {
goto on_error;
}
aws_linked_list_init(&client->pending_queries);
aws_atomic_store_int(&client->ref_count, 1);
client->allocator = allocator;
client->function_table =
options->function_table ? options->function_table : g_aws_credentials_provider_http_function_table;
client->token_required = options->imds_version == IMDS_PROTOCOL_V1 ? false : true;
client->ec2_metadata_v1_disabled = options->ec2_metadata_v1_disabled;
client->shutdown_options = options->shutdown_options;
struct aws_socket_options socket_options;
AWS_ZERO_STRUCT(socket_options);
socket_options.type = AWS_SOCKET_STREAM;
socket_options.domain = AWS_SOCKET_IPV4;
socket_options.connect_timeout_ms = (uint32_t)aws_timestamp_convert(
IMDS_CONNECT_TIMEOUT_DEFAULT_IN_SECONDS, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_MILLIS, NULL);
struct aws_http_connection_manager_options manager_options;
AWS_ZERO_STRUCT(manager_options);
manager_options.bootstrap = options->bootstrap;
manager_options.initial_window_size = IMDS_RESPONSE_SIZE_LIMIT;
manager_options.socket_options = &socket_options;
manager_options.tls_connection_options = NULL;
manager_options.host = aws_byte_cursor_from_string(s_imds_host);
manager_options.port = 80;
manager_options.max_connections = 10;
manager_options.shutdown_complete_callback = s_on_connection_manager_shutdown;
manager_options.shutdown_complete_user_data = client;
client->connection_manager = client->function_table->aws_http_connection_manager_new(allocator, &manager_options);
if (!client->connection_manager) {
goto on_error;
}
if (options->retry_strategy) {
client->retry_strategy = options->retry_strategy;
aws_retry_strategy_acquire(client->retry_strategy);
} else {
struct aws_exponential_backoff_retry_options retry_options = {
.el_group = options->bootstrap->event_loop_group,
.max_retries = IMDS_DEFAULT_RETRIES,
};
/* exponential backoff is plenty here. We're hitting a local endpoint and do not run the risk of bringing
* down more than the local VM. */
client->retry_strategy = aws_retry_strategy_new_exponential_backoff(allocator, &retry_options);
}
if (!client->retry_strategy) {
goto on_error;
}
return client;
on_error:
s_aws_imds_client_destroy(client);
return NULL;
}
/*
* Tracking structure for each outstanding async query to an imds client
*/
struct imds_user_data {
/* immutable post-creation */
struct aws_allocator *allocator;
struct aws_imds_client *client;
aws_imds_client_on_get_resource_callback_fn *original_callback;
void *original_user_data;
/* mutable */
struct aws_http_connection *connection;
struct aws_http_message *request;
struct aws_byte_buf current_result;
struct aws_byte_buf imds_token;
struct aws_string *resource_path;
struct aws_retry_token *retry_token;
/*
* initial value is copy of client->token_required,
* will be adapted according to response.
*/
bool imds_token_required;
/* Indicate the request is a fallback from a failure call. */
bool is_fallback_request;
bool is_imds_token_request;
bool ec2_metadata_v1_disabled;
int status_code;
int error_code;
struct aws_atomic_var ref_count;
};
static void s_user_data_destroy(struct imds_user_data *user_data) {
if (user_data == NULL) {
return;
}
struct aws_imds_client *client = user_data->client;
if (user_data->connection) {
client->function_table->aws_http_connection_manager_release_connection(
client->connection_manager, user_data->connection);
}
aws_byte_buf_clean_up(&user_data->current_result);
aws_byte_buf_clean_up(&user_data->imds_token);
aws_string_destroy(user_data->resource_path);
if (user_data->request) {
aws_http_message_destroy(user_data->request);
}
aws_retry_token_release(user_data->retry_token);
aws_imds_client_release(client);
aws_mem_release(user_data->allocator, user_data);
}
static struct imds_user_data *s_user_data_new(
struct aws_imds_client *client,
struct aws_byte_cursor resource_path,
aws_imds_client_on_get_resource_callback_fn *callback,
void *user_data) {
struct imds_user_data *wrapped_user_data = aws_mem_calloc(client->allocator, 1, sizeof(struct imds_user_data));
if (!wrapped_user_data) {
goto on_error;
}
wrapped_user_data->allocator = client->allocator;
wrapped_user_data->client = client;
aws_imds_client_acquire(client);
wrapped_user_data->original_user_data = user_data;
wrapped_user_data->original_callback = callback;
if (aws_byte_buf_init(&wrapped_user_data->current_result, client->allocator, IMDS_RESPONSE_SIZE_INITIAL)) {
goto on_error;
}
if (aws_byte_buf_init(&wrapped_user_data->imds_token, client->allocator, IMDS_RESPONSE_TOKEN_SIZE_INITIAL)) {
goto on_error;
}
wrapped_user_data->resource_path =
aws_string_new_from_array(client->allocator, resource_path.ptr, resource_path.len);
if (!wrapped_user_data->resource_path) {
goto on_error;
}
wrapped_user_data->imds_token_required = client->token_required;
wrapped_user_data->ec2_metadata_v1_disabled = client->ec2_metadata_v1_disabled;
aws_atomic_store_int(&wrapped_user_data->ref_count, 1);
return wrapped_user_data;
on_error:
s_user_data_destroy(wrapped_user_data);
return NULL;
}
static void s_user_data_acquire(struct imds_user_data *user_data) {
if (user_data == NULL) {
return;
}
aws_atomic_fetch_add(&user_data->ref_count, 1);
}
static void s_user_data_release(struct imds_user_data *user_data) {
if (!user_data) {
return;
}
size_t old_value = aws_atomic_fetch_sub(&user_data->ref_count, 1);
if (old_value == 1) {
s_user_data_destroy(user_data);
}
}
static void s_reset_scratch_user_data(struct imds_user_data *user_data) {
user_data->current_result.len = 0;
user_data->status_code = 0;
if (user_data->request) {
aws_http_message_destroy(user_data->request);
user_data->request = NULL;
}
}
static enum imds_token_copy_result s_copy_token_safely(struct imds_user_data *user_data);
static void s_update_token_safely(
struct aws_imds_client *client,
struct aws_byte_buf *token,
bool token_required,
uint64_t expire_timestamp);
static void s_query_complete(struct imds_user_data *user_data);
static void s_on_acquire_connection(struct aws_http_connection *connection, int error_code, void *user_data);
static void s_on_retry_token_acquired(struct aws_retry_strategy *, int, struct aws_retry_token *, void *);
static int s_on_incoming_body_fn(struct aws_http_stream *stream, const struct aws_byte_cursor *data, void *user_data) {
(void)stream;
(void)data;
struct imds_user_data *imds_user_data = user_data;
struct aws_imds_client *client = imds_user_data->client;
if (data->len + imds_user_data->current_result.len > IMDS_RESPONSE_SIZE_LIMIT) {
client->function_table->aws_http_connection_close(imds_user_data->connection);
AWS_LOGF_ERROR(
AWS_LS_IMDS_CLIENT, "(id=%p) IMDS client query response exceeded maximum allowed length", (void *)client);
return aws_raise_error(AWS_AUTH_IMDS_CLIENT_SOURCE_FAILURE);
}
if (aws_byte_buf_append_dynamic(&imds_user_data->current_result, data)) {
client->function_table->aws_http_connection_close(imds_user_data->connection);
AWS_LOGF_ERROR(AWS_LS_IMDS_CLIENT, "(id=%p) IMDS client query error appending response", (void *)client);
return AWS_OP_ERR;
}
return AWS_OP_SUCCESS;
}
static int s_on_incoming_headers_fn(
struct aws_http_stream *stream,
enum aws_http_header_block header_block,
const struct aws_http_header *header_array,
size_t num_headers,
void *user_data) {
(void)header_array;
(void)num_headers;
if (header_block != AWS_HTTP_HEADER_BLOCK_MAIN) {
return AWS_OP_SUCCESS;
}
struct imds_user_data *imds_user_data = user_data;
struct aws_imds_client *client = imds_user_data->client;
if (header_block == AWS_HTTP_HEADER_BLOCK_MAIN) {
if (imds_user_data->status_code == 0) {
if (client->function_table->aws_http_stream_get_incoming_response_status(
stream, &imds_user_data->status_code)) {
AWS_LOGF_ERROR(
AWS_LS_IMDS_CLIENT, "(id=%p) IMDS client failed to get http status code", (void *)client);
return AWS_OP_ERR;
}
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client query received http status code %d for requester %p.",
(void *)client,
imds_user_data->status_code,
user_data);
}
}
return AWS_OP_SUCCESS;
}
AWS_STATIC_STRING_FROM_LITERAL(s_imds_host_header, "Host");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_accept_header, "Accept");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_accept_header_value, "*/*");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_user_agent_header, "User-Agent");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_user_agent_header_value, "aws-sdk-crt/aws-imds-client");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_h1_0_keep_alive_header, "Connection");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_h1_0_keep_alive_header_value, "keep-alive");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_token_resource_path, "/latest/api/token");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_token_ttl_header, "x-aws-ec2-metadata-token-ttl-seconds");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_token_header, "x-aws-ec2-metadata-token");
AWS_STATIC_STRING_FROM_LITERAL(s_imds_token_ttl_default_value, "21600");
/* s_imds_token_ttl_default_value - 5secs for refreshing the cached token */
static const uint64_t s_imds_token_ttl_secs = 21595;
static void s_on_stream_complete_fn(struct aws_http_stream *stream, int error_code, void *user_data);
static int s_make_imds_http_query(
struct imds_user_data *user_data,
const struct aws_byte_cursor *verb,
const struct aws_byte_cursor *uri,
const struct aws_http_header *headers,
size_t header_count) {
AWS_FATAL_ASSERT(user_data->connection);
struct aws_imds_client *client = user_data->client;
struct aws_http_stream *stream = NULL;
struct aws_http_message *request = aws_http_message_new_request(user_data->allocator);
if (request == NULL) {
return AWS_OP_ERR;
}
if (headers && aws_http_message_add_header_array(request, headers, header_count)) {
goto on_error;
}
struct aws_http_header host_header = {
.name = aws_byte_cursor_from_string(s_imds_host_header),
.value = aws_byte_cursor_from_string(s_imds_host),
};
if (aws_http_message_add_header(request, host_header)) {
goto on_error;
}
struct aws_http_header accept_header = {
.name = aws_byte_cursor_from_string(s_imds_accept_header),
.value = aws_byte_cursor_from_string(s_imds_accept_header_value),
};
if (aws_http_message_add_header(request, accept_header)) {
goto on_error;
}
struct aws_http_header user_agent_header = {
.name = aws_byte_cursor_from_string(s_imds_user_agent_header),
.value = aws_byte_cursor_from_string(s_imds_user_agent_header_value),
};
if (aws_http_message_add_header(request, user_agent_header)) {
goto on_error;
}
struct aws_http_header keep_alive_header = {
.name = aws_byte_cursor_from_string(s_imds_h1_0_keep_alive_header),
.value = aws_byte_cursor_from_string(s_imds_h1_0_keep_alive_header_value),
};
if (aws_http_message_add_header(request, keep_alive_header)) {
goto on_error;
}
if (aws_http_message_set_request_method(request, *verb)) {
goto on_error;
}
if (aws_http_message_set_request_path(request, *uri)) {
goto on_error;
}
user_data->request = request;
struct aws_http_make_request_options request_options = {
.self_size = sizeof(request_options),
.on_response_headers = s_on_incoming_headers_fn,
.on_response_header_block_done = NULL,
.on_response_body = s_on_incoming_body_fn,
.on_complete = s_on_stream_complete_fn,
.response_first_byte_timeout_ms = 1000,
.user_data = user_data,
.request = request,
};
/* for test with mocking http stack where make request finishes
immediately and releases client before stream activate call */
s_user_data_acquire(user_data);
stream = client->function_table->aws_http_connection_make_request(user_data->connection, &request_options);
if (!stream || client->function_table->aws_http_stream_activate(stream)) {
goto on_error;
}
s_user_data_release(user_data);
return AWS_OP_SUCCESS;
on_error:
user_data->client->function_table->aws_http_stream_release(stream);
aws_http_message_destroy(request);
user_data->request = NULL;
s_user_data_release(user_data);
return AWS_OP_ERR;
}
/*
* Process the http response from the token put request.
*/
static void s_client_on_token_response(struct imds_user_data *user_data) {
/* Gets 400 means token is required but the request itself failed. */
if (user_data->status_code == AWS_HTTP_STATUS_CODE_400_BAD_REQUEST) {
s_update_token_safely(user_data->client, NULL, true, 0 /*expire_timestamp*/);
return;
}
if (user_data->status_code == AWS_HTTP_STATUS_CODE_200_OK && user_data->current_result.len != 0) {
AWS_LOGF_DEBUG(AWS_LS_IMDS_CLIENT, "(id=%p) IMDS client has fetched the token", (void *)user_data->client);
struct aws_byte_cursor cursor = aws_byte_cursor_from_buf(&(user_data->current_result));
aws_byte_cursor_trim_pred(&cursor, aws_char_is_space);
aws_byte_buf_reset(&user_data->imds_token, true /*zero contents*/);
if (aws_byte_buf_append_and_update(&user_data->imds_token, &cursor)) {
s_update_token_safely(user_data->client, NULL /*token*/, true /*token_required*/, 0 /*expire_timestamp*/);
return;
}
/* The token was ALWAYS last for 6 hours, 21600 secs. Use current timestamp plus 21595 secs as the expiration
* timestamp for current token */
uint64_t current = 0;
user_data->client->function_table->aws_high_res_clock_get_ticks(¤t);
uint64_t expire_timestamp = aws_add_u64_saturating(
current, aws_timestamp_convert(s_imds_token_ttl_secs, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL));
AWS_ASSERT(cursor.len != 0);
s_update_token_safely(user_data->client, &user_data->imds_token, true /*token_required*/, expire_timestamp);
} else if (user_data->ec2_metadata_v1_disabled) {
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to fetch token for requester %p, and fall back to v1 is disabled."
"Received response status code: %d",
(void *)user_data->client,
(void *)user_data,
user_data->status_code);
s_update_token_safely(user_data->client, NULL /*token*/, true /*token_required*/, 0 /*expire_timestamp*/);
} else {
/* Request failed; falling back to insecure request.
* TODO: The retryable error (503 throttle) will also fall back to v1. Instead, we should just resend the token
* request.
*/
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to fetch token for requester %p, fall back to v1 for the same "
"requester. Received response status code: %d",
(void *)user_data->client,
(void *)user_data,
user_data->status_code);
s_update_token_safely(user_data->client, NULL /*token*/, false /* token_required*/, 0 /*expire_timestamp*/);
}
}
static int s_client_start_query_token(struct aws_imds_client *client) {
struct imds_user_data *user_data = s_user_data_new(client, aws_byte_cursor_from_c_str(""), NULL, (void *)client);
if (!user_data) {
AWS_LOGF_ERROR(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to query token with error: %s.",
(void *)client,
aws_error_str(aws_last_error()));
return AWS_OP_ERR;
}
user_data->is_imds_token_request = true;
if (aws_retry_strategy_acquire_retry_token(
client->retry_strategy, NULL, s_on_retry_token_acquired, user_data, 100)) {
s_user_data_release(user_data);
return AWS_OP_ERR;
}
return AWS_OP_SUCCESS;
}
/* Make an http request to put a ttl and hopefully get a token back. */
static void s_client_do_query_token(struct imds_user_data *user_data) {
/* start query token for imds client */
struct aws_byte_cursor uri = aws_byte_cursor_from_string(s_imds_token_resource_path);
/* Hard-coded 6 hour TTL for the token. */
struct aws_http_header token_ttl_header = {
.name = aws_byte_cursor_from_string(s_imds_token_ttl_header),
.value = aws_byte_cursor_from_string(s_imds_token_ttl_default_value),
};
struct aws_http_header headers[] = {
token_ttl_header,
};
struct aws_byte_cursor verb = aws_byte_cursor_from_c_str("PUT");
if (s_make_imds_http_query(user_data, &verb, &uri, headers, AWS_ARRAY_SIZE(headers))) {
user_data->error_code = aws_last_error();
if (user_data->error_code == AWS_ERROR_SUCCESS) {
user_data->error_code = AWS_ERROR_UNKNOWN;
}
s_query_complete(user_data);
}
}
/*
* Make the http request to fetch the resource
*/
static void s_do_query_resource(struct imds_user_data *user_data) {
struct aws_http_header token_header = {
.name = aws_byte_cursor_from_string(s_imds_token_header),
.value = aws_byte_cursor_from_buf(&user_data->imds_token),
};
struct aws_http_header headers[] = {
token_header,
};
size_t headers_count = 0;
struct aws_http_header *headers_array_ptr = NULL;
if (user_data->imds_token_required) {
headers_count = 1;
headers_array_ptr = headers;
}
struct aws_byte_cursor verb = aws_byte_cursor_from_c_str("GET");
struct aws_byte_cursor path_cursor = aws_byte_cursor_from_string(user_data->resource_path);
if (s_make_imds_http_query(user_data, &verb, &path_cursor, headers_array_ptr, headers_count)) {
user_data->error_code = aws_last_error();
if (user_data->error_code == AWS_ERROR_SUCCESS) {
user_data->error_code = AWS_ERROR_UNKNOWN;
}
s_query_complete(user_data);
}
}
int s_get_resource_async_with_imds_token(struct imds_user_data *user_data);
static void s_query_complete(struct imds_user_data *user_data) {
if (user_data->is_imds_token_request) {
s_client_on_token_response(user_data);
s_user_data_release(user_data);
return;
}
if (user_data->status_code == AWS_HTTP_STATUS_CODE_401_UNAUTHORIZED) {
struct aws_imds_client *client = user_data->client;
aws_mutex_lock(&client->token_lock);
if (aws_byte_buf_eq(&user_data->imds_token, &client->cached_token)) {
/* If the token used matches the cached token, that means the cached token is invalid. */
client->token_state = AWS_IMDS_TS_INVALID;
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client's cached token is invalidated by requester %p.",
(void *)client,
(void *)user_data);
}
/* let following requests use token as it's required. */
client->token_required = true;
aws_mutex_unlock(&client->token_lock);
if (!user_data->imds_token_required && !user_data->is_fallback_request) {
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to fetch resource via V1, try to use V2. requester %p.",
(void *)user_data->client,
(void *)user_data);
/* V1 request, fallback to V2 and try again. */
s_reset_scratch_user_data(user_data);
user_data->is_fallback_request = true;
aws_retry_token_release(user_data->retry_token);
/* Try V2 now. */
if (s_get_resource_async_with_imds_token(user_data)) {
s_user_data_release(user_data);
}
return;
} else {
/* Not retirable error. */
AWS_LOGF_ERROR(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to fetch resource. Server response 401 UNAUTHORIZED. requester %p.",
(void *)user_data->client,
(void *)user_data);
user_data->error_code = AWS_AUTH_IMDS_CLIENT_SOURCE_FAILURE;
}
}
/* TODO: if server sent out error, we will still report as succeed with the error body received from server. */
/* TODO: retry for 503 throttle. */
user_data->original_callback(
user_data->error_code ? NULL : &user_data->current_result,
user_data->error_code,
user_data->original_user_data);
s_user_data_release(user_data);
}
static void s_on_acquire_connection(struct aws_http_connection *connection, int error_code, void *user_data) {
struct imds_user_data *imds_user_data = user_data;
imds_user_data->connection = connection;
if (!connection) {
AWS_LOGF_WARN(
AWS_LS_IMDS_CLIENT,
"id=%p: IMDS Client failed to acquire a connection, error code %d(%s)",
(void *)imds_user_data->client,
error_code,
aws_error_str(error_code));
imds_user_data->error_code = error_code;
s_query_complete(imds_user_data);
return;
}
if (imds_user_data->is_imds_token_request) {
s_client_do_query_token(imds_user_data);
} else {
s_do_query_resource(imds_user_data);
}
}
static void s_on_retry_ready(struct aws_retry_token *token, int error_code, void *user_data) {
(void)token;
struct imds_user_data *imds_user_data = user_data;
struct aws_imds_client *client = imds_user_data->client;
if (!error_code) {
client->function_table->aws_http_connection_manager_acquire_connection(
client->connection_manager, s_on_acquire_connection, user_data);
} else {
AWS_LOGF_WARN(
AWS_LS_IMDS_CLIENT,
"id=%p: IMDS Client failed to retry the request with error code %d(%s)",
(void *)client,
error_code,
aws_error_str(error_code));
imds_user_data->error_code = error_code;
s_query_complete(imds_user_data);
}
}
static void s_on_stream_complete_fn(struct aws_http_stream *stream, int error_code, void *user_data) {
struct imds_user_data *imds_user_data = user_data;
struct aws_imds_client *client = imds_user_data->client;
aws_http_message_destroy(imds_user_data->request);
imds_user_data->request = NULL;
imds_user_data->connection = NULL;
struct aws_http_connection *connection = client->function_table->aws_http_stream_get_connection(stream);
client->function_table->aws_http_stream_release(stream);
client->function_table->aws_http_connection_manager_release_connection(client->connection_manager, connection);
/* on encountering error, see if we could try again */
/* TODO: check the status code as well? */
if (error_code) {
AWS_LOGF_WARN(
AWS_LS_IMDS_CLIENT,
"id=%p: Stream completed with error code %d(%s)",
(void *)client,
error_code,
aws_error_str(error_code));
if (!aws_retry_strategy_schedule_retry(
imds_user_data->retry_token, AWS_RETRY_ERROR_TYPE_TRANSIENT, s_on_retry_ready, user_data)) {
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"id=%p: Stream completed, retrying the last request on a new connection.",
(void *)client);
return;
} else {
AWS_LOGF_ERROR(AWS_LS_IMDS_CLIENT, "id=%p: Stream completed, retries have been exhausted.", (void *)client);
imds_user_data->error_code = error_code;
}
} else if (aws_retry_token_record_success(imds_user_data->retry_token)) {
AWS_LOGF_ERROR(
AWS_LS_IMDS_CLIENT,
"id=%p: Error while recording successful retry: %s",
(void *)client,
aws_error_str(aws_last_error()));
}
s_query_complete(imds_user_data);
}
static void s_on_retry_token_acquired(
struct aws_retry_strategy *strategy,
int error_code,
struct aws_retry_token *token,
void *user_data) {
(void)strategy;
struct imds_user_data *imds_user_data = user_data;
struct aws_imds_client *client = imds_user_data->client;
if (!error_code) {
AWS_LOGF_DEBUG(AWS_LS_IMDS_CLIENT, "id=%p: IMDS Client successfully acquired retry token.", (void *)client);
imds_user_data->retry_token = token;
client->function_table->aws_http_connection_manager_acquire_connection(
client->connection_manager, s_on_acquire_connection, imds_user_data);
} else {
AWS_LOGF_WARN(
AWS_LS_IMDS_CLIENT,
"id=%p: IMDS Client failed to acquire retry token, error code %d(%s)",
(void *)client,
error_code,
aws_error_str(error_code));
imds_user_data->error_code = error_code;
s_query_complete(imds_user_data);
}
}
static void s_complete_pending_queries(
struct aws_imds_client *client,
struct aws_linked_list *queries,
bool token_required,
struct aws_byte_buf *token) {
/* poll swapped out pending queries if there is any */
while (!aws_linked_list_empty(queries)) {
struct aws_linked_list_node *node = aws_linked_list_pop_back(queries);
struct imds_token_query *query = AWS_CONTAINER_OF(node, struct imds_token_query, node);
struct imds_user_data *requester = query->user_data;
aws_mem_release(client->allocator, query);
bool should_continue = true;
if (requester->imds_token_required && !token_required) {
if (requester->is_fallback_request) {
AWS_LOGF_ERROR(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to fetch resource without token, and also failed to fetch token. "
"requester %p.",
(void *)requester->client,
(void *)requester);
requester->error_code = AWS_AUTH_IMDS_CLIENT_SOURCE_FAILURE;
should_continue = false;
} else {
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to fetch token, fallback to v1. requester %p.",
(void *)requester->client,
(void *)requester);
requester->is_fallback_request = true;
}
}
requester->imds_token_required = token_required;
if (token) {
aws_byte_buf_reset(&requester->imds_token, true);
struct aws_byte_cursor cursor = aws_byte_cursor_from_buf(token);
if (aws_byte_buf_append_dynamic(&requester->imds_token, &cursor)) {
AWS_LOGF_ERROR(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to copy IMDS token for requester %p.",
(void *)client,
(void *)requester);
should_continue = false;
}
} else if (token_required) {
requester->error_code = AWS_AUTH_IMDS_CLIENT_SOURCE_FAILURE;
should_continue = false;
}
if (should_continue && aws_retry_strategy_acquire_retry_token(
client->retry_strategy, NULL, s_on_retry_token_acquired, requester, 100)) {
AWS_LOGF_ERROR(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client failed to allocate retry token for requester %p to send resource request.",
(void *)client,
(void *)requester);
should_continue = false;
}
if (!should_continue) {
if (requester->error_code == AWS_ERROR_SUCCESS) {
requester->error_code = aws_last_error() == AWS_ERROR_SUCCESS ? AWS_ERROR_UNKNOWN : aws_last_error();
}
s_query_complete(requester);
}
}
}
static enum imds_token_copy_result s_copy_token_safely(struct imds_user_data *user_data) {
struct aws_imds_client *client = user_data->client;
enum imds_token_copy_result ret = AWS_IMDS_TCR_UNEXPECTED_ERROR;
struct aws_linked_list pending_queries;
aws_linked_list_init(&pending_queries);
uint64_t current = 0;
user_data->client->function_table->aws_high_res_clock_get_ticks(¤t);
aws_mutex_lock(&client->token_lock);
if (client->token_state == AWS_IMDS_TS_VALID) {
if (current > client->cached_token_expiration_timestamp) {
/* The cached token expired. Switch the state */
client->token_state = AWS_IMDS_TS_INVALID;
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client's cached token expired. Fetching new token for requester %p.",
(void *)client,
(void *)user_data);
} else {
aws_byte_buf_reset(&user_data->imds_token, true);
struct aws_byte_cursor cursor = aws_byte_cursor_from_buf(&client->cached_token);
if (aws_byte_buf_append_dynamic(&user_data->imds_token, &cursor)) {
ret = AWS_IMDS_TCR_UNEXPECTED_ERROR;
} else {
ret = AWS_IMDS_TCR_SUCCESS;
}
}
}
if (client->token_state != AWS_IMDS_TS_VALID) {
ret = AWS_IMDS_TCR_WAITING_IN_QUEUE;
struct imds_token_query *query = aws_mem_calloc(client->allocator, 1, sizeof(struct imds_token_query));
query->user_data = user_data;
aws_linked_list_push_back(&client->pending_queries, &query->node);
if (client->token_state == AWS_IMDS_TS_INVALID) {
if (s_client_start_query_token(client)) {
ret = AWS_IMDS_TCR_UNEXPECTED_ERROR;
aws_linked_list_swap_contents(&pending_queries, &client->pending_queries);
} else {
client->token_state = AWS_IMDS_TS_UPDATE_IN_PROGRESS;
}
}
}
aws_mutex_unlock(&client->token_lock);
s_complete_pending_queries(client, &pending_queries, true, NULL);
switch (ret) {
case AWS_IMDS_TCR_SUCCESS:
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client copied token to requester %p successfully.",
(void *)client,
(void *)user_data);
break;
case AWS_IMDS_TCR_WAITING_IN_QUEUE:
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT, "(id=%p) IMDS client's token is invalid and is now updating.", (void *)client);
break;
case AWS_IMDS_TCR_UNEXPECTED_ERROR:
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT,
"(id=%p) IMDS client encountered unexpected error when processing token query for requester %p, error: "
"%s.",
(void *)client,
(void *)user_data,
aws_error_str(aws_last_error()));
break;
}
return ret;
}
/**
* Once a requseter returns from token request, it should call this function to unblock all other
* waiting requesters. When the token parameter is NULL, means the token request failed. Now we need
* a new requester to acquire the token again.
*/
static void s_update_token_safely(
struct aws_imds_client *client,
struct aws_byte_buf *token,
bool token_required,
uint64_t expire_timestamp) {
AWS_FATAL_ASSERT(client);
bool updated = false;
struct aws_linked_list pending_queries;
aws_linked_list_init(&pending_queries);
aws_mutex_lock(&client->token_lock);
client->token_required = token_required;
if (token) {
aws_byte_buf_reset(&client->cached_token, true);
struct aws_byte_cursor cursor = aws_byte_cursor_from_buf(token);
if (aws_byte_buf_append_dynamic(&client->cached_token, &cursor) == AWS_OP_SUCCESS) {
client->token_state = AWS_IMDS_TS_VALID;
client->cached_token_expiration_timestamp = expire_timestamp;
updated = true;
}
} else {
client->token_state = AWS_IMDS_TS_INVALID;
}
aws_linked_list_swap_contents(&pending_queries, &client->pending_queries);
aws_mutex_unlock(&client->token_lock);
s_complete_pending_queries(client, &pending_queries, token_required, token);
if (updated) {
AWS_LOGF_DEBUG(
AWS_LS_IMDS_CLIENT, "(id=%p) IMDS client updated the cached token successfully.", (void *)client);
} else {
AWS_LOGF_ERROR(AWS_LS_IMDS_CLIENT, "(id=%p) IMDS client failed to update the token from IMDS.", (void *)client);
}
}
int s_get_resource_async_with_imds_token(struct imds_user_data *user_data) {
enum imds_token_copy_result res = s_copy_token_safely(user_data);
if (res == AWS_IMDS_TCR_UNEXPECTED_ERROR) {