summaryrefslogtreecommitdiffstats
path: root/fluent-bit/src/aws/flb_aws_credentials_sts.c
blob: d992485cc00dc8ad675235698726fd135c236a1e (plain)
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
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2022 The Fluent Bit Authors
 *
 *  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.
 */

#include <fluent-bit/flb_info.h>
#include <fluent-bit/flb_sds.h>
#include <fluent-bit/flb_http_client.h>
#include <fluent-bit/flb_aws_credentials.h>
#include <fluent-bit/flb_aws_util.h>
#include <fluent-bit/flb_random.h>
#include <fluent-bit/flb_jsmn.h>

#include <stdlib.h>
#include <time.h>
#include <string.h>

#define STS_ASSUME_ROLE_URI_FORMAT    "/?Version=2011-06-15&Action=%s\
&RoleSessionName=%s&RoleArn=%s"
#define STS_ASSUME_ROLE_URI_BASE_LEN  54

/*
 * The STS APIs return an XML document with credentials.
 * The part of the document we care about looks like this:
 * <Credentials>
 *    <AccessKeyId>akid</AccessKeyId>
 *    <SecretAccessKey>skid</SecretAccessKey>
 *    <SessionToken>token</SessionToken>
 *    <Expiration>2019-11-09T13:34:41Z</Expiration>
 * </Credentials>
 */
#define CREDENTIALS_NODE              "<Credentials>"
#define CREDENTIALS_NODE_LEN          13
#define ACCESS_KEY_NODE               "<AccessKeyId>"
#define ACCESS_KEY_NODE_LEN           13
#define ACCESS_KEY_NODE_END           "</AccessKeyId>"
#define SECRET_KEY_NODE               "<SecretAccessKey>"
#define SECRET_KEY_NODE_LEN           17
#define SECRET_KEY_NODE_END           "</SecretAccessKey>"
#define SESSION_TOKEN_NODE            "<SessionToken>"
#define SESSION_TOKEN_NODE_LEN        14
#define SESSION_TOKEN_NODE_END        "</SessionToken>"
#define EXPIRATION_NODE               "<Expiration>"
#define EXPIRATION_NODE_LEN           12
#define EXPIRATION_NODE_END           "</Expiration>"

#define TOKEN_FILE_ENV_VAR            "AWS_WEB_IDENTITY_TOKEN_FILE"
#define ROLE_ARN_ENV_VAR              "AWS_ROLE_ARN"
#define SESSION_NAME_ENV_VAR          "AWS_ROLE_SESSION_NAME"

#define SESSION_NAME_RANDOM_BYTE_LEN  32

struct flb_aws_provider_eks;
void bytes_to_string(unsigned char *data, char *buf, size_t len);
static int assume_with_web_identity(struct flb_aws_provider_eks
                                    *implementation);
static int sts_assume_role_request(struct flb_aws_client *sts_client,
                                   struct flb_aws_credentials **creds,
                                   char *uri,
                                   time_t *next_refresh);
static flb_sds_t get_node(char *cred_node, char* node_name, int node_name_len, char* node_end);


/*
 * A provider that uses credentials from the base provider to call STS
 * and assume an IAM Role.
 */
struct flb_aws_provider_sts {
    int custom_endpoint;
    struct flb_aws_provider *base_provider;

    struct flb_aws_credentials *creds;
    time_t next_refresh;

    struct flb_aws_client *sts_client;

    /* Fluent Bit uses regional STS endpoints; this is a best practice. */
    char *endpoint;

    flb_sds_t uri;
};

struct flb_aws_credentials *get_credentials_fn_sts(struct flb_aws_provider
                                                   *provider)
{
    struct flb_aws_credentials *creds;
    int refresh = FLB_FALSE;
    struct flb_aws_provider_sts *implementation = provider->implementation;

    flb_debug("[aws_credentials] Requesting credentials from the "
              "STS provider..");

    /* a negative next_refresh means that auto-refresh is disabled */
    if (implementation->next_refresh > 0
        && time(NULL) > implementation->next_refresh) {
        refresh = FLB_TRUE;
    }
    if (!implementation->creds || refresh == FLB_TRUE) {
        /* credentials need to be refreshed/obtained */
        if (try_lock_provider(provider)) {
            flb_debug("[aws_credentials] STS Provider: Refreshing credential "
                      "cache.");
            sts_assume_role_request(implementation->sts_client,
                                    &implementation->creds,
                                    implementation->uri,
                                    &implementation->next_refresh);
            unlock_provider(provider);
        }
    }

    if (!implementation->creds) {
        /*
         * We failed to lock the provider and creds are unset. This means that
         * another co-routine is performing the refresh.
         */
        flb_warn("[aws_credentials] No cached credentials are available and "
                 "a credential refresh is already in progress. The current "
                 "co-routine will retry.");

        return NULL;
    }

    /* return a copy of the existing cached credentials */
    creds = flb_calloc(1, sizeof(struct flb_aws_credentials));
    if (!creds) {
        goto error;
    }

    creds->access_key_id = flb_sds_create(implementation->creds->access_key_id);
    if (!creds->access_key_id) {
        goto error;
    }

    creds->secret_access_key = flb_sds_create(implementation->creds->
                                              secret_access_key);
    if (!creds->secret_access_key) {
        goto error;
    }

    if (implementation->creds->session_token) {
        creds->session_token = flb_sds_create(implementation->creds->
                                              session_token);
        if (!creds->session_token) {
            goto error;
        }

    } else {
        creds->session_token = NULL;
    }

    return creds;

error:
    flb_errno();
    flb_aws_credentials_destroy(creds);
    return NULL;
}

int refresh_fn_sts(struct flb_aws_provider *provider) {
    int ret = -1;
    struct flb_aws_provider_sts *implementation = provider->implementation;

    flb_debug("[aws_credentials] Refresh called on the STS provider");

    if (try_lock_provider(provider)) {
        ret = sts_assume_role_request(implementation->sts_client,
                                      &implementation->creds, implementation->uri,
                                      &implementation->next_refresh);
        unlock_provider(provider);
    }
    return ret;
}

int init_fn_sts(struct flb_aws_provider *provider) {
    int ret = -1;
    struct flb_aws_provider_sts *implementation = provider->implementation;

    flb_debug("[aws_credentials] Init called on the STS provider");

    /* Call Init on the base provider first */
    implementation->base_provider->provider_vtable->
                                   init(implementation->base_provider);

    implementation->sts_client->debug_only = FLB_TRUE;

    if (try_lock_provider(provider)) {
        ret = sts_assume_role_request(implementation->sts_client,
                                      &implementation->creds, implementation->uri,
                                      &implementation->next_refresh);
        unlock_provider(provider);
    }

    implementation->sts_client->debug_only = FLB_FALSE;
    return ret;
}

void sync_fn_sts(struct flb_aws_provider *provider) {
    struct flb_aws_provider_sts *implementation = provider->implementation;
    struct flb_aws_provider *base_provider = implementation->base_provider;

    flb_debug("[aws_credentials] Sync called on the STS provider");
    /* Remove async flag */
    flb_stream_disable_async_mode(&implementation->sts_client->upstream->base);

    /* we also need to call sync on the base_provider */
    base_provider->provider_vtable->sync(base_provider);
}

void async_fn_sts(struct flb_aws_provider *provider) {
    struct flb_aws_provider_sts *implementation = provider->implementation;
    struct flb_aws_provider *base_provider = implementation->base_provider;

    flb_debug("[aws_credentials] Async called on the STS provider");
    /* Add async flag */
    flb_stream_enable_async_mode(&implementation->sts_client->upstream->base);

    /* we also need to call async on the base_provider */
    base_provider->provider_vtable->async(base_provider);
}

void upstream_set_fn_sts(struct flb_aws_provider *provider,
                        struct flb_output_instance *ins) {
    struct flb_aws_provider_sts *implementation = provider->implementation;
    struct flb_aws_provider *base_provider = implementation->base_provider;

    flb_debug("[aws_credentials] upstream_set called on the STS provider");
    /* associate output and upstream */
    flb_output_upstream_set(implementation->sts_client->upstream, ins);

    /* we also need to call upstream_set on the base_provider */
    base_provider->provider_vtable->upstream_set(base_provider, ins);
}

void destroy_fn_sts(struct flb_aws_provider *provider) {
    struct flb_aws_provider_sts *implementation;

    implementation = provider->implementation;

    if (implementation) {
        if (implementation->creds) {
            flb_aws_credentials_destroy(implementation->creds);
        }

        if (implementation->sts_client) {
            flb_aws_client_destroy(implementation->sts_client);
        }

        if (implementation->uri) {
            flb_sds_destroy(implementation->uri);
        }

        if (implementation->custom_endpoint == FLB_FALSE) {
            flb_free(implementation->endpoint);
        }

        flb_free(implementation);
        provider->implementation = NULL;
    }

    return;
}

static struct flb_aws_provider_vtable sts_provider_vtable = {
    .get_credentials = get_credentials_fn_sts,
    .init = init_fn_sts,
    .refresh = refresh_fn_sts,
    .destroy = destroy_fn_sts,
    .sync = sync_fn_sts,
    .async = async_fn_sts,
    .upstream_set = upstream_set_fn_sts,
};

struct flb_aws_provider *flb_sts_provider_create(struct flb_config *config,
                                                 struct flb_tls *tls,
                                                 struct flb_aws_provider
                                                 *base_provider,
                                                 char *external_id,
                                                 char *role_arn,
                                                 char *session_name,
                                                 char *region,
                                                 char *sts_endpoint,
                                                 char *proxy,
                                                 struct
                                                 flb_aws_client_generator
                                                 *generator)
{
    struct flb_aws_provider_sts *implementation = NULL;
    struct flb_aws_provider *provider = NULL;
    struct flb_upstream *upstream = NULL;

    provider = flb_calloc(1, sizeof(struct flb_aws_provider));
    if (!provider) {
        flb_errno();
        return NULL;
    }

    pthread_mutex_init(&provider->lock, NULL);

    implementation = flb_calloc(1, sizeof(struct flb_aws_provider_sts));
    if (!implementation) {
        goto error;
    }

    provider->provider_vtable = &sts_provider_vtable;
    provider->implementation = implementation;

    implementation->uri = flb_sts_uri("AssumeRole", role_arn, session_name,
                                      external_id, NULL);
    if (!implementation->uri) {
        goto error;
    }

    if (sts_endpoint) {
        implementation->endpoint = removeProtocol(sts_endpoint, "https://");
        implementation->custom_endpoint = FLB_TRUE;
    }
    else {
        implementation->endpoint = flb_aws_endpoint("sts", region);
        implementation->custom_endpoint = FLB_FALSE;
    }

    if(!implementation->endpoint) {
        goto error;
    }

    implementation->base_provider = base_provider;
    implementation->sts_client = generator->create();
    if (!implementation->sts_client) {
        goto error;
    }
    implementation->sts_client->name = "sts_client_assume_role_provider";
    implementation->sts_client->has_auth = FLB_TRUE;
    implementation->sts_client->provider = base_provider;
    implementation->sts_client->region = region;
    implementation->sts_client->service = "sts";
    implementation->sts_client->port = 443;
    implementation->sts_client->flags = 0;
    implementation->sts_client->proxy = proxy;

    upstream = flb_upstream_create(config, implementation->endpoint, 443,
                                   FLB_IO_TLS, tls);
    if (!upstream) {
        flb_error("[aws_credentials] Connection initialization error");
        goto error;
    }

    upstream->base.net.connect_timeout = FLB_AWS_CREDENTIAL_NET_TIMEOUT;

    implementation->sts_client->upstream = upstream;
    implementation->sts_client->host = implementation->endpoint;

    return provider;

error:
    flb_errno();
    flb_aws_provider_destroy(provider);
    return NULL;
}

/*
 * A provider that uses OIDC tokens provided by kubernetes to obtain
 * AWS credentials.
 *
 * The AWS SDKs have defined a spec for an OIDC provider that obtains tokens
 * from environment variables or the shared config file.
 * This provider only contains the functionality needed for EKS- obtaining the
 * location of the OIDC token from an environment variable.
 */
struct flb_aws_provider_eks {
    int custom_endpoint;
    struct flb_aws_credentials *creds;
    /*
     * Time to auto-refresh creds before they expire. A negative value disables
     * auto-refresh. Client code can always force a refresh.
     */
    time_t next_refresh;

    struct flb_aws_client *sts_client;

    /* Fluent Bit uses regional STS endpoints; this is a best practice. */
    char *endpoint;

    char *session_name;
    /* session name can come from env or be generated by the provider */
    int free_session_name;
    char *role_arn;

    char *token_file;
};


struct flb_aws_credentials *get_credentials_fn_eks(struct flb_aws_provider
                                                   *provider)
{
    struct flb_aws_credentials *creds = NULL;
    int refresh = FLB_FALSE;
    struct flb_aws_provider_eks *implementation = provider->implementation;

    flb_debug("[aws_credentials] Requesting credentials from the "
              "EKS provider..");

    /* a negative next_refresh means that auto-refresh is disabled */
    if (implementation->next_refresh > 0
        && time(NULL) > implementation->next_refresh) {
        refresh = FLB_TRUE;
    }
    if (!implementation->creds || refresh == FLB_TRUE) {
        if (try_lock_provider(provider)) {
            flb_debug("[aws_credentials] EKS Provider: Refreshing credential "
                      "cache.");
            assume_with_web_identity(implementation);
            unlock_provider(provider);
        }
    }

    if (!implementation->creds) {
        /*
         * We failed to lock the provider and creds are unset. This means that
         * another co-routine is performing the refresh.
         */
        flb_warn("[aws_credentials] No cached credentials are available and "
                 "a credential refresh is already in progress. The current "
                 "co-routine will retry.");

        return NULL;
    }

    creds = flb_calloc(1, sizeof(struct flb_aws_credentials));
    if (!creds) {
        goto error;
    }

    creds->access_key_id = flb_sds_create(implementation->creds->access_key_id);
    if (!creds->access_key_id) {
        goto error;
    }

    creds->secret_access_key = flb_sds_create(implementation->creds->
                                              secret_access_key);
    if (!creds->secret_access_key) {
        goto error;
    }

    if (implementation->creds->session_token) {
        creds->session_token = flb_sds_create(implementation->creds->
                                              session_token);
        if (!creds->session_token) {
            goto error;
        }

    }
    else {
        creds->session_token = NULL;
    }

    return creds;

error:
    flb_errno();
    flb_aws_credentials_destroy(creds);
    return NULL;
}

int refresh_fn_eks(struct flb_aws_provider *provider) {
    int ret = -1;
    struct flb_aws_provider_eks *implementation = provider->implementation;

    flb_debug("[aws_credentials] Refresh called on the EKS provider");
    if (try_lock_provider(provider)) {
        ret = assume_with_web_identity(implementation);
        unlock_provider(provider);
    }
    return ret;
}

int init_fn_eks(struct flb_aws_provider *provider) {
    int ret = -1;
    struct flb_aws_provider_eks *implementation = provider->implementation;

    implementation->sts_client->debug_only = FLB_TRUE;

    flb_debug("[aws_credentials] Init called on the EKS provider");
    if (try_lock_provider(provider)) {
        ret = assume_with_web_identity(implementation);
        unlock_provider(provider);
    }

    implementation->sts_client->debug_only = FLB_FALSE;
    return ret;
}

void sync_fn_eks(struct flb_aws_provider *provider) {
    struct flb_aws_provider_eks *implementation = provider->implementation;
    flb_debug("[aws_credentials] Sync called on the EKS provider");
    /* remove async flag */
    flb_stream_disable_async_mode(&implementation->sts_client->upstream->base);
}

void async_fn_eks(struct flb_aws_provider *provider) {
    struct flb_aws_provider_eks *implementation = provider->implementation;
    flb_debug("[aws_credentials] Async called on the EKS provider");
    /* add async flag */
    flb_stream_enable_async_mode(&implementation->sts_client->upstream->base);
}

void upstream_set_fn_eks(struct flb_aws_provider *provider,
                         struct flb_output_instance *ins) {
    struct flb_aws_provider_eks *implementation = provider->implementation;
    flb_debug("[aws_credentials] upstream_set called on the EKS provider");
    /* set upstream on output */
    flb_output_upstream_set(implementation->sts_client->upstream, ins);
}

void destroy_fn_eks(struct flb_aws_provider *provider) {
    struct flb_aws_provider_eks *implementation = provider->
                                                          implementation;
    if (implementation) {
        if (implementation->creds) {
            flb_aws_credentials_destroy(implementation->creds);
        }

        if (implementation->sts_client) {
            flb_aws_client_destroy(implementation->sts_client);
        }

        if (implementation->custom_endpoint == FLB_FALSE) {
            flb_free(implementation->endpoint);
        }
        if (implementation->free_session_name == FLB_TRUE) {
            flb_free(implementation->session_name);
        }

        flb_free(implementation);
        provider->implementation = NULL;
    }

    return;
}

static struct flb_aws_provider_vtable eks_provider_vtable = {
    .get_credentials = get_credentials_fn_eks,
    .init = init_fn_eks,
    .refresh = refresh_fn_eks,
    .destroy = destroy_fn_eks,
    .sync = sync_fn_eks,
    .async = async_fn_eks,
    .upstream_set = upstream_set_fn_eks,
};

struct flb_aws_provider *flb_eks_provider_create(struct flb_config *config,
                                                 struct flb_tls *tls,
                                                 char *region,
                                                 char *sts_endpoint,
                                                 char *proxy,
                                                 struct
                                                 flb_aws_client_generator
                                                 *generator)
{
    struct flb_aws_provider_eks *implementation = NULL;
    struct flb_aws_provider *provider = NULL;
    struct flb_upstream *upstream = NULL;

    provider = flb_calloc(1, sizeof(struct flb_aws_provider));

    if (!provider) {
        flb_errno();
        return NULL;
    }
    
    pthread_mutex_init(&provider->lock, NULL);
    
    implementation = flb_calloc(1, sizeof(struct flb_aws_provider_eks));

    if (!implementation) {
        goto error;
    }

    provider->provider_vtable = &eks_provider_vtable;
    provider->implementation = implementation;

    /* session name either comes from the env var or is a random uuid */
    implementation->session_name = getenv(SESSION_NAME_ENV_VAR);
    implementation->free_session_name = FLB_FALSE;
    if (!implementation->session_name ||
        strlen(implementation->session_name) == 0) {
        implementation->session_name = flb_sts_session_name();
        if (!implementation->session_name) {
            goto error;
        }
        implementation->free_session_name = FLB_TRUE;
    }

    implementation->role_arn = getenv(ROLE_ARN_ENV_VAR);
    if (!implementation->role_arn || strlen(implementation->role_arn) == 0) {
        flb_debug("[aws_credentials] Not initializing EKS provider because"
                  " %s was not set", ROLE_ARN_ENV_VAR);
        flb_aws_provider_destroy(provider);
        return NULL;
    }

    implementation->token_file = getenv(TOKEN_FILE_ENV_VAR);
    if (!implementation->token_file || strlen(implementation->token_file) == 0)
    {
        flb_debug("[aws_credentials] Not initializing EKS provider because"
                  " %s was not set", TOKEN_FILE_ENV_VAR);
        flb_aws_provider_destroy(provider);
        return NULL;
    }

    if (sts_endpoint) {
        implementation->endpoint = removeProtocol(sts_endpoint, "https://");
        implementation->custom_endpoint = FLB_TRUE;
    }
    else {
        implementation->endpoint = flb_aws_endpoint("sts", region);
        implementation->custom_endpoint = FLB_FALSE;
    }

    if(!implementation->endpoint) {
        goto error;
    }

    implementation->sts_client = generator->create();
    if (!implementation->sts_client) {
        goto error;
    }
    implementation->sts_client->name = "sts_client_eks_provider";
    /* AssumeRoleWithWebIdentity does not require sigv4 */
    implementation->sts_client->has_auth = FLB_FALSE;
    implementation->sts_client->provider = NULL;
    implementation->sts_client->region = region;
    implementation->sts_client->service = "sts";
    implementation->sts_client->port = 443;
    implementation->sts_client->flags = 0;
    implementation->sts_client->proxy = proxy;

    upstream = flb_upstream_create(config, implementation->endpoint, 443,
                                   FLB_IO_TLS, tls);

    if (!upstream) {
        goto error;
    }

    upstream->base.net.connect_timeout = FLB_AWS_CREDENTIAL_NET_TIMEOUT;

    implementation->sts_client->upstream = upstream;
    implementation->sts_client->host = implementation->endpoint;

    return provider;

error:
    flb_errno();
    flb_aws_provider_destroy(provider);
    return NULL;
}

/* Generates string which can serve as a unique session name */
char *flb_sts_session_name() {
    unsigned char random_data[SESSION_NAME_RANDOM_BYTE_LEN];
    char *session_name = NULL;
    int ret;

    ret = flb_random_bytes(random_data, SESSION_NAME_RANDOM_BYTE_LEN);

    if (ret != 0) {
        flb_errno();

        return NULL;
    }

    session_name = flb_calloc(SESSION_NAME_RANDOM_BYTE_LEN + 1,
                              sizeof(char));
    if (session_name == NULL) {
        flb_errno();

        return NULL;
    }

    bytes_to_string(random_data, session_name, SESSION_NAME_RANDOM_BYTE_LEN);

    return session_name;
}

/* converts random bytes to a string we can safely put in a URL */
void bytes_to_string(unsigned char *data, char *buf, size_t len) {
    int index;
    char charset[] = "0123456789"
                     "abcdefghijklmnopqrstuvwxyz"
                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    while (len-- > 0) {
        index = (int) data[len];
        index = index % (sizeof(charset) - 1);
        buf[len] = charset[index];
    }
}

static int assume_with_web_identity(struct flb_aws_provider_eks
                                    *implementation)
{
    int ret;
    char *web_token = NULL;
    size_t web_token_size;
    flb_sds_t uri = NULL;
    int init_mode = implementation->sts_client->debug_only;

    ret = flb_read_file(implementation->token_file, &web_token,
                        &web_token_size);
    if (ret < 0) {
        if (init_mode == FLB_TRUE) {
            flb_debug("[aws_credentials] Could not read web identify token file");
        } else {
            flb_error("[aws_credentials] Could not read web identify token file");
        }
        return -1;
    }

    uri = flb_sts_uri("AssumeRoleWithWebIdentity", implementation->role_arn,
                      implementation->session_name, NULL, web_token);
    if (!uri) {
        flb_free(web_token);
        return -1;
    }

    ret = sts_assume_role_request(implementation->sts_client,
                                  &implementation->creds, uri,
                                  &implementation->next_refresh);
    flb_free(web_token);
    flb_sds_destroy(uri);
    return ret;
}

static int sts_assume_role_request(struct flb_aws_client *sts_client,
                                   struct flb_aws_credentials **creds,
                                   char *uri,
                                   time_t *next_refresh)
{
    time_t expiration;
    struct flb_aws_credentials *credentials = NULL;
    struct flb_http_client *c = NULL;
    flb_sds_t error_type;
    int init_mode = sts_client->debug_only;

    flb_debug("[aws_credentials] Calling STS..");

    c = sts_client->client_vtable->request(sts_client, FLB_HTTP_GET,
                                           uri, NULL, 0, NULL, 0);

    if (c && c->resp.status == 200) {
        credentials = flb_parse_sts_resp(c->resp.payload, &expiration);
        if (!credentials) {
            if (init_mode == FLB_TRUE) {
                flb_debug("[aws_credentials] Failed to parse response from STS");
            }
            else {
                flb_error("[aws_credentials] Failed to parse response from STS");
            }
            flb_http_client_destroy(c);
            return -1;
        }

        /* unset and free existing credentials first */
        flb_aws_credentials_destroy(*creds);
        *creds = NULL;

        *next_refresh = expiration - FLB_AWS_REFRESH_WINDOW;
        *creds = credentials;
        flb_http_client_destroy(c);
        return 0;
    }

    if (c && c->resp.payload_size > 0) {
        error_type = flb_aws_error(c->resp.payload, c->resp.payload_size);
        if (error_type) {
            if (init_mode == FLB_TRUE) {
                flb_debug("[aws_credentials] STS API responded with %s", error_type);
            }
            else {
                flb_error("[aws_credentials] STS API responded with %s", error_type);
            }
        } else {
            flb_debug("[aws_credentials] STS raw response: \n%s",
                      c->resp.payload);
        }
    }

    if (c) {
        flb_http_client_destroy(c);
    }
    if (init_mode == FLB_TRUE) {
        flb_debug("[aws_credentials] STS assume role request failed");
    }
    else {
        flb_error("[aws_credentials] STS assume role request failed");
    }
    return -1;

}

/*
 * The STS APIs return an XML document with credentials.
 * The part of the document we care about looks like this:
 * <Credentials>
 *    <AccessKeyId>akid</AccessKeyId>
 *    <SecretAccessKey>skid</SecretAccessKey>
 *    <SessionToken>token</SessionToken>
 *    <Expiration>2019-11-09T13:34:41Z</Expiration>
 * </Credentials>
 */
struct flb_aws_credentials *flb_parse_sts_resp(char *response,
                                               time_t *expiration)
{
    struct flb_aws_credentials *creds = NULL;
    char *cred_node = NULL;
    flb_sds_t tmp = NULL;

    cred_node = strstr(response, CREDENTIALS_NODE);
    if (!cred_node) {
        flb_error("[aws_credentials] Could not find '%s' node in sts response",
                  CREDENTIALS_NODE);
        return NULL;
    }
    cred_node += CREDENTIALS_NODE_LEN;

    creds = flb_calloc(1, sizeof(struct flb_aws_credentials));
    if (!creds) {
        flb_errno();
        return NULL;
    }

    creds->access_key_id = get_node(cred_node, ACCESS_KEY_NODE,
                                    ACCESS_KEY_NODE_LEN, ACCESS_KEY_NODE_END);
    if (!creds->access_key_id) {
        goto error;
    }

    creds->secret_access_key = get_node(cred_node, SECRET_KEY_NODE,
                                        SECRET_KEY_NODE_LEN, SECRET_KEY_NODE_END);
    if (!creds->secret_access_key) {
        goto error;
    }

    creds->session_token = get_node(cred_node, SESSION_TOKEN_NODE,
                                    SESSION_TOKEN_NODE_LEN, SESSION_TOKEN_NODE_END);
    if (!creds->session_token) {
        goto error;
    }

    tmp = get_node(cred_node, EXPIRATION_NODE, EXPIRATION_NODE_LEN, EXPIRATION_NODE_END);
    if (!tmp) {
        goto error;
    }
    *expiration = flb_aws_cred_expiration(tmp);

    flb_sds_destroy(tmp);
    return creds;

error:
    flb_aws_credentials_destroy(creds);
    if (tmp) {
        flb_sds_destroy(tmp);
    }
    return NULL;
}

/*
 * Constructs the STS request uri.
 * external_id can be NULL.
 */
flb_sds_t flb_sts_uri(char *action, char *role_arn, char *session_name,
                      char *external_id, char *identity_token)
{
    flb_sds_t tmp;
    flb_sds_t uri = NULL;
    size_t len = STS_ASSUME_ROLE_URI_BASE_LEN;

    if (external_id) {
        len += 12; /* will add "&ExternalId=" */
        len += strlen(external_id);
    }

    if (identity_token) {
        len += 18; /* will add "&WebIdentityToken=" */
        len += strlen(identity_token);
    }


    len += strlen(session_name);
    len += strlen(role_arn);
    len += strlen(action);
    len++; /* null char */

    uri = flb_sds_create_size(len);
    if (!uri) {
        return NULL;
    }

    tmp = flb_sds_printf(&uri, STS_ASSUME_ROLE_URI_FORMAT, action, session_name,
                         role_arn);
    if (!tmp) {
        flb_sds_destroy(uri);
        return NULL;
    }

    if (external_id) {
        flb_sds_printf(&uri, "&ExternalId=%s", external_id);
    }

    if (identity_token) {
        flb_sds_printf(&uri, "&WebIdentityToken=%s", identity_token);
    }

    return uri;
}

static flb_sds_t get_node(char *cred_node, char* node_name, int node_name_len, char* node_end)
{
    char *node = NULL;
    char *end = NULL;
    flb_sds_t val = NULL;
    int len;

    node = strstr(cred_node, node_name);
    if (!node) {
        flb_error("[aws_credentials] Could not find '%s' node in sts response",
                  node_name);
        return NULL;
    }
    node += node_name_len;
    end = strstr(node, node_end);
    if (!end) {
        flb_error("[aws_credentials] Could not find end of '%s' node in "
                  "sts response", node_name);
        return NULL;
    }
    len = end - node;
    val = flb_sds_create_len(node, len);
    if (!val) {
        flb_errno();
        return NULL;
    }

    return val;
}