-
Notifications
You must be signed in to change notification settings - Fork 311
Expand file tree
/
Copy pathjsecrets.cpp
More file actions
2510 lines (2185 loc) · 85.2 KB
/
jsecrets.cpp
File metadata and controls
2510 lines (2185 loc) · 85.2 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
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
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2020 HPCC Systems®.
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 "jstring.hpp"
#include "platform.h"
#include "jlog.hpp"
#include "jutil.hpp"
#include "jexcept.hpp"
#include "jmutex.hpp"
#include "jfile.hpp"
#include "jptree.hpp"
#include "jerror.hpp"
#include "jsecrets.hpp"
#include "jthread.hpp"
//including cpp-httplib single header file REST client
// doesn't work with format-nonliteral as an error
//
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
//httplib also generates warning about access outside of array bounds in gcc
#pragma GCC diagnostic ignored "-Warray-bounds"
#endif
#if defined(_USE_OPENSSL) || defined(EMSCRIPTEN)
#define CPPHTTPLIB_OPENSSL_SUPPORT
#endif
#undef INVALID_SOCKET
#include "httplib.h"
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#ifdef verify
#define JWT_HAS_VERIFY_MACRO
#define OLD_VERIFY verify
#undef verify
#endif
#include "jwt-cpp/jwt.h"
#include "nlohmann/json.hpp"
#ifdef JWT_HAS_VERIFY_MACRO
//Force an error if verify macro is used in any of the following code
#undef verify
#endif
#ifdef _USE_OPENSSL
#include <opensslcommon.hpp>
#include <openssl/x509v3.h>
#endif
//#define TRACE_SECRETS
#include <vector>
// Vault specific support
enum class CVaultKind {
kv_v1, // Hashicorp vault API version 1
kv_v2, // Hashicorp vault API version 2
akeyless_v2 // Akeyless vault API version 2
};
enum class VaultType { hashicorp, akeyless }; // Vault provider type.
CVaultKind getSecretType(const char *s)
{
if (isEmptyString(s))
return CVaultKind::kv_v2;
if (strieq(s, "kv-v1"))
return CVaultKind::kv_v1;
if (strieq(s, "kv-v2"))
return CVaultKind::kv_v2;
if (strieq(s, "akeyless"))
return CVaultKind::akeyless_v2;
return CVaultKind::kv_v2;
}
static VaultType getVaultType(const char *s)
{
if (strisame(s, "akeyless"))
return VaultType::akeyless;
return VaultType::hashicorp;
}
interface IVaultManager : extends IInterface
{
virtual IPropertyTree *requestSecretFromVault(const char *category, const char *vaultId, const char *secret, const char *version) = 0;
virtual IPropertyTree *requestSecretByCategory(const char *category, const char *secret, const char *version) = 0;
};
static Owned<IVaultManager> vaultManager;
static MemoryAttr udpKey;
static bool udpKeyInitialized = false;
static const IPropertyTree *getLocalSecret(const char *category, const char * name)
{
return getSecret(category, name, "k8s", nullptr);
}
// based on kubernetes secret / key names. Even if some vault backends support additional characters we'll restrict to this subset for now
// isKeyName is not currently used, but may be in the future
inline static bool isValidSecretOrKeyNameChr(char c, bool firstOrLastChar, bool isKeyName)
{
if (c == '\0')
return false;
if (isalnum(c))
return true;
if (firstOrLastChar)
return false;
switch (c)
{
case '.':
case '-':
case '_': //keyname supports '_', relax restrictions for all - since supported by vaults
return true;
default:
return false;
}
}
static bool isValidSecretOrKeyName(const char *name, bool isKeyName)
{
if (!isValidSecretOrKeyNameChr(*name, true, isKeyName))
return false;
++name;
while ('\0' != *name)
{
bool lastChar = ('\0' == *(name+1));
if (!isValidSecretOrKeyNameChr(*name, lastChar, isKeyName))
return false;
++name;
}
return true;
}
static void validateCategoryName(const char *category)
{
if (!isValidSecretOrKeyName(category, true))
throw makeStringExceptionV(-1, "Invalid secret category %s", category);
}
static void validateSecretNameNotEmpty(const char *name)
{
if (isEmptyString(name))
throw makeStringExceptionV(-1, "Invalid secret name %s", name);
}
static void validateKeyName(const char *key)
{
if (!isValidSecretOrKeyName(key, true))
throw makeStringExceptionV(-1, "Invalid secret key name %s", key);
}
static bool isUnsignedInteger(const char *value)
{
if (isEmptyString(value))
return false;
for (const char *cur = value; *cur; ++cur)
{
if (!isdigit(*cur))
return false;
}
return true;
}
static void splitUrlAddress(const char *address, size_t len, StringBuffer &host, StringBuffer &port)
{
if (!address || len==0)
return;
const char *sep = (const char *)memchr(address, ':', len);
if (!sep)
host.append(len, address);
else
{
host.append(sep - address, address);
len = len - (sep - address) - 1;
port.append(len, sep+1);
}
}
static void splitUrlAuthority(const char *authority, size_t authorityLen, StringBuffer &user, StringBuffer &password, StringBuffer &host, StringBuffer &port)
{
if (!authority || authorityLen==0)
return;
const char *at = (const char *) memchr(authority, '@', authorityLen);
if (!at)
splitUrlAddress(authority, authorityLen, host, port);
else
{
size_t userinfoLen = (at - authority);
splitUrlAddress(at+1, authorityLen - userinfoLen - 1, host, port);
const char *sep = (const char *) memchr(authority, ':', at - authority);
if (!sep)
user.append(at-authority, authority);
else
{
user.append(sep-authority, authority);
size_t passwordLen = (at - sep - 1);
password.append(passwordLen, sep+1);
}
}
}
static void splitUrlAuthorityHostPort(const char *authority, size_t authorityLen, StringBuffer &user, StringBuffer &password, StringBuffer &hostPort)
{
StringBuffer port;
splitUrlAuthority(authority, authorityLen, user, password, hostPort, port);
if (port.length())
hostPort.append(':').append(port);
}
static inline void extractUrlProtocol(const char *&url, StringBuffer *scheme)
{
if (!url)
throw makeStringException(-1, "Invalid empty URL");
if (0 == strnicmp(url, "HTTPS://", 8))
{
url+=8;
if (scheme)
scheme->append("https://");
}
else if (0 == strnicmp(url, "HTTP://", 7))
{
url+=7;
if (scheme)
scheme->append("http://");
}
else
throw MakeStringException(-1, "Invalid URL, protocol not recognized %s", url);
}
static void splitUrlSections(const char *url, const char * &authority, size_t &authorityLen, StringBuffer &fullpath, StringBuffer *scheme)
{
extractUrlProtocol(url, scheme);
const char* path = strchr(url, '/');
authority = url;
if (!path)
authorityLen = strlen(authority);
else
{
authorityLen = path-url;
if (!streq(path, "/")) // treat empty trailing path as equal to no path
fullpath.append(path);
}
}
extern jlib_decl void splitFullUrl(const char *url, StringBuffer &user, StringBuffer &password, StringBuffer &host, StringBuffer &port, StringBuffer &path)
{
const char *authority = nullptr;
size_t authorityLen = 0;
splitUrlSections(url, authority, authorityLen, path, nullptr);
splitUrlAuthority(authority, authorityLen, user, password, host, port);
}
extern jlib_decl void splitUrlSchemeHostPort(const char *url, StringBuffer &user, StringBuffer &password, StringBuffer &schemeHostPort, StringBuffer &path)
{
const char *authority = nullptr;
size_t authorityLen = 0;
splitUrlSections(url, authority, authorityLen, path, &schemeHostPort);
splitUrlAuthorityHostPort(authority, authorityLen, user, password, schemeHostPort);
}
extern jlib_decl void splitUrlIsolateScheme(const char *url, StringBuffer &user, StringBuffer &password, StringBuffer &scheme, StringBuffer &host, StringBuffer &port, StringBuffer &path)
{
const char *authority = nullptr;
size_t authorityLen = 0;
splitUrlSections(url, authority, authorityLen, path, &scheme);
splitUrlAuthority(authority, authorityLen, user, password, host, port);
}
static StringBuffer &replaceExtraHostAndPortChars(StringBuffer &s)
{
size_t l = s.length();
for (size_t i = 0; i < l; i++)
{
if (s.charAt(i) == '.' || s.charAt(i) == ':')
s.setCharAt(i, '-');
}
return s;
}
extern jlib_decl StringBuffer &generateDynamicUrlSecretName(StringBuffer &secretName, const char *scheme, const char *userPasswordPair, const char *host, unsigned port, const char *path)
{
secretName.set("http-connect-");
//Having the host and port visible will help with manageability wherever the secret is stored
if (scheme)
{
if (!strnicmp("http", scheme, 4))
{
if ('s' == scheme[4])
{
if (443 == port)
port = 0; // suppress default port, such that with or without, the generated secret name will be the same
secretName.append("ssl-");
}
else if (':' == scheme[4])
{
if (80 == port)
port = 0; // suppress default port, such that with or without, the generated secret name will be the same
}
}
}
secretName.append(host);
//port is optionally already part of host
replaceExtraHostAndPortChars(secretName);
if (port)
secretName.append('-').append(port);
//Path and username are both sensitive and shouldn't be accessible in the name, include both in the hash to give us the uniqueness we need
unsigned hashvalue = 0;
if (!isEmptyString(path))
hashvalue = hashcz((const unsigned char *)path, hashvalue);
if (!isEmptyString(userPasswordPair))
{
const char *delim = strchr(userPasswordPair, ':');
//Make unique for a given username, but not the current password. The pw provided could change but what's in the secret (if there is one) wins
if (delim)
hashvalue = hashc((const unsigned char *)userPasswordPair, delim-userPasswordPair, hashvalue);
else
hashvalue = hashcz((const unsigned char *)userPasswordPair, hashvalue);
}
if (hashvalue)
secretName.appendf("-%x", hashvalue);
return secretName;
}
extern jlib_decl StringBuffer &generateDynamicUrlSecretName(StringBuffer &secretName, const char *url, const char *inputUsername)
{
StringBuffer username;
StringBuffer urlPassword;
StringBuffer scheme;
StringBuffer host;
StringBuffer port;
StringBuffer path;
splitUrlIsolateScheme(url, username, urlPassword, scheme, host, port, path);
if (!isEmptyString(inputUsername))
username.set(inputUsername);
unsigned portNum = port.length() ? atoi(port) : 0;
return generateDynamicUrlSecretName(secretName, scheme, username, host, portNum, path);
}
//---------------------------------------------------------------------------------------------------------------------
static StringBuffer secretDirectory;
static CriticalSection secretCS;
//there are various schemes for renewing kubernetes secrets and they are likely to vary greatly in how often
// a secret gets updated this timeout determines the maximum amount of time before we'll pick up a change
// 10 minutes for now we can change this as we gather more experience and user feedback
static unsigned __int64 secretTimeoutNs = 10 * 60 * 1000000000LL;
extern jlib_decl unsigned getSecretTimeout()
{
return secretTimeoutNs / 1000000;
}
extern jlib_decl void setSecretTimeout(unsigned timeoutMs)
{
secretTimeoutNs = (unsigned __int64)timeoutMs * 1000000;
}
extern jlib_decl void setSecretMount(const char * path)
{
if (!path)
{
getPackageFolder(secretDirectory);
addPathSepChar(secretDirectory).append("secrets");
}
else
secretDirectory.set(path);
}
static const char *ensureSecretDirectory()
{
CriticalBlock block(secretCS);
if (secretDirectory.isEmpty())
setSecretMount(nullptr);
return secretDirectory;
}
static StringBuffer &buildSecretPath(StringBuffer &path, const char *category, const char * name)
{
return addPathSepChar(path.append(ensureSecretDirectory())).append(category).append(PATHSEPCHAR).append(name).append(PATHSEPCHAR);
}
enum class VaultAuthType {unknown, k8s, appRole, token, clientcert};
static void setTimevalMS(timeval &tv, time_t ms)
{
if (!ms)
tv = {0, 0};
else
{
tv.tv_sec = ms / 1000;
tv.tv_usec = (ms % 1000)*1000;
}
}
static bool isEmptyTimeval(const timeval &tv)
{
return (tv.tv_sec==0 && tv.tv_usec==0);
}
//---------------------------------------------------------------------------------------------------------------------
//The secret key has the form category/name[@vaultId][#version]
static std::string buildSecretKey(const char * category, const char * name, const char * optVaultId, const char * optVersion)
{
std::string key;
key.append(category).append("/").append(name);
if (optVaultId)
key.append("@").append(optVaultId);
if (optVersion)
key.append("#").append(optVersion);
return key;
}
static void expandSecretKey(std::string & category, std::string & name, std::string & optVaultId, std::string & optVersion, const char * key)
{
const char * slash = strchr(key, '/');
assertex(slash);
const char * at = strchr(slash, '@');
const char * hash = strchr(slash, '#');
const char * end = nullptr;
if (hash)
{
optVersion.assign(hash+1);
end = hash;
}
if (at)
{
if (end)
optVaultId.assign(at+1, end-at-1);
else
optVaultId.assign(at+1);
end = at;
}
if (end)
name.assign(slash+1, end-slash-1);
else
name.assign(slash+1);
category.assign(key, slash-key);
}
//---------------------------------------------------------------------------------------------------------------------
//Represents an entry in the secret cache. Once created it is always used for the secret.
using cache_timestamp = unsigned __int64;
using cache_timestamp_diff = __int64;
inline cache_timestamp getCacheTimestamp() { return nsTick(); }
class SecretCacheEntry : public CInterface
{
friend class SecretCache;
public:
//A cache entry is initally created that has a create and access,and check time of now
SecretCacheEntry(cache_timestamp _now, const char * _secretKey)
: secretKey(_secretKey), contentTimestamp(_now), accessedTimestamp(_now), checkedTimestamp(_now)
{
}
unsigned getHash() const
{
return contentHash;
}
void getSecretOptions(std::string & category, std::string & name, std::string & optVaultId, std::string & optVersion)
{
expandSecretKey(category, name, optVaultId, optVersion, secretKey.c_str());
}
// We should never replace known contents for unknown contents
// so once this returns true it should always return true
bool hasContents() const
{
return contents != nullptr;
}
//Has the secret value been used since it was last checked for an update?
bool isActive() const
{
return (cache_timestamp_diff)(accessedTimestamp - checkedTimestamp) >= 0;
}
//Is the secret potentially out of date?
bool isStale() const
{
cache_timestamp now = getCacheTimestamp();
cache_timestamp elapsed = (now - contentTimestamp);
return (elapsed > secretTimeoutNs);
}
// Is it time to check if there is a new value for this secret?
bool needsRefresh(cache_timestamp now) const
{
if (!initialized)
return true;
cache_timestamp elapsed = (now - checkedTimestamp);
return (elapsed > secretTimeoutNs);
}
void noteAccessed(cache_timestamp now)
{
accessedTimestamp = now;
}
void noteFailedUpdate(cache_timestamp now, bool accessed)
{
//Update the checked timestamp - so that we do not continually check for updates to secrets which
//are stale because the vault or other source of values in inaccessible.
//Keep using the last good value
initialized = true;
checkedTimestamp = now;
if (accessed)
accessedTimestamp = now;
}
const char * queryTraceName() const { return secretKey.c_str(); }
//The following functions can only be called from member functions of SecretCache
private:
void updateContents(IPropertyTree * _contents, cache_timestamp now, bool accessed)
{
initialized = true;
contents.set(_contents);
updateHash();
contentTimestamp = now;
checkedTimestamp = now;
if (accessed)
accessedTimestamp = now;
}
void updateHash()
{
if (contents)
contentHash = getPropertyTreeHash(*contents, 0x811C9DC5);
else
contentHash = 0;
}
private:
const std::string secretKey; // Duplicate of the key used to find this entry in the cache
Linked<IPropertyTree> contents;// Can only be accessed when SecretCache::cs is held
cache_timestamp contentTimestamp = 0; // When was this secret read from disk/vault
cache_timestamp accessedTimestamp = 0; // When was this secret last accessed?
cache_timestamp checkedTimestamp = 0; // When was this last checked for updates?
unsigned contentHash = 0;
bool initialized = false;
};
// A cache of (secret[:version] to a secret cache entry)
// Once a hash table entry has been created for a secret it is never removed and the associated
// value is never replaced. This means it is safe to keep a pointer to the entry in another class.
class SecretCache
{
public:
const IPropertyTree * getContents(SecretCacheEntry * match)
{
//Return contents within the critical section so no other thread can modify it
CriticalBlock block(cs);
return LINK(match->contents);
}
//Check to see if a secret exists, and if not add a null entry that has expired.
SecretCacheEntry * getSecret(const std::string & secretKey, cache_timestamp now, bool & isNewEntry)
{
SecretCacheEntry * result;
isNewEntry = false;
CriticalBlock block(cs);
auto match = secrets.find(secretKey);
if (match != secrets.cend())
{
result = match->second.get();
result->accessedTimestamp = now;
}
else
{
//Insert an entry with a null value
result = new SecretCacheEntry(now, secretKey.c_str());
secrets.emplace(secretKey, result);
isNewEntry = true;
}
return result;
}
void gatherPendingRefresh(std::vector<SecretCacheEntry *> & pending, cache_timestamp when)
{
CriticalBlock block(cs);
for (auto & entry : secrets)
{
SecretCacheEntry * secret = entry.second.get();
//Only refresh secrets that have been used since the last time they were refreshed, otherwise the vault
//may be overloaed with unnecessary requests - since secrets are never removed from the hash table.
if (secret->isActive() && secret->needsRefresh(when))
pending.push_back(secret);
}
}
void updateSecret(SecretCacheEntry * match, IPropertyTree * value, cache_timestamp now, bool accessed)
{
CriticalBlock block(cs);
match->updateContents(value, now, accessed);
}
private:
CriticalSection cs;
std::unordered_map<std::string, std::unique_ptr<SecretCacheEntry>> secrets;
};
//---------------------------------------------------------------------------------------------------------------------
class CVault
{
public:
virtual ~CVault() = default;
virtual IPropertyTree *requestSecret(const char *secret, const char *version) = 0;
CVaultKind getVaultKind() const { return kind; }
VaultType getVaultType() const { return vaultType; }
// Static helper to extract and prepare namespace from config
static StringAttr prepareNamespace(const IPropertyTree *vault, bool stripLeadingSlash=false)
{
StringBuffer ns;
ns.set(vault->queryProp("@namespace"));
if (stripLeadingSlash)
{
while (ns.length() && ns.charAt(0) == '/')
ns.remove(0, 1);
}
if (ns.length())
addPathSepChar(ns, '/');
return StringAttr(ns.str());
}
protected:
enum class SecretFetchStatus
{
success,
authFailure,
notFound,
failure
};
CVault(const IPropertyTree *vault, VaultType _vaultType, CVaultKind vaultKind, const char *namespace_prepared = nullptr)
{
category.appendLower(vault->queryName());
StringBuffer url;
replaceEnvVariables(url, vault->queryProp("@url"), false);
PROGLOG("vault url %s", url.str());
if (url.length())
splitUrlSchemeHostPort(url.str(), username, password, schemeHostPort, path);
if (username.length() || password.length())
WARNLOG("vault: unexpected use of basic auth in url, user=%s", username.str());
name.set(vault->queryProp("@name"));
// Vault type and kind are fixed by derived class.
vaultType = _vaultType;
kind = vaultKind;
// namespace is prepared and passed in by derived class
if (!isEmptyString(namespace_prepared))
vaultNamespace.set(namespace_prepared);
verify_server = vault->getPropBool("@verify_server", true);
retries = (unsigned) vault->getPropInt("@retries", retries);
retryWait = (unsigned) vault->getPropInt("@retryWait", retryWait);
if (vault->hasProp("@backoffTimeout"))
backoffTimeoutUs = vault->getPropInt64("@backoffTimeout") * 1000ULL;
setTimevalMS(connectTimeout, (time_t) vault->getPropInt("@connectTimeout"));
setTimevalMS(readTimeout, (time_t) vault->getPropInt("@readTimeout"));
setTimevalMS(writeTimeout, (time_t) vault->getPropInt("@writeTimeout"));
PROGLOG("Vault: httplib verify_server=%s", boolToStr(verify_server));
}
void initHttpClient(httplib::Client &cli, httplib::Headers &headers, unsigned &numRetries)
{
numRetries = retries;
cli.enable_server_certificate_verification(verify_server);
if (!isEmptyTimeval(connectTimeout))
cli.set_connection_timeout(connectTimeout.tv_sec, connectTimeout.tv_usec);
if (!isEmptyTimeval(readTimeout))
cli.set_read_timeout(readTimeout.tv_sec, readTimeout.tv_usec);
if (!isEmptyTimeval(writeTimeout))
cli.set_write_timeout(writeTimeout.tv_sec, writeTimeout.tv_usec);
if (username.length() && password.length())
cli.set_basic_auth(username, password);
}
void throwAuthError(const char *authType, const char *msg)
{
Owned<IException> e = makeStringExceptionV(0, "Vault [%s] %s auth error %s", name.str(), authType, msg);
OERRLOG(e);
throw e.getClear();
}
void throwAuthErrorV(const char *authType, const char* format, ...) __attribute__((format(printf, 3, 4)))
{
va_list args;
va_start(args, format);
StringBuffer msg;
msg.valist_appendf(format, args);
va_end(args);
throwAuthError(authType, msg);
}
protected:
CVaultKind kind;
VaultType vaultType = VaultType::hashicorp;
CriticalSection vaultCS;
StringBuffer category;
StringBuffer schemeHostPort;
StringBuffer path;
StringBuffer vaultNamespace;
StringBuffer username;
StringBuffer password;
StringAttr name;
bool verify_server = true;
unsigned retries = 3;
unsigned retryWait = 1000;
timestamp_type backoffTimeoutUs = 0; // Default to no backoff
std::atomic<timestamp_type> backoffFailureTs{0};
timeval connectTimeout = {0, 0};
timeval readTimeout = {0, 0};
timeval writeTimeout = {0, 0};
};
class CHashicorpVault final : public CVault
{
private:
VaultAuthType authType = VaultAuthType::unknown;
std::string clientCertPath;
std::string clientKeyPath;
StringAttr authRole; //authRole is used by kubernetes and client cert auth, it's not part of appRole auth
StringAttr appRoleId;
StringBuffer appRoleSecretName;
StringBuffer clientToken;
time_t clientTokenExpiration = 0;
bool clientTokenRenewable = false;
public:
CHashicorpVault(const IPropertyTree *vault, CVaultKind vaultKind)
: CVault(vault, VaultType::hashicorp, vaultKind, CVault::prepareNamespace(vault))
{
StringBuffer clientTlsPath;
buildSecretPath(clientTlsPath, "certificates", "vaultclient");
clientCertPath.append(clientTlsPath.str()).append(category.str()).append("/tls.crt");
clientKeyPath.append(clientTlsPath.str()).append(category.str()).append("/tls.key");
if (!checkFileExists(clientCertPath.c_str()))
WARNLOG("vault: client cert not found, %s", clientCertPath.c_str());
if (!checkFileExists(clientKeyPath.c_str()))
WARNLOG("vault: client key not found, %s", clientKeyPath.c_str());
//set up vault client auth [appRole, clientToken (aka "token from the sky"), or kubernetes auth]
appRoleId.set(vault->queryProp("@appRoleId"));
if (appRoleId.length())
{
authType = VaultAuthType::appRole;
if (vault->hasProp("@appRoleSecret"))
appRoleSecretName.set(vault->queryProp("@appRoleSecret"));
if (appRoleSecretName.isEmpty())
appRoleSecretName.set("appRoleSecret");
}
else if (vault->hasProp("@client-secret"))
{
Owned<const IPropertyTree> clientSecret = getLocalSecret("system", vault->queryProp("@client-secret"));
if (clientSecret)
{
StringBuffer tokenText;
// NOTE: Token is loaded once at construction from filesystem (via getLocalSecret() which reads Kubernetes-mounted secrets).
// The secret is NOT re-read on every request; instead it is cached in clientToken.
// If using Kubernetes secrets: kubelet automatically updates the mounted filesystem when the secret is rotated,
// but this code must detect the update via error responses. If using an externalized vault backend for client-secret,
// that backend would need to ensure the filesystem is updated when tokens rotate.
// Token rotation is detected via: (1) isClientTokenExpired() checking lease_duration (if available), or
// (2) a 403 permission denied error triggering relogin via checkAuthentication().
// Both mechanisms re-read the filesystem, picking up the new token.
if (getSecretKeyValue(clientToken, clientSecret, "token"))
{
authType = VaultAuthType::token;
PROGLOG("using a client token for vault auth");
}
}
}
else if (vault->getPropBool("@useTLSCertificateAuth", false))
{
authType = VaultAuthType::clientcert;
if (vault->hasProp("@role"))
authRole.set(vault->queryProp("@role"));
}
else if (isContainerized())
{
authType = VaultAuthType::k8s;
if (vault->hasProp("@role"))
authRole.set(vault->queryProp("@role"));
else
authRole.set("hpcc-vault-access");
PROGLOG("using kubernetes vault auth");
}
}
virtual IPropertyTree *requestSecret(const char *secret, const char *version) override
{
if (isEmptyString(secret))
return nullptr;
StringBuffer location(path);
location.replaceString("${secret}", secret);
location.replaceString("${version}", version ? version : "1");
StringBuffer content;
if (requestSecretAtLocation(content, location, secret, version, false) != SecretFetchStatus::success)
return nullptr;
return parseHashicorpSecretResponse(content.str());
}
private:
IPropertyTree *parseHashicorpSecretResponse(const char *content)
{
if (isEmptyString(content))
return nullptr;
Owned<IPropertyTree> tree;
try
{
tree.setown(createPTreeFromJSONString(content));
}
catch (IException * e)
{
OERRLOG(e, "Failed to parse vault secret JSON response");
e->Release();
return nullptr;
}
// Extract data based on Hashicorp KV version
if (kind == CVaultKind::kv_v1)
{
return tree->getPropTree("data");
}
else if (kind == CVaultKind::kv_v2)
{
return tree->getPropTree("data/data");
}
else
{
return nullptr;
}
}
inline const char *queryAuthType()
{
switch (authType)
{
case VaultAuthType::appRole:
return "approle";
case VaultAuthType::k8s:
return "kubernetes";
case VaultAuthType::token:
return "token";
case VaultAuthType::clientcert:
return "clientcert";
}
return "unknown";
}
void buildClientHeaders(httplib::Headers &headers) const
{
if (vaultNamespace.length())
headers.emplace("X-Vault-Namespace", vaultNamespace.str());
}
void processClientTokenResponse(httplib::Result &res)
{
if (!res)
throwAuthErrorV(queryAuthType(), "login communication error %d", res.error());
if (res.error()!=0)
throwAuthErrorV(queryAuthType(), "JSECRETS login calling HTTPLIB POST returned error %d", res.error());
if (res->status != 200)
throwAuthErrorV(queryAuthType(), "[%d](%d) - response: %s", res->status, res.error(), res->body.c_str());
const char *json = res->body.c_str();
if (isEmptyString(json))
throwAuthError(queryAuthType(), "empty login response");
Owned<IPropertyTree> respTree;
try
{
respTree.setown(createPTreeFromJSONString(json));
}
catch (IException *e)
{
StringBuffer msg("parsing JSON response: ");
e->errorMessage(msg);
e->Release();
throwAuthError(queryAuthType(), msg.str());
}
const char *token = respTree->queryProp("auth/client_token");
if (isEmptyString(token))
throwAuthError(queryAuthType(), "response missing client_token");
clientToken.set(token);
clientTokenRenewable = respTree->getPropBool("auth/renewable");
unsigned lease_duration = respTree->getPropInt("auth/lease_duration");
if (lease_duration==0)
clientTokenExpiration = 0;
else
clientTokenExpiration = time(nullptr) + lease_duration;
PROGLOG("VAULT TOKEN duration=%d", lease_duration);
}
bool isClientTokenExpired()
{
if (clientTokenExpiration==0)
return false;
double remaining = difftime(clientTokenExpiration, time(nullptr));
if (remaining <= 0)
{
PROGLOG("vault auth client token expired");
return true;
}
//TBD check renewal
return false;
}
//if we tried to use our token and it returned access denied it could be that we need to login again, or
// perhaps it could be specific permissions about the secret that was being accessed, I don't think we can tell the difference
void kubernetesLogin(bool permissionDenied)
{
CriticalBlock block(vaultCS);
if (!permissionDenied && (clientToken.length() && !isClientTokenExpired()))
return;
DBGLOG("kubernetesLogin%s", permissionDenied ? " because existing token permission denied" : "");
StringBuffer login_token;
login_token.loadFile("/var/run/secrets/kubernetes.io/serviceaccount/token");
if (login_token.isEmpty())
throwAuthError(queryAuthType(), "missing k8s auth token");
std::string json;
json.append("{\"jwt\": \"").append(login_token.str()).append("\", \"role\": \"").append(authRole.str()).append("\"}");
httplib::Client cli(schemeHostPort.str());
httplib::Headers headers;
buildClientHeaders(headers);
unsigned numRetries = 0;
initHttpClient(cli, headers, numRetries);
httplib::Result res = cli.Post("/v1/auth/kubernetes/login", headers, json, "application/json");
while (!res && numRetries > 0)
{
OERRLOG("Retrying vault %s kubernetes auth, communication error %d", name.str(), res.error());
if (retryWait)
Sleep(retryWait);
numRetries--;
res = cli.Post("/v1/auth/kubernetes/login", headers, json, "application/json");
}
processClientTokenResponse(res);
}
void clientCertLogin(bool permissionDenied)
{
CriticalBlock block(vaultCS);
if (!permissionDenied && (clientToken.length() && !isClientTokenExpired()))
return;
DBGLOG("clientCertLogin%s", permissionDenied ? " because existing token permission denied" : "");
std::string json;
json.append("{\"name\": \"").append(authRole.str()).append("\"}"); //name can be empty but that is inefficient because vault would have to search for the cert being used