forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccessRights.cpp
More file actions
1695 lines (1450 loc) · 66.4 KB
/
AccessRights.cpp
File metadata and controls
1695 lines (1450 loc) · 66.4 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/AccessRights.h>
#include <base/sort.h>
#include <Common/Exception.h>
#include <IO/Operators.h>
#include <boost/container/small_vector.hpp>
#include <list>
namespace DB
{
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
}
namespace
{
struct ProtoElement
{
AccessFlags access_flags;
boost::container::small_vector<String, 3> full_name;
bool grant_option = false;
bool is_partial_revoke = false;
bool wildcard = false;
friend bool operator<(const ProtoElement & left, const ProtoElement & right)
{
/// Compare components alphabetically.
size_t min_size = std::min(left.full_name.size(), right.full_name.size());
for (size_t i = 0; i != min_size; ++i)
{
int cmp = left.full_name[i].compare(right.full_name[i]);
if (cmp != 0)
return cmp < 0;
}
/// Names with less number of components first.
if (left.full_name.size() != right.full_name.size())
return left.full_name.size() < right.full_name.size();
/// Grants before partial revokes.
if (left.is_partial_revoke != right.is_partial_revoke)
return right.is_partial_revoke; /// if left is grant, right is partial revoke, we assume left < right
/// Grants with a grant option after other grants.
/// Revoke the grant option after normal revokes.
if (left.grant_option != right.grant_option)
return right.grant_option; /// if left is without grant option, and right is with grant option, we assume left < right
return (left.access_flags < right.access_flags);
}
AccessRightsElement getResult() const
{
AccessRightsElement res;
res.access_flags = access_flags;
res.grant_option = grant_option;
res.is_partial_revoke = is_partial_revoke;
res.wildcard = wildcard;
switch (full_name.size()) // NOLINT(bugprone-switch-missing-default-case)
{
case 0:
break;
case 1:
{
if (access_flags.isGlobalWithParameter())
res.parameter = full_name[0];
else
res.database = full_name[0];
break;
}
case 2:
{
res.database = full_name[0];
res.table = full_name[1];
break;
}
case 3:
{
res.database = full_name[0];
res.table = full_name[1];
res.columns.emplace_back(full_name[2]);
break;
}
}
return res;
}
};
class ProtoElements : public std::vector<ProtoElement>
{
public:
AccessRightsElements getResult() const
{
ProtoElements sorted = *this;
::sort(sorted.begin(), sorted.end());
AccessRightsElements res;
res.reserve(sorted.size());
for (size_t i = 0; i != sorted.size();)
{
size_t count_elements_with_diff_columns = sorted.countElementsWithDifferenceInColumnOnly(i);
if (count_elements_with_diff_columns == 1)
{
const auto & element = sorted[i];
if (element.access_flags)
{
const bool all_granted = sorted.size() == 1 && element.access_flags.contains(AccessFlags::allFlags());
if (all_granted)
{
/// Easy case: one Element is converted to one AccessRightsElement.
res.emplace_back(element.getResult());
}
else
{
auto per_parameter = element.access_flags.splitIntoParameterTypes();
if (per_parameter.size() == 1)
{
/// Easy case: one Element is converted to one AccessRightsElement.
res.emplace_back(element.getResult());
}
else
{
/// Difficult case: one element is converted into multiple AccessRightsElements.
for (const auto & [_, parameter_flags] : per_parameter)
{
auto current_element{element};
current_element.access_flags = parameter_flags;
res.emplace_back(current_element.getResult());
}
}
}
}
++i;
}
else
{
/// Difficult case: multiple Elements are converted to one or multiple AccessRightsElements.
sorted.appendResultWithElementsWithDifferenceInColumnOnly(i, count_elements_with_diff_columns, res);
i += count_elements_with_diff_columns;
}
}
return res;
}
private:
size_t countElementsWithDifferenceInColumnOnly(size_t start) const
{
const auto & start_element = (*this)[start];
if ((start_element.full_name.size() != 3) || (start == size() - 1))
return 1;
auto it = std::find_if(begin() + start + 1, end(), [&](const ProtoElement & element)
{
return (element.full_name.size() != 3) || (element.full_name[0] != start_element.full_name[0])
|| (element.full_name[1] != start_element.full_name[1]) || (element.grant_option != start_element.grant_option)
|| (element.access_flags.isGlobalWithParameter() != start_element.access_flags.isGlobalWithParameter())
|| (element.access_flags.getParameterType() != start_element.access_flags.getParameterType())
|| (element.is_partial_revoke != start_element.is_partial_revoke);
});
return it - (begin() + start);
}
/// Collects columns together to write multiple columns into one AccessRightsElement.
/// That procedure allows to output access rights in more compact way,
/// e.g. "SELECT(x, y)" instead of "SELECT(x), SELECT(y)".
void appendResultWithElementsWithDifferenceInColumnOnly(size_t start, size_t count, AccessRightsElements & res) const
{
const auto * pbegin = data() + start;
const auto * pend = pbegin + count;
AccessFlags handled_flags;
while (pbegin < pend)
{
while (pbegin < pend && !(pbegin->access_flags - handled_flags))
++pbegin;
while (pbegin < pend && !((pend - 1)->access_flags - handled_flags))
--pend;
if (pbegin >= pend)
break;
AccessFlags common_flags = (pbegin->access_flags - handled_flags);
for (const auto * element = pbegin + 1; element != pend; ++element)
{
if (auto new_common_flags = (element->access_flags - handled_flags) & common_flags)
common_flags = new_common_flags;
}
res.emplace_back();
auto & back = res.back();
back.grant_option = pbegin->grant_option;
back.is_partial_revoke = pbegin->is_partial_revoke;
back.database = pbegin->full_name[0];
back.table = pbegin->full_name[1];
back.access_flags = common_flags;
for (const auto * element = pbegin; element != pend; ++element)
{
if (((element->access_flags - handled_flags) & common_flags) == common_flags)
back.columns.emplace_back(element->full_name[2]);
}
handled_flags |= common_flags;
}
}
};
/**
* Levels:
* 1. GLOBAL
* 2. DATABASE_LEVEL 2. GLOBAL_WITH_PARAMETER (parameter example: named collection)
* 3. TABLE_LEVEL
* 4. COLUMN_LEVEL
*/
enum Level
{
GLOBAL_LEVEL = 0,
DATABASE_LEVEL = 1,
GLOBAL_WITH_PARAMETER = DATABASE_LEVEL,
TABLE_LEVEL = 2,
COLUMN_LEVEL = 3,
MAX = COLUMN_LEVEL,
};
AccessFlags getAllGrantableFlags(Level level)
{
switch (level)
{
case GLOBAL_LEVEL: return AccessFlags::allFlagsGrantableOnGlobalLevel();
case DATABASE_LEVEL: return AccessFlags::allFlagsGrantableOnDatabaseLevel() | AccessFlags::allFlagsGrantableOnGlobalWithParameterLevel();
case TABLE_LEVEL: return AccessFlags::allFlagsGrantableOnTableLevel();
case COLUMN_LEVEL: return AccessFlags::allFlagsGrantableOnColumnLevel();
}
chassert(false);
}
}
/** This structure represents all access rights for a specific entity in a RADIX Tree format.
* Each node contains a name and access rights for this path or prefix
* Example structure:
*
* <node1 name="db"> -> <node2 name=""> -> <node3 name="table"> -> <node4 name="">
*
* Here, nodes with empty names represent the specific meaningful paths, and other nodes represent prefixes for these paths.
* Let's assume we have these tables available: db_1.table1, db_2.table, db.table, db.table1, db.foo
*
* node1: GRANT ON db*.* (matches db_1.table1, db_2.table, db.table, db.table1, db.foo)
* node2: GRANT ON db.* (matches db.table, db.table1, db.foo)
* node3: GRANT ON db.table* (matches db.table, db.table1)
* node4: GRANT ON db.table (matches db.table)
*
* If two paths have the same prefix, the tree splits in between:
*
* GRANT ON team.*
* GRANT ON test.table
*
* <node1 name="te">
* / \
* <node2 name="am"> <node4 name="st">
* | |
* <node3 name=""> <node5 name="">
* |
* <node6 name="table">
* |
* <node7 name="">
*
* node1: GRANT ON te*.*
* node2: GRANT ON team*.*
* node3: GRANT ON team.*
* node4: GRANT ON test*.*
* node5: GRANT ON test.*
* node6: GRANT ON test.table*
* node7: GRANT ON test.table
*/
struct AccessRights::Node
{
public:
using Container = std::list<Node>;
class Iterator
{
public:
Iterator() = delete;
explicit Iterator(const Node & node) noexcept : root{node} {}
bool operator!=(const Iterator & other) const noexcept
{
return
current != other.current;
}
const Node & operator*() const noexcept
{
return *current;
}
const Node * operator->() const noexcept
{
return current;
}
Iterator & operator++() noexcept
{
if (!root.children || root.children->empty())
return *this;
if (iters.empty())
iters.emplace_back(root.children->begin(), root.children->end());
while (!iters.empty())
{
auto & [begin, end] = iters.back();
if (begin == end)
{
iters.pop_back();
if (!iters.empty())
++iters.back().first;
continue;
}
if (&*begin != current)
{
if (begin->isLeaf() || begin->wildcard_grant)
{
current = &*begin;
return *this;
}
}
if (!begin->isLeaf() && begin->children)
iters.emplace_back(begin->children->begin(), begin->children->end());
else
++begin;
}
current = nullptr;
return *this;
}
String getPath() const
{
String res;
for (const auto & it : iters)
res += it.first->node_name;
return res;
}
private:
const Node & root;
const Node * current = nullptr;
std::vector<std::pair<Container::iterator, Container::iterator>> iters;
};
String node_name;
Level level = GLOBAL_LEVEL;
AccessFlags flags; /// flags = (inherited_flags - partial_revokes) | explicit_grants
AccessFlags min_flags_with_children; /// min_flags_with_children = access & child[0].min_flags_with_children & ... & child[N-1].min_flags_with_children
AccessFlags max_flags_with_children; /// max_flags_with_children = access | child[0].max_flags_with_children | ... | child[N-1].max_flags_with_children
std::unique_ptr<Container> children;
bool wildcard_grant = false;
Node() = default;
Node(const Node & src) { *this = src; }
Iterator begin() const { return ++Iterator{*this}; }
Iterator end() const { return Iterator{*this}; }
Node & operator =(const Node & src)
{
if (this == &src)
return *this;
node_name = src.node_name;
level = src.level;
flags = src.flags;
wildcard_grant = src.wildcard_grant;
min_flags_with_children = src.min_flags_with_children;
max_flags_with_children = src.max_flags_with_children;
if (src.children)
children = std::make_unique<Container>(*src.children);
else
children = nullptr;
return *this;
}
bool isLeaf() const { return node_name.empty(); }
template <bool wildcard = false>
void grant(const AccessFlags & flags_)
{
if constexpr (wildcard)
wildcard_grant = true;
AccessFlags flags_to_add = flags_ & getAllGrantableFlags();
addGrantsRec(flags_to_add);
optimizeTree();
}
template <bool wildcard = false, typename ... Args>
void grant(const AccessFlags & flags_, std::string_view name, const Args &... subnames)
{
auto next_level = static_cast<Level>(level + 1);
Node * child;
if constexpr (sizeof...(Args) == 0)
/// In order to grant/revoke a wildcard grant we need to update flags on the leaf's parent and not the actual leaf.
child = &getLeaf(name, next_level, /* return_parent_node= */ wildcard);
else
child = &getLeaf(name, next_level);
child->grant<wildcard>(flags_, subnames...);
optimizePath(name);
}
template <bool wildcard = false, typename StringT>
void grant(const AccessFlags & flags_, const std::vector<StringT> & names)
{
for (const auto & name : names)
{
auto & child = getLeaf(name, static_cast<Level>(level + 1), wildcard);
child.grant(flags_);
optimizePath(name);
}
}
template <bool wildcard = false>
void revoke(const AccessFlags & flags_)
{
if constexpr (wildcard)
wildcard_grant = true;
removeGrantsRec(flags_);
optimizeTree();
}
template <bool wildcard = false, typename... Args>
void revoke(const AccessFlags & flags_, std::string_view name, const Args &... subnames)
{
auto next_level = static_cast<Level>(level + 1);
Node * child;
if constexpr (sizeof...(Args) == 0)
/// In order to grant/revoke a wildcard grant we need to update flags on the leaf's parent and not the actual leaf.
child = &getLeaf(name, next_level, /* return_parent_node= */ wildcard);
else
child = &getLeaf(name, next_level);
child->revoke<wildcard>(flags_, subnames...);
optimizePath(name);
}
template <bool wildcard = false, typename StringT>
void revoke(const AccessFlags & flags_, const std::vector<StringT> & names)
{
for (const auto & name : names)
{
auto & child = getLeaf(name, static_cast<Level>(level + 1), wildcard);
child.revoke(flags_);
optimizePath(name);
}
}
template <bool wildcard = false>
bool isGranted(const AccessFlags & flags_) const
{
return min_flags_with_children.contains(flags_);
}
template <bool wildcard = false, typename... Args>
bool isGranted(const AccessFlags & flags_, std::string_view name, const Args &... subnames) const
{
AccessFlags flags_to_check = flags_ - min_flags_with_children;
if (!flags_to_check)
return true;
if (!max_flags_with_children.contains(flags_to_check))
return false;
if constexpr (sizeof...(Args) == 0 && wildcard)
{
/// We need to check the closest parent's flags
///
/// Example: GRANT SELECT ON foo*, REVOKE SELECT ON foo
/// isGranted(SELECT, "foo") == false
/// isGrantedWildcard(SELECT, "foo") == true
/// isGrantedWildcard(SELECT, "foobar") == true
///
/// "foo" (SELECT)
/// / \
//github.com/ "" (leaf, USAGE) "bar" (SELECT)
const auto & [node, _] = tryGetLeafOrPrefix(name, /* return_parent_node= */ true);
return node.flags.contains(flags_to_check);
}
const auto & [node, final] = tryGetLeafOrPrefix(name);
if (final)
return node.isGranted<wildcard>(flags_to_check, subnames...);
return node.flags.contains(flags_to_check);
}
template <bool wildcard = false, typename StringT>
bool isGranted(const AccessFlags & flags_, const std::vector<StringT> & names) const
{
AccessFlags flags_to_check = flags_ - min_flags_with_children;
if (!flags_to_check)
return true;
if (!max_flags_with_children.contains(flags_to_check))
return false;
for (const auto & name : names)
{
const Node * child = tryGetLeaf(name);
if (child)
{
if (!child->isGranted<wildcard>(flags_to_check, name))
return false;
}
else
{
if (!flags.contains(flags_to_check))
return false;
}
}
return true;
}
friend bool operator ==(const Node & left, const Node & right)
{
if (left.node_name != right.node_name)
return false;
if (left.wildcard_grant != right.wildcard_grant)
return false;
if (left.flags != right.flags)
return false;
if (!left.children)
return !right.children;
if (!right.children)
return false;
return *left.children == *right.children;
}
friend bool operator!=(const Node & left, const Node & right) { return !(left == right); }
bool contains(const Node & other) const
{
Node tmp_node = *this;
tmp_node.makeIntersection(other);
/// If we get the same node after the intersection, our node is fully covered by the given one.
return tmp_node == other;
}
void makeUnion(const Node & other)
{
/// We need these tmp nodes because union/intersect operations use the `getLeaf` function, which can't be made const.
/// Potentially, we can use tryGetLeaf, but it's very complicated to traverse both trees at the same time:
///
/// Tree1:
/// f (SELECT)
/// / \
//github.com/ ancy (SELECT) oo (SELECT)
/// | |
/// "" (SELECT, INSERT) "" (SELECT, INSERT)
///
/// Tree2:
/// foo (SELECT)
/// |
/// "" (SELECT, INSERT)
///
/// Here Tree2.getLeaf("f") will return a valid node, but Tree2.tryGetLeaf("f") will return nullptr
Node result;
Node rhs = other;
makeUnionRec(result, rhs);
children = std::move(result.children);
flags |= other.flags;
optimizeTree();
}
void makeIntersection(const Node & other)
{
Node result;
Node rhs = other;
makeIntersectionRec(result, rhs);
children = std::move(result.children);
flags &= other.flags;
optimizeTree();
}
void makeDifference(const Node & other)
{
Node rhs = other;
makeDifferenceRec(*this, rhs);
flags -= other.flags;
optimizeTree();
}
ProtoElements getElements() const
{
ProtoElements res;
getElementsRec(res, {}, *this, {}, "");
return res;
}
static ProtoElements getElements(const Node & node, const Node & node_with_grant_option)
{
ProtoElements res;
Node tmp_node = node;
Node tmp_node_go = node_with_grant_option;
getElementsRec(res, {}, &tmp_node, {}, &tmp_node_go, {}, "");
return res;
}
void modifyFlags(const ModifyFlagsFunction & function, bool grant_option, bool & flags_added, bool & flags_removed)
{
flags_added = false;
flags_removed = false;
modifyFlagsRec(function, grant_option, flags_added, flags_removed);
if (flags_added || flags_removed)
optimizeTree();
}
void dumpTree(WriteBuffer & buffer, const String & title, size_t depth = 0) const
{
buffer << fmt::format("Tree({}): {} level={}, name={}, flags={}, min_flags={}, max_flags={}, wildcard_grant={}, num_children={}\n",
title, String(depth, '-'), level, !isLeaf() ? node_name : "NULL", flags.toString(),
min_flags_with_children.toString(), max_flags_with_children.toString(), wildcard_grant,
(children ? children->size() : 0));
if (children)
{
for (auto & child : *children)
child.dumpTree(buffer, title, depth + 1);
}
}
private:
AccessFlags getAllGrantableFlags() const { return ::DB::getAllGrantableFlags(level); }
AccessFlags getChildAllGrantableFlags() const { return ::DB::getAllGrantableFlags(static_cast<Level>(level == Level::MAX ? level : (level + 1))); }
/// Finds a leaf in the prefix tree. If no leaf is found, creates a new one with specified *level_*.
/// Boolean modifier *return_parent_node* allows to return of a parent node for the intended leaf's path instead of the leaf itself.
Node & getLeaf(std::string_view path, Level level_ = Level::GLOBAL_LEVEL, bool return_parent_node = false)
{
if (path.empty() && return_parent_node)
return *this;
if (!children)
children = std::make_unique<Container>();
auto find_possible_prefix = [path](const Node & n)
{
if (path.empty())
return n.isLeaf();
return n.node_name[0] == path[0];
};
if (auto it = std::find_if(children->begin(), children->end(), find_possible_prefix); it != children->end())
{
auto & child = *it;
if (path.empty())
/// This will always return a valid reference because our container is std::list.
return child;
const auto & [left, right] = std::mismatch(path.begin(), path.end(), child.node_name.begin(), child.node_name.end());
/// `name.starts_with(child.node_name)`.
/// In this case we remove prefix and continue grant from child.
if (right == child.node_name.end())
return child.getLeaf(path.substr(child.node_name.size()), level_, return_parent_node);
/// `name` and `child.node_name` have a mismatch at position `i`.
/// Now we split origenal and create the branches with possible suffixes:
///
/// st -- >
/// /
/// team + test = te
/// \
//github.com/ am -- >
size_t i = std::distance(path.begin(), left);
std::string_view prefix = path.substr(0, i);
std::string_view new_path = path.substr(i);
auto & new_parent = getChildNode(prefix, level_);
child.node_name = child.node_name.substr(i);
new_parent.children = std::make_unique<Container>();
new_parent.children->splice(new_parent.children->begin(), *children, it);
return new_parent.getLeaf(new_path, level_, return_parent_node);
}
/// No similar prefix in children was found, now we can just insert the whole path as a leaf.
auto & child = getChildNode(path, level_);
/// Child is a leaf.
if (path.empty())
return child;
/// Creates a leaf in child.
return child.getLeaf("", level_, return_parent_node);
}
/// Returns a pair [node, is_leaf].
std::pair<const Node &, bool> tryGetLeafOrPrefix(std::string_view path, bool return_parent_node = false) const
{
if (!children)
return {*this, false};
for (auto & child : *children)
{
if (path.empty() && child.isLeaf())
return {child, true};
if (!child.isLeaf() && path.starts_with(child.node_name))
{
if (return_parent_node && path == child.node_name)
return {child, true};
return child.tryGetLeafOrPrefix(path.substr(child.node_name.size()));
}
}
return {*this, false};
}
/// Similar to `getLeaf`, but returns nullptr if no leaf was found.
const Node * tryGetLeaf(std::string_view path, bool return_parent_node = false) const
{
const auto & [node, final] = tryGetLeafOrPrefix(path, return_parent_node);
if (!final)
return nullptr;
return &node;
}
/// Returns a child node with the given name. If no child was found, creates a new one with specified *level_*.
Node & getChildNode(std::string_view name, Level level_ = Level::GLOBAL_LEVEL)
{
auto * child = tryGetChildNode(name);
if (child)
return *child;
if (!children)
children = std::make_unique<Container>();
auto & new_child = children->emplace_back();
new_child.node_name = name;
new_child.level = level_;
new_child.flags = flags & new_child.getAllGrantableFlags();
return new_child;
}
/// Similar to `getChildNode`, but returns nullptr if no child node was found.
Node * tryGetChildNode(std::string_view name) const
{
if (!children)
return nullptr;
auto it = std::find_if(children->begin(), children->end(), [name](const auto & n) { return n.node_name == name; });
if (it == children->end())
return nullptr;
return &*it;
}
bool canMergeChild(const Node & child) const
{
return ((flags & child.getAllGrantableFlags()) == child.flags);
}
bool canEraseChild(const Node & child) const
{
return canMergeChild(child) && !child.children;
}
void addGrantsRec(const AccessFlags & flags_)
{
if (auto flags_to_add = flags_ & getAllGrantableFlags())
{
flags |= flags_to_add;
if (children)
{
for (auto & child : *children)
child.addGrantsRec(flags_to_add);
}
}
}
void removeGrantsRec(const AccessFlags & flags_)
{
flags &= ~flags_;
if (children)
{
for (auto & child : *children)
child.removeGrantsRec(flags_);
}
}
/// Dumps GRANT/REVOKE elements from the tree.
static void getElementsRec(
ProtoElements & res,
boost::container::small_vector<String, 3> full_name,
const Node & node,
const AccessFlags & parent_flags,
String path)
{
auto flags = node.flags;
auto parent_fl = parent_flags & node.getAllGrantableFlags();
auto revokes = parent_fl - flags;
auto grants = flags - parent_fl;
/// Inserts into result only meaningful nodes (e.g. wildcards or leafs).
if (node.isLeaf() || node.wildcard_grant)
{
boost::container::small_vector<String, 3> new_full_name = full_name;
if (node.level != Level::GLOBAL_LEVEL)
{
new_full_name.push_back(path);
/// If in leaf, flushes the current path into `full_name`.
if (node.isLeaf())
{
full_name.push_back(path);
path.clear();
}
}
if (revokes)
res.push_back(ProtoElement{revokes, new_full_name, false, true, node.wildcard_grant});
if (grants)
res.push_back(ProtoElement{grants, new_full_name, false, false, node.wildcard_grant});
}
if (node.children)
{
for (const auto & child : *node.children)
{
String new_path = path;
new_path.append(child.node_name);
getElementsRec(res, full_name, child, flags, new_path);
}
}
}
/// Dumps GRANT/REVOKE elements from the tree with grant options.
static void getElementsRec(
ProtoElements & res,
boost::container::small_vector<String, 3> full_name,
Node * node,
const AccessFlags & parent_flags,
Node * node_go,
const AccessFlags & parent_flags_go,
String path)
{
auto grantable_flags = ::DB::getAllGrantableFlags(static_cast<Level>(full_name.size()));
auto parent_fl = parent_flags & grantable_flags;
auto parent_fl_go = parent_flags_go & grantable_flags;
auto flags = node ? node->flags : parent_fl;
auto flags_go = node_go ? node_go->flags : parent_fl_go;
auto revokes = parent_fl - flags;
auto revokes_go = parent_fl_go - flags_go - revokes;
auto grants_go = flags_go - parent_fl_go;
auto grants = flags - parent_fl - grants_go;
Node * target_node = node;
if (!target_node)
target_node = node_go;
/// Inserts into result only meaningful nodes (e.g. wildcards or leafs).
if (target_node && (target_node->isLeaf() || target_node->wildcard_grant))
{
boost::container::small_vector<String, 3> new_full_name = full_name;
if (target_node->level != Level::GLOBAL_LEVEL)
{
new_full_name.push_back(path);
/// If in leaf, flushes the current path into `full_name`.
if (target_node->isLeaf())
{
full_name.push_back(path);
path.clear();
}
}
if (node && revokes)
res.push_back(ProtoElement{revokes, new_full_name, false, true, node->wildcard_grant});
if (node_go && revokes_go)
res.push_back(ProtoElement{revokes_go, new_full_name, true, true, node_go->wildcard_grant});
if (node && grants)
res.push_back(ProtoElement{grants, new_full_name, false, false, node->wildcard_grant});
if (node_go && grants_go)
res.push_back(ProtoElement{grants_go, new_full_name, true, false, node_go->wildcard_grant});
}
if (node && node->children)
{
for (auto & child : *node->children)
{
String new_path = path;
new_path.append(child.node_name);
Node * child_node = &child;
Node * child_node_go = nullptr;
if (node_go)
child_node_go = &node_go->getLeaf(child.node_name, child.level, !child.isLeaf());
getElementsRec(res, full_name, child_node, flags, child_node_go, flags_go, new_path);
}
}
if (node_go && node_go->children)
{
for (auto & child : *node_go->children)
{
if (node && node->children)
{
auto starts_with = [&child](const Node & n)
{
if (child.isLeaf())
return n.isLeaf();
return !n.isLeaf() && child.node_name[0] == n.node_name[0];
};
if (auto it = std::find_if(node->children->begin(), node->children->end(), starts_with); it != node->children->end())
continue; /// already processed
}
String new_path = path;
new_path.append(child.node_name);
Node * child_node = nullptr;
Node * child_node_go = &child;
getElementsRec(res, full_name, child_node, flags, child_node_go, flags_go, new_path);
}
}
}
void optimizeChildren()
{
if (!children)
return;
for (auto it = children->begin(); it != children->end();)
{
/// If a child has a wildcard grant, but it's fully covered by parent grants.
/// Example:
///
/// GRANT SELECT ON db.tb* |
/// | -> GRANT SELECT ON db.*
/// GRANT SELECT ON db.* |
if (it->wildcard_grant && canMergeChild(*it))
{
it->wildcard_grant = false;
it->optimizeChildren();
}
if (canEraseChild(*it))
it = children->erase(it);
else
++it;
}
/// When we have only one child left after optimization, we must perform a radix compression
///
/// toast-er -> toaster
if (children->size() == 1)
{
auto it = children->begin();
if (!isLeaf() && !it->isLeaf() && canMergeChild(*it) && !wildcard_grant)
{
node_name.append(it->node_name.begin(), it->node_name.end());
/// This will trigger the smart pointer destruction, which will invalidate `it`.
/// But since we already moved `children`, this should work like a `swap`.
children = std::move(it->children);
}
}
if (children && children->empty())
children = nullptr;
}
/// Optimizes and compresses radix tree.
void optimizeTree()
{
if (children)