forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathIAccessStorage.cpp
More file actions
1065 lines (890 loc) · 39.3 KB
/
Copy pathIAccessStorage.cpp
File metadata and controls
1065 lines (890 loc) · 39.3 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
#include <Access/IAccessStorage.h>
#include <Access/Authentication.h>
#include <Access/Common/AuthenticationType.h>
#include <Access/Credentials.h>
#include <Access/User.h>
#include <Access/AccessBackup.h>
#include <Backups/BackupEntriesCollector.h>
#include <Backups/IBackupCoordination.h>
#include <Backups/IRestoreCoordination.h>
#include <Backups/RestoreSettings.h>
#include <Backups/RestorerFromBackup.h>
#include <Common/Exception.h>
#include <Common/quoteString.h>
#include <Common/callOnce.h>
#include <base/scope_guard.h>
#include <IO/WriteHelpers.h>
#include <Interpreters/Context.h>
#include <Parsers/parseIdentifierOrStringLiteral.h>
#include <Poco/UUIDGenerator.h>
#include <Poco/Logger.h>
#include <base/FnTraits.h>
#include <base/range.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/range/algorithm/copy.hpp>
namespace DB
{
namespace ErrorCodes
{
extern const int ACCESS_ENTITY_ALREADY_EXISTS;
extern const int ACCESS_ENTITY_NOT_FOUND;
extern const int ACCESS_STORAGE_READONLY;
extern const int ACCESS_STORAGE_DOESNT_ALLOW_BACKUP;
extern const int REQUIRED_SECOND_FACTOR;
extern const int WRONG_PASSWORD;
extern const int IP_ADDRESS_NOT_ALLOWED;
extern const int LOGICAL_ERROR;
extern const int NOT_IMPLEMENTED;
}
namespace
{
String outputID(const UUID & id)
{
return "ID(" + toString(id) + ")";
}
/// Tracks how deep we are inside `IAccessStorage::remove`. Concrete storages (e.g.
/// `DiskAccessStorage`) call `remove` on their internal in-memory cache, and
/// `MultipleAccessStorage::removeImpl` delegates to a sub-storage's `remove`. We
/// only want to cascade dependency cleanup once — at the outermost user-facing call —
/// otherwise an inner cascade can update the in-memory state without writing it to
/// disk, and the outer cascade then sees no work to do.
thread_local size_t remove_depth = 0;
}
std::vector<UUID> IAccessStorage::findAll(AccessEntityType type) const
{
return findAllImpl(type);
}
std::optional<UUID> IAccessStorage::find(AccessEntityType type, const String & name) const
{
return findImpl(type, name);
}
std::vector<UUID> IAccessStorage::find(AccessEntityType type, const Strings & names) const
{
std::vector<UUID> ids;
ids.reserve(names.size());
for (const String & name : names)
{
auto id = findImpl(type, name);
if (id)
ids.push_back(*id);
}
return ids;
}
std::vector<UUID> IAccessStorage::findAllImpl() const
{
std::vector<UUID> res;
for (auto type : collections::range(AccessEntityType::MAX))
{
auto ids = findAllImpl(type);
res.insert(res.end(), ids.begin(), ids.end());
}
return res;
}
UUID IAccessStorage::getID(AccessEntityType type, const String & name) const
{
auto id = findImpl(type, name);
if (id)
return *id;
throwNotFound(type, name, storage_name);
}
std::vector<UUID> IAccessStorage::getIDs(AccessEntityType type, const Strings & names) const
{
std::vector<UUID> ids;
ids.reserve(names.size());
for (const String & name : names)
ids.push_back(getID(type, name));
return ids;
}
String IAccessStorage::readName(const UUID & id) const
{
return readNameWithType(id).first;
}
bool IAccessStorage::exists(const std::vector<UUID> & ids) const
{
for (const auto & id : ids)
{
if (!exists(id))
return false;
}
return true;
}
std::optional<String> IAccessStorage::readName(const UUID & id, bool throw_if_not_exists) const
{
if (auto name_and_type = readNameWithType(id, throw_if_not_exists))
return name_and_type->first;
return std::nullopt;
}
Strings IAccessStorage::readNames(const UUIDs & ids, bool throw_if_not_exists) const
{
Strings res;
res.reserve(ids.size());
for (const auto & id : ids)
{
if (auto name = readName(id, throw_if_not_exists))
res.emplace_back(std::move(name).value());
}
return res;
}
std::optional<String> IAccessStorage::tryReadName(const UUID & id) const
{
return readName(id, /* throw_if_not_exists = */ false);
}
Strings IAccessStorage::tryReadNames(const UUIDs & ids) const
{
return readNames(ids, /* throw_if_not_exists = */ false);
}
std::pair<String, AccessEntityType> IAccessStorage::readNameWithType(const UUID & id) const
{
return *readNameWithTypeImpl(id, /* throw_if_not_exists = */ true);
}
std::optional<std::pair<String, AccessEntityType>> IAccessStorage::readNameWithType(const UUID & id, bool throw_if_not_exists) const
{
return readNameWithTypeImpl(id, throw_if_not_exists);
}
std::optional<std::pair<String, AccessEntityType>> IAccessStorage::tryReadNameWithType(const UUID & id) const
{
return readNameWithTypeImpl(id, /* throw_if_not_exists = */ false);
}
std::optional<std::pair<String, AccessEntityType>> IAccessStorage::readNameWithTypeImpl(const UUID & id, bool throw_if_not_exists) const
{
if (auto entity = read(id, throw_if_not_exists))
return std::make_pair(entity->getName(), entity->getType());
return std::nullopt;
}
std::vector<std::pair<UUID, AccessEntityPtr>> IAccessStorage::readAllWithIDs(AccessEntityType type) const
{
std::vector<std::pair<UUID, AccessEntityPtr>> entities;
for (const auto & id : findAll(type))
{
if (auto entity = tryRead(id))
entities.emplace_back(id, entity);
}
return entities;
}
UUID IAccessStorage::insert(const AccessEntityPtr & entity)
{
return *insert(entity, /* replace_if_exists = */ false, /* throw_if_exists = */ true);
}
std::optional<UUID> IAccessStorage::insert(const AccessEntityPtr & entity, bool replace_if_exists, bool throw_if_exists, UUID * conflicting_id)
{
auto id = generateRandomID();
if (insert(id, entity, replace_if_exists, throw_if_exists, conflicting_id))
return id;
return std::nullopt;
}
bool IAccessStorage::insert(const DB::UUID & id, const DB::AccessEntityPtr & entity, bool replace_if_exists, bool throw_if_exists, UUID * conflicting_id)
{
return insertImpl(id, entity, replace_if_exists, throw_if_exists, conflicting_id);
}
std::vector<UUID> IAccessStorage::insert(const std::vector<AccessEntityPtr> & multiple_entities, bool replace_if_exists, bool throw_if_exists)
{
return insert(multiple_entities, /* ids = */ {}, replace_if_exists, throw_if_exists);
}
std::vector<UUID> IAccessStorage::insert(const std::vector<AccessEntityPtr> & multiple_entities, const std::vector<UUID> & ids, bool replace_if_exists, bool throw_if_exists)
{
chassert(ids.empty() || (multiple_entities.size() == ids.size()));
if (multiple_entities.empty())
return {};
if (multiple_entities.size() == 1)
{
UUID id;
if (!ids.empty())
id = ids[0];
else
id = generateRandomID();
if (insert(id, multiple_entities[0], replace_if_exists, throw_if_exists))
return {id};
return {};
}
std::vector<AccessEntityPtr> successfully_inserted;
try
{
std::vector<UUID> new_ids;
for (size_t i = 0; i < multiple_entities.size(); ++i)
{
const auto & entity = multiple_entities[i];
UUID id;
if (!ids.empty())
id = ids[i];
else
id = generateRandomID();
if (insert(id, entity, replace_if_exists, throw_if_exists))
{
successfully_inserted.push_back(entity);
new_ids.push_back(id);
}
}
return new_ids;
}
catch (Exception & e)
{
/// Try to add more information to the error message.
if (!successfully_inserted.empty())
{
String successfully_inserted_str;
for (const auto & entity : successfully_inserted)
{
if (!successfully_inserted_str.empty())
successfully_inserted_str += ", ";
successfully_inserted_str += entity->formatTypeWithName();
}
e.addMessage("After successfully inserting {}/{}: {}", successfully_inserted.size(), multiple_entities.size(), successfully_inserted_str);
}
throw;
}
}
std::optional<UUID> IAccessStorage::tryInsert(const AccessEntityPtr & entity)
{
return insert(entity, /* replace_if_exists = */ false, /* throw_if_exists = */ false);
}
std::vector<UUID> IAccessStorage::tryInsert(const std::vector<AccessEntityPtr> & multiple_entities)
{
return insert(multiple_entities, /* replace_if_exists = */ false, /* throw_if_exists = */ false);
}
UUID IAccessStorage::insertOrReplace(const AccessEntityPtr & entity)
{
return *insert(entity, /* replace_if_exists = */ true, /* throw_if_exists = */ false);
}
std::vector<UUID> IAccessStorage::insertOrReplace(const std::vector<AccessEntityPtr> & multiple_entities)
{
return insert(multiple_entities, /* replace_if_exists = */ true, /* throw_if_exists = */ false);
}
bool IAccessStorage::insertImpl(const UUID &, const AccessEntityPtr & entity, bool, bool, UUID *)
{
if (isReadOnly())
throwReadonlyCannotInsert(entity->getType(), entity->getName());
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "insertImpl is not implemented in {}", getStorageType());
}
bool IAccessStorage::remove(const UUID & id, bool throw_if_not_exists)
{
++remove_depth;
SCOPE_EXIT(--remove_depth);
bool removed = removeImpl(id, throw_if_not_exists);
if (removed && remove_depth == 1)
removeReferencesToRemovedIDs({id});
return removed;
}
std::vector<UUID> IAccessStorage::remove(const std::vector<UUID> & ids, bool throw_if_not_exists)
{
if (ids.empty())
return {};
if (ids.size() == 1)
return remove(ids[0], throw_if_not_exists) ? ids : std::vector<UUID>{};
++remove_depth;
SCOPE_EXIT(--remove_depth);
Strings removed_names;
std::vector<UUID> removed_ids;
try
{
std::vector<UUID> readonly_ids;
/// First we call removeImpl() for non-readonly entities. We bypass remove() here
/// to defer the dependency cleanup until after every entity has been removed —
/// otherwise we'd run the cascade once per id and waste work.
for (const auto & id : ids)
{
if (isReadOnly(id))
readonly_ids.push_back(id);
else
{
auto name = tryReadName(id);
if (removeImpl(id, throw_if_not_exists))
{
removed_ids.push_back(id);
if (name)
removed_names.push_back(std::move(name).value());
}
}
}
/// For readonly entities we're still going to call removeImpl() because
/// isReadOnly(id) could change and even if it's not then a storage-specific
/// implementation of removeImpl() will probably generate a better error message.
for (const auto & id : readonly_ids)
{
auto name = tryReadName(id);
if (removeImpl(id, throw_if_not_exists))
{
removed_ids.push_back(id);
if (name)
removed_names.push_back(std::move(name).value());
}
}
}
catch (Exception & e)
{
/// Even on failure, clean up references for the entities we did remove so the
/// access state on disk does not retain dangling UUIDs.
if (!removed_ids.empty() && remove_depth == 1)
{
std::unordered_set<UUID> removed_set(removed_ids.begin(), removed_ids.end());
removeReferencesToRemovedIDs(removed_set);
}
/// Try to add more information to the error message.
if (!removed_names.empty())
{
String removed_names_str;
for (const auto & name : removed_names)
{
if (!removed_names_str.empty())
removed_names_str += ", ";
removed_names_str += backQuote(name);
}
e.addMessage("After successfully removing {}/{}: {}", removed_names.size(), ids.size(), removed_names_str);
}
throw;
}
if (!removed_ids.empty() && remove_depth == 1)
{
std::unordered_set<UUID> removed_set(removed_ids.begin(), removed_ids.end());
removeReferencesToRemovedIDs(removed_set);
}
return removed_ids;
}
void IAccessStorage::removeReferencesToRemovedIDs(const std::unordered_set<UUID> & removed_ids)
{
if (removed_ids.empty())
return;
auto update_func = [&removed_ids](const AccessEntityPtr & old, const UUID &) -> AccessEntityPtr
{
auto new_entity = old->clone();
new_entity->removeDependencies(removed_ids);
return new_entity;
};
/// Any access entity type can reference any other (e.g. a user references roles, a
/// settings profile references roles/users, a row policy references roles/users, etc.),
/// so we walk every type. Iteration is O(N) where N is the total number of access
/// entities — typically small.
for (auto type : collections::range(AccessEntityType::MAX))
{
std::vector<UUID> dependent_ids;
try
{
dependent_ids = findAllImpl(type);
}
catch (...)
{
tryLogCurrentException(getLogger(), "while listing access entities for dependency cleanup");
continue;
}
for (const auto & dependent_id : dependent_ids)
{
/// An entity can never depend on itself in the relevant sense, and we just
/// removed entities in `removed_ids` — there is nothing to update for them.
if (removed_ids.contains(dependent_id))
continue;
try
{
auto entity = readImpl(dependent_id, /* throw_if_not_exists= */ false);
if (!entity)
continue;
if (!entity->hasDependencies(removed_ids))
continue;
/// `update()` will dispatch to the same storage that owns the entity,
/// so for `MultipleAccessStorage` this naturally crosses sub-storages.
/// `throw_if_not_exists=false` covers concurrent removals.
update(dependent_id, update_func, /* throw_if_not_exists= */ false);
}
catch (Exception & e)
{
/// A read-only sub-storage (e.g. `users.xml`) cannot be updated. That is
/// expected — its content is reloaded from the config so any references
/// will be reconciled on the next reload. Don't fail the whole cascade.
if (e.code() == ErrorCodes::ACCESS_STORAGE_READONLY)
continue;
tryLogCurrentException(getLogger(),
"while removing references to dropped access entities from " + outputID(dependent_id));
}
catch (...)
{
tryLogCurrentException(getLogger(),
"while removing references to dropped access entities from " + outputID(dependent_id));
}
}
}
}
bool IAccessStorage::tryRemove(const UUID & id)
{
return remove(id, /* throw_if_not_exists = */ false);
}
std::vector<UUID> IAccessStorage::tryRemove(const std::vector<UUID> & ids)
{
return remove(ids, /* throw_if_not_exists = */ false);
}
bool IAccessStorage::removeImpl(const UUID & id, bool throw_if_not_exists)
{
if (isReadOnly(id))
{
auto entity = read(id, throw_if_not_exists);
if (!entity)
return false;
throwReadonlyCannotRemove(entity->getType(), entity->getName());
}
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "removeImpl is not implemented in {}", getStorageType());
}
bool IAccessStorage::update(const UUID & id, const UpdateFunc & update_func, bool throw_if_not_exists)
{
return updateImpl(id, update_func, throw_if_not_exists);
}
std::vector<UUID> IAccessStorage::update(const std::vector<UUID> & ids, const UpdateFunc & update_func, bool throw_if_not_exists)
{
if (ids.empty())
return {};
if (ids.size() == 1)
return update(ids[0], update_func, throw_if_not_exists) ? ids : std::vector<UUID>{};
Strings names_of_updated;
try
{
std::vector<UUID> ids_of_updated;
std::vector<UUID> readonly_ids;
/// First we call update() for non-readonly entities.
for (const auto & id : ids)
{
if (isReadOnly(id))
readonly_ids.push_back(id);
else
{
auto name = tryReadName(id);
if (update(id, update_func, throw_if_not_exists))
{
ids_of_updated.push_back(id);
if (name)
names_of_updated.push_back(std::move(name).value());
}
}
}
/// For readonly entities we're still going to call update() because
/// isReadOnly(id) could change and even if it's not then a storage-specific
/// implementation of updateImpl() will probably generate a better error message.
for (const auto & id : readonly_ids)
{
auto name = tryReadName(id);
if (update(id, update_func, throw_if_not_exists))
{
ids_of_updated.push_back(id);
if (name)
names_of_updated.push_back(std::move(name).value());
}
}
return ids_of_updated;
}
catch (Exception & e)
{
/// Try to add more information to the error message.
if (!names_of_updated.empty())
{
String names_of_updated_str;
for (const auto & name : names_of_updated)
{
if (!names_of_updated_str.empty())
names_of_updated_str += ", ";
names_of_updated_str += backQuote(name);
}
e.addMessage("After successfully updating {}/{}: {}", names_of_updated.size(), ids.size(), names_of_updated_str);
}
throw;
}
}
bool IAccessStorage::tryUpdate(const UUID & id, const UpdateFunc & update_func)
{
return update(id, update_func, /* throw_if_not_exists = */ false);
}
std::vector<UUID> IAccessStorage::tryUpdate(const std::vector<UUID> & ids, const UpdateFunc & update_func)
{
return update(ids, update_func, /* throw_if_not_exists = */ false);
}
bool IAccessStorage::updateImpl(const UUID & id, const UpdateFunc &, bool throw_if_not_exists)
{
if (isReadOnly(id))
{
auto entity = read(id, throw_if_not_exists);
if (!entity)
return false;
throwReadonlyCannotUpdate(entity->getType(), entity->getName());
}
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "updateImpl is not implemented in {}", getStorageType());
}
AuthResult IAccessStorage::authenticate(
const Credentials & credentials,
const Poco::Net::IPAddress & address,
const ExternalAuthenticators & external_authenticators,
const ClientInfo & client_info,
bool allow_no_password,
bool allow_plaintext_password) const
{
return *authenticateImpl(credentials, address, external_authenticators, client_info, /* throw_if_user_not_exists = */ true, allow_no_password, allow_plaintext_password);
}
std::optional<AuthResult> IAccessStorage::authenticate(
const Credentials & credentials,
const Poco::Net::IPAddress & address,
const ExternalAuthenticators & external_authenticators,
const ClientInfo & client_info,
bool throw_if_user_not_exists,
bool allow_no_password,
bool allow_plaintext_password) const
{
return authenticateImpl(credentials, address, external_authenticators, client_info, throw_if_user_not_exists, allow_no_password, allow_plaintext_password);
}
/// `check_valid_until = false` answers "does this credential match this method?" without the expiry gate.
/// The fail-close ambiguity scan below needs that: an already-expired matching method must still shorten
/// the combined `VALID UNTIL` of the session instead of silently disappearing from the combination.
Authentication::CredentialsCheckResult areCredentialsValid(
const std::string & user_name,
const AuthenticationData & authentication_method,
const Credentials & credentials,
const ExternalAuthenticators & external_authenticators,
const ClientInfo & client_info,
SettingsChanges & settings,
bool check_valid_until = true);
/// A `NO_PASSWORD` or `PLAINTEXT_PASSWORD` method is ignored entirely when the corresponding server setting disables it
/// (`allow_no_password` / `allow_plaintext_password`). Both the primary authentication loop and the fail-close ambiguity
/// scan below must apply this gate, otherwise a disabled method could still narrow the `GRANTS` or shorten the
/// `VALID UNTIL` of an allowed login, contradicting the "skip this authentication type entirely" contract.
static bool authenticationTypeIsAllowed(AuthenticationType type, bool allow_no_password, bool allow_plaintext_password)
{
if (type == AuthenticationType::NO_PASSWORD)
return allow_no_password;
if (type == AuthenticationType::PLAINTEXT_PASSWORD)
return allow_plaintext_password;
return true;
}
std::optional<AuthResult> IAccessStorage::authenticateImpl(
const Credentials & credentials,
const Poco::Net::IPAddress & address,
const ExternalAuthenticators & external_authenticators,
const ClientInfo & client_info,
bool throw_if_user_not_exists,
bool allow_no_password,
bool allow_plaintext_password) const
{
if (auto id = find<User>(credentials.getUserName()))
{
if (auto user = tryRead<User>(*id))
{
AuthResult auth_result { .user_id = *id, .user_name = credentials.getUserName() };
if (!isAddressAllowed(*user, address))
throwAddressNotAllowed(address);
bool skipped_not_allowed_authentication_methods = false;
bool need_second_factor = false;
const AuthenticationData * matched_authentication_method = nullptr;
for (const auto & auth_method : user->authentication_methods)
{
auto auth_type = auth_method.getType();
if (!authenticationTypeIsAllowed(auth_type, allow_no_password, allow_plaintext_password))
{
skipped_not_allowed_authentication_methods = true;
continue;
}
auto cred_check_result = areCredentialsValid(user->getName(), auth_method, credentials, external_authenticators, client_info, auth_result.settings);
if (cred_check_result == Authentication::CredentialsCheckResult::Success)
{
matched_authentication_method = &auth_method;
break;
}
if (cred_check_result == Authentication::CredentialsCheckResult::NeedSecondFactor)
need_second_factor = true;
}
if (matched_authentication_method)
{
/// `AlwaysAllowCredentials` are used only after an internal caller has authenticated the user, for
/// example with an interserver secret. They do not identify any particular authentication method, so
/// applying one method's `GRANTS` or `VALID UNTIL` here would incorrectly make those method-specific
/// limits affect the internal connection. Preserve the matched method's type for session logging.
if (typeid_cast<const AlwaysAllowCredentials *>(&credentials))
{
auth_result.authentication_data = *matched_authentication_method;
auth_result.authentication_data.setGrants({});
auth_result.authentication_data.setValidUntil(0);
return auth_result;
}
auth_result.authentication_data = *matched_authentication_method;
/// Fail-close against ambiguous credentials. Authentication returns the first matching method, but the
/// same effective credential can be accepted by more than one method (for example `IDENTIFIED BY 'p', BY 'p'`
/// stores two `sha256_password` methods with different random salts). If a broader or earlier method could
/// shadow a later token-style method, a limited credential would silently regain the full rights (or lifetime)
/// of the other method. To prevent that, the session is limited to the intersection of the `GRANTS` of all
/// matching methods and expires at the earliest of their `VALID UNTIL`. The scan matches credentials
/// while ignoring expiry: an already-expired method that accepts the credential must still shorten the
/// combined `VALID UNTIL` (rejecting the login below), otherwise the expiry of a token method would
/// silently hand the shared credential the rights and lifetime of the broader method.
///
/// Methods that neither restrict the grants nor set an expiry cannot narrow anything and are skipped without
/// an extra credential check. Methods verified against an external system (`LDAP`/`KERBEROS`/`HTTP`/`JWT`) are
/// also skipped, so authentication never performs an extra external probe here: a probe with the same credential
/// could fail against a different server and, for example, trip an account lockout there. This skip cannot lose
/// a `GRANTS` narrowing, because a `GRANTS` clause on an externally verified method is rejected at creation
/// (see `AuthenticationData::fromAST`); it can only lose a `VALID UNTIL` of such a method, matching the
/// pre-existing first-match behavior of per-method `VALID UNTIL`.
std::optional<AccessRights> combined_grants;
if (!matched_authentication_method->getGrants().structurallyEmpty())
combined_grants.emplace(matched_authentication_method->getGrants());
bool another_method_restricts_grants = false;
time_t combined_valid_until = matched_authentication_method->getValidUntil();
for (const auto & other_method : user->authentication_methods)
{
if (&other_method == matched_authentication_method)
continue;
/// A method disabled by `allow_no_password` / `allow_plaintext_password` must be ignored here too,
/// exactly as in the primary loop above; otherwise it could narrow or expire an otherwise allowed login.
if (!authenticationTypeIsAllowed(other_method.getType(), allow_no_password, allow_plaintext_password))
continue;
const bool restricts_grants = !other_method.getGrants().structurallyEmpty();
const time_t other_valid_until = other_method.getValidUntil();
if (!restricts_grants && other_valid_until == 0)
continue;
if (!authenticationTypeIsVerifiedLocally(other_method.getType()))
continue;
SettingsChanges discarded_settings;
if (areCredentialsValid(user->getName(), other_method, credentials, external_authenticators, client_info, discarded_settings, /* check_valid_until = */ false)
!= Authentication::CredentialsCheckResult::Success)
continue;
if (restricts_grants)
{
another_method_restricts_grants = true;
AccessRights other_grants{other_method.getGrants()};
if (combined_grants)
combined_grants->makeIntersection(other_grants);
else
combined_grants.emplace(std::move(other_grants));
}
if (other_valid_until != 0 && (combined_valid_until == 0 || other_valid_until < combined_valid_until))
combined_valid_until = other_valid_until;
}
/// The earliest `VALID UNTIL` among the matching methods wins even when it has already passed:
/// the shared credential is expired as a whole, exactly as if the single matched method had expired.
if (combined_valid_until != 0)
{
const time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
if (now > combined_valid_until)
throw Exception(ErrorCodes::WRONG_PASSWORD, "Invalid credentials");
}
if (another_method_restricts_grants)
{
AccessRightsElements limited = combined_grants->getElements();
if (limited.structurallyEmpty())
limited.emplace_back(); /// Empty intersection means deny all (`USAGE ON *.*`), not "no limit".
auth_result.authentication_data.setGrants(std::move(limited));
}
if (combined_valid_until != matched_authentication_method->getValidUntil())
auth_result.authentication_data.setValidUntil(combined_valid_until);
return auth_result;
}
if (skipped_not_allowed_authentication_methods)
{
LOG_INFO(getLogger(), "Skipped the check for not allowed authentication methods,"
"check allow_no_password and allow_plaintext_password settings in the server configuration");
}
if (need_second_factor)
throw Exception(ErrorCodes::REQUIRED_SECOND_FACTOR, "Authentication requires second factor");
throw Exception(ErrorCodes::WRONG_PASSWORD, "Invalid credentials");
}
}
if (throw_if_user_not_exists)
throwNotFound(AccessEntityType::USER, credentials.getUserName(), storage_name);
else
return std::nullopt;
}
Authentication::CredentialsCheckResult areCredentialsValid(
const std::string & user_name,
const AuthenticationData & authentication_method,
const Credentials & credentials,
const ExternalAuthenticators & external_authenticators,
const ClientInfo & client_info,
SettingsChanges & settings,
bool check_valid_until)
{
if (!credentials.isReady())
return Authentication::CredentialsCheckResult::Fail;
if (credentials.getUserName() != user_name)
return Authentication::CredentialsCheckResult::Fail;
if (check_valid_until)
{
auto valid_until = authentication_method.getValidUntil();
if (valid_until)
{
const time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
if (now > valid_until)
return Authentication::CredentialsCheckResult::Fail;
}
}
return Authentication::areCredentialsValid(credentials, authentication_method, external_authenticators, client_info, settings);
}
bool IAccessStorage::isAddressAllowed(const User & user, const Poco::Net::IPAddress & address) const
{
return user.allowed_client_hosts.contains(address);
}
void IAccessStorage::backup(BackupEntriesCollector & backup_entries_collector, const String & data_path_in_backup, AccessEntityType type) const
{
if (!isBackupAllowed())
throwBackupNotAllowed();
auto entities_ids = findAll(type);
if (entities_ids.empty())
return;
auto backup_entry_with_path = makeBackupEntryForAccessEntities(
entities_ids,
backup_entries_collector.getAllAccessEntities(),
backup_entries_collector.getBackupSettings().write_access_entities_dependents,
data_path_in_backup);
if (isReplicated())
{
auto backup_coordination = backup_entries_collector.getBackupCoordination();
auto replication_id = getReplicationID();
backup_coordination->addReplicatedAccessFilePath(replication_id, type, backup_entry_with_path.first);
backup_entries_collector.addPostTask(
[backup_entry = backup_entry_with_path.second,
replication_id,
type,
&backup_entries_collector,
backup_coordination]
{
for (const String & path : backup_coordination->getReplicatedAccessFilePaths(replication_id, type))
backup_entries_collector.addBackupEntry(path, backup_entry);
});
}
else
{
backup_entries_collector.addBackupEntry(backup_entry_with_path);
}
}
void IAccessStorage::restoreFromBackup(RestorerFromBackup & restorer, const String & data_path_in_backup)
{
if (!isRestoreAllowed())
throwRestoreNotAllowed();
if (isReplicated())
{
auto restore_coordination = restorer.getRestoreCoordination();
if (!restore_coordination->acquireReplicatedAccessStorage(getReplicationID()))
return;
}
restorer.addDataRestoreTask(
[this, &restorer, data_path_in_backup]
{
auto entities_to_restore = restorer.getAccessEntitiesToRestore(data_path_in_backup);
const auto & restore_settings = restorer.getRestoreSettings();
restoreAccessEntitiesFromBackup(*this, entities_to_restore, restore_settings);
});
}
UUID IAccessStorage::generateRandomID()
{
static Poco::UUIDGenerator generator;
UUID id;
generator.createRandom().copyTo(reinterpret_cast<char *>(&id));
return id;
}
void IAccessStorage::clearConflictsInEntitiesList(std::vector<std::pair<UUID, AccessEntityPtr>> & entities, LoggerPtr log_)
{
std::unordered_map<UUID, size_t> positions_by_id;
std::unordered_map<std::string_view, size_t> positions_by_type_and_name[static_cast<size_t>(AccessEntityType::MAX)];
std::vector<size_t> positions_to_remove;
for (size_t pos = 0; pos != entities.size(); ++pos)
{
const auto & [id, entity] = entities[pos];
if (auto it = positions_by_id.find(id); it == positions_by_id.end())
{
positions_by_id[id] = pos;
}
else if (it->second != pos)
{
/// Conflict: same ID is used for multiple entities. We will ignore them.
positions_to_remove.emplace_back(pos);
positions_to_remove.emplace_back(it->second);
}
std::string_view entity_name = entity->getName();
auto & positions_by_name = positions_by_type_and_name[static_cast<size_t>(entity->getType())];
if (auto it = positions_by_name.find(entity_name); it == positions_by_name.end())
{
positions_by_name[entity_name] = pos;
}
else if (it->second != pos)
{
/// Conflict: same name and type are used for multiple entities. We will ignore them.
positions_to_remove.emplace_back(pos);
positions_to_remove.emplace_back(it->second);
}
}
if (positions_to_remove.empty())
return;
std::sort(positions_to_remove.begin(), positions_to_remove.end());
positions_to_remove.erase(std::unique(positions_to_remove.begin(), positions_to_remove.end()), positions_to_remove.end());
for (size_t pos : positions_to_remove)
{
LOG_WARNING(
log_,
"Skipping {} (id={}) due to conflicts with other access entities",
entities[pos].second->formatTypeWithName(),
toString(entities[pos].first));
}
/// Remove conflicting entities.
for (size_t pos : positions_to_remove | boost::adaptors::reversed) /// Must remove in reversive order.
entities.erase(entities.begin() + pos);
}
LoggerPtr IAccessStorage::getLogger() const
{
callOnce(log_initialized, [&] {
log = ::getLogger("Access(" + storage_name + ")");
});
return log;
}
void IAccessStorage::throwNotFound(const UUID & id, const String & storage_name)
{
throw Exception(ErrorCodes::ACCESS_ENTITY_NOT_FOUND, "{} not found in {}", outputID(id), backQuote(storage_name));
}
void IAccessStorage::throwNotFound(AccessEntityType type, const String & name, const String & storage_name)
{
int error_code = AccessEntityTypeInfo::get(type).not_found_error_code;
throw Exception(error_code, "There is no {} in {}", formatEntityTypeWithName(type, name), backQuote(storage_name));
}
void IAccessStorage::throwBadCast(const UUID & id, AccessEntityType type, const String & name, AccessEntityType required_type)
{
throw Exception(ErrorCodes::LOGICAL_ERROR, "{}: {} expected to be of type {}", outputID(id),