aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Access/ContextAccess.cpp
blob: c3aeec15cdd69f9658a60693c9b1e1b40e218bc0 (plain) (blame)
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
#include <Access/ContextAccess.h>
#include <Access/AccessControl.h>
#include <Access/EnabledRoles.h>
#include <Access/EnabledRowPolicies.h>
#include <Access/EnabledQuota.h>
#include <Access/QuotaUsage.h>
#include <Access/User.h>
#include <Access/Role.h>
#include <Access/EnabledRolesInfo.h>
#include <Access/EnabledSettings.h>
#include <Access/SettingsProfilesInfo.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Interpreters/Context.h>
#include <Common/Exception.h>
#include <Common/quoteString.h>
#include <Core/Settings.h>
#include <IO/WriteHelpers.h>
#include <Poco/Logger.h>
#include <Common/logger_useful.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/range/algorithm/set_algorithm.hpp>
#include <cassert>


namespace DB
{
namespace ErrorCodes
{
    extern const int ACCESS_DENIED;
    extern const int READONLY;
    extern const int QUERY_IS_PROHIBITED;
    extern const int FUNCTION_NOT_ALLOWED;
    extern const int UNKNOWN_USER;
    extern const int LOGICAL_ERROR;
}


namespace
{
    AccessRights mixAccessRightsFromUserAndRoles(const User & user, const EnabledRolesInfo & roles_info)
    {
        AccessRights res = user.access;
        res.makeUnion(roles_info.access);
        return res;
    }


    AccessRights addImplicitAccessRights(const AccessRights & access, const AccessControl & access_control)
    {
        AccessFlags max_flags;

        auto modifier = [&](const AccessFlags & flags,
                            const AccessFlags & min_flags_with_children,
                            const AccessFlags & max_flags_with_children,
                            std::string_view database,
                            std::string_view table,
                            std::string_view column,
                            bool /* grant_option */) -> AccessFlags
        {
            size_t level = !database.empty() + !table.empty() + !column.empty();
            AccessFlags res = flags;

            /// CREATE_TABLE => CREATE_VIEW, DROP_TABLE => DROP_VIEW, ALTER_TABLE => ALTER_VIEW
            static const AccessFlags create_table = AccessType::CREATE_TABLE;
            static const AccessFlags create_view = AccessType::CREATE_VIEW;
            static const AccessFlags drop_table = AccessType::DROP_TABLE;
            static const AccessFlags drop_view = AccessType::DROP_VIEW;
            static const AccessFlags alter_table = AccessType::ALTER_TABLE;
            static const AccessFlags alter_view = AccessType::ALTER_VIEW;

            if (res & create_table)
                res |= create_view;

            if (res & drop_table)
                res |= drop_view;

            if (res & alter_table)
                res |= alter_view;

            /// CREATE TABLE (on any database/table) => CREATE_TEMPORARY_TABLE (global)
            static const AccessFlags create_temporary_table = AccessType::CREATE_TEMPORARY_TABLE;
            if ((level == 0) && (max_flags_with_children & create_table))
                res |= create_temporary_table;

            /// CREATE TABLE (on any database/table) => CREATE_ARBITRARY_TEMPORARY_TABLE (global)
            static const AccessFlags create_arbitrary_temporary_table = AccessType::CREATE_ARBITRARY_TEMPORARY_TABLE;
            if ((level == 0) && (max_flags_with_children & create_table))
                res |= create_arbitrary_temporary_table;

            /// ALTER_TTL => ALTER_MATERIALIZE_TTL
            static const AccessFlags alter_ttl = AccessType::ALTER_TTL;
            static const AccessFlags alter_materialize_ttl = AccessType::ALTER_MATERIALIZE_TTL;
            if (res & alter_ttl)
                res |= alter_materialize_ttl;

            /// RELOAD_DICTIONARY (global) => RELOAD_EMBEDDED_DICTIONARIES (global)
            static const AccessFlags reload_dictionary = AccessType::SYSTEM_RELOAD_DICTIONARY;
            static const AccessFlags reload_embedded_dictionaries = AccessType::SYSTEM_RELOAD_EMBEDDED_DICTIONARIES;
            if ((level == 0) && (min_flags_with_children & reload_dictionary))
                res |= reload_embedded_dictionaries;

            /// any column flag => SHOW_COLUMNS => SHOW_TABLES => SHOW_DATABASES
            ///                  any table flag => SHOW_TABLES => SHOW_DATABASES
            ///       any dictionary flag => SHOW_DICTIONARIES => SHOW_DATABASES
            ///                              any database flag => SHOW_DATABASES
            static const AccessFlags show_columns = AccessType::SHOW_COLUMNS;
            static const AccessFlags show_tables = AccessType::SHOW_TABLES;
            static const AccessFlags show_dictionaries = AccessType::SHOW_DICTIONARIES;
            static const AccessFlags show_tables_or_dictionaries = show_tables | show_dictionaries;
            static const AccessFlags show_databases = AccessType::SHOW_DATABASES;

            if (res & AccessFlags::allColumnFlags())
                res |= show_columns;

            if ((res & AccessFlags::allTableFlags())
                || (level <= 2 && (res & show_columns))
                || (level == 2 && (max_flags_with_children & show_columns)))
            {
                res |= show_tables;
            }

            if (res & AccessFlags::allDictionaryFlags())
                res |= show_dictionaries;

            if ((res & AccessFlags::allDatabaseFlags())
                || (level <= 1 && (res & show_tables_or_dictionaries))
                || (level == 1 && (max_flags_with_children & show_tables_or_dictionaries)))
            {
                res |= show_databases;
            }

            max_flags |= res;

            return res;
        };

        AccessRights res = access;
        res.modifyFlags(modifier);

        /// If "select_from_system_db_requires_grant" is enabled we provide implicit grants only for a few tables in the system database.
        if (access_control.doesSelectFromSystemDatabaseRequireGrant())
        {
            const char * always_accessible_tables[] = {
                /// Constant tables
                "one",

                /// "numbers", "numbers_mt", "zeros", "zeros_mt" were excluded because they can generate lots of values and
                /// that can decrease performance in some cases.

                "contributors",
                "licenses",
                "time_zones",
                "collations",

                "formats",
                "privileges",
                "data_type_families",
                "table_engines",
                "table_functions",
                "aggregate_function_combinators",

                "functions", /// Can contain user-defined functions

                /// The following tables hide some rows if the current user doesn't have corresponding SHOW privileges.
                "databases",
                "tables",
                "columns",

                /// Specific to the current session
                "settings",
                "current_roles",
                "enabled_roles",
                "quota_usage"
            };

            for (const auto * table_name : always_accessible_tables)
                res.grant(AccessType::SELECT, DatabaseCatalog::SYSTEM_DATABASE, table_name);

            if (max_flags.contains(AccessType::SHOW_USERS))
                res.grant(AccessType::SELECT, DatabaseCatalog::SYSTEM_DATABASE, "users");

            if (max_flags.contains(AccessType::SHOW_ROLES))
                res.grant(AccessType::SELECT, DatabaseCatalog::SYSTEM_DATABASE, "roles");

            if (max_flags.contains(AccessType::SHOW_ROW_POLICIES))
                res.grant(AccessType::SELECT, DatabaseCatalog::SYSTEM_DATABASE, "row_policies");

            if (max_flags.contains(AccessType::SHOW_SETTINGS_PROFILES))
                res.grant(AccessType::SELECT, DatabaseCatalog::SYSTEM_DATABASE, "settings_profiles");

            if (max_flags.contains(AccessType::SHOW_QUOTAS))
                res.grant(AccessType::SELECT, DatabaseCatalog::SYSTEM_DATABASE, "quotas");
        }
        else
        {
            res.grant(AccessType::SELECT, DatabaseCatalog::SYSTEM_DATABASE);
        }

        /// If "select_from_information_schema_requires_grant" is enabled we don't provide implicit grants for the information_schema database.
        if (!access_control.doesSelectFromInformationSchemaRequireGrant())
        {
            res.grant(AccessType::SELECT, DatabaseCatalog::INFORMATION_SCHEMA);
            res.grant(AccessType::SELECT, DatabaseCatalog::INFORMATION_SCHEMA_UPPERCASE);
        }

        return res;
    }


    std::array<UUID, 1> to_array(const UUID & id)
    {
        std::array<UUID, 1> ids;
        ids[0] = id;
        return ids;
    }

    /// Helper for using in templates.
    std::string_view getDatabase() { return {}; }

    template <typename... OtherArgs>
    std::string_view getDatabase(std::string_view arg1, const OtherArgs &...) { return arg1; }
}


std::shared_ptr<const ContextAccess> ContextAccess::fromContext(const ContextPtr & context)
{
    return context->getAccess();
}


ContextAccess::ContextAccess(const AccessControl & access_control_, const Params & params_)
    : access_control(&access_control_)
    , params(params_)
{
}


ContextAccess::~ContextAccess() = default;


void ContextAccess::initialize()
{
    std::lock_guard lock{mutex};

    if (params.full_access)
    {
        access = std::make_shared<AccessRights>(AccessRights::getFullAccess());
        access_with_implicit = access;
        return;
    }

    if (!params.user_id)
        throw Exception(ErrorCodes::LOGICAL_ERROR, "No user in current context, it's a bug");

    subscription_for_user_change = access_control->subscribeForChanges(
        *params.user_id,
        [weak_ptr = weak_from_this()](const UUID &, const AccessEntityPtr & entity)
        {
            auto ptr = weak_ptr.lock();
            if (!ptr)
                return;
            UserPtr changed_user = entity ? typeid_cast<UserPtr>(entity) : nullptr;
            std::lock_guard lock2{ptr->mutex};
            ptr->setUser(changed_user);
        });

    setUser(access_control->read<User>(*params.user_id));
}


void ContextAccess::setUser(const UserPtr & user_) const
{
    user = user_;

    if (!user_)
    {
        /// User has been dropped.
        user_was_dropped = true;
        subscription_for_user_change = {};
        subscription_for_roles_changes = {};
        access = nullptr;
        access_with_implicit = nullptr;
        enabled_roles = nullptr;
        roles_info = nullptr;
        enabled_row_policies = nullptr;
        row_policies_of_initial_user = nullptr;
        enabled_quota = nullptr;
        enabled_settings = nullptr;
        return;
    }

    user_name = user->getName();
    trace_log = &Poco::Logger::get("ContextAccess (" + user_name + ")");

    std::vector<UUID> current_roles, current_roles_with_admin_option;
    if (params.use_default_roles)
    {
        current_roles = user->granted_roles.findGranted(user->default_roles);
        current_roles_with_admin_option = user->granted_roles.findGrantedWithAdminOption(user->default_roles);
    }
    else if (params.current_roles)
    {
        current_roles = user->granted_roles.findGranted(*params.current_roles);
        current_roles_with_admin_option = user->granted_roles.findGrantedWithAdminOption(*params.current_roles);
    }

    subscription_for_roles_changes.reset();
    enabled_roles = access_control->getEnabledRoles(current_roles, current_roles_with_admin_option);
    subscription_for_roles_changes = enabled_roles->subscribeForChanges([this](const std::shared_ptr<const EnabledRolesInfo> & roles_info_)
    {
        std::lock_guard lock{mutex};
        setRolesInfo(roles_info_);
    });

    setRolesInfo(enabled_roles->getRolesInfo());

    std::optional<UUID> initial_user_id;
    if (!params.initial_user.empty())
        initial_user_id = access_control->find<User>(params.initial_user);
    row_policies_of_initial_user = initial_user_id ? access_control->tryGetDefaultRowPolicies(*initial_user_id) : nullptr;
}


void ContextAccess::setRolesInfo(const std::shared_ptr<const EnabledRolesInfo> & roles_info_) const
{
    assert(roles_info_);
    roles_info = roles_info_;

    enabled_row_policies = access_control->getEnabledRowPolicies(*params.user_id, roles_info->enabled_roles);

    enabled_settings = access_control->getEnabledSettings(
        *params.user_id, user->settings, roles_info->enabled_roles, roles_info->settings_from_enabled_roles);

    calculateAccessRights();
}


void ContextAccess::calculateAccessRights() const
{
    access = std::make_shared<AccessRights>(mixAccessRightsFromUserAndRoles(*user, *roles_info));
    access_with_implicit = std::make_shared<AccessRights>(addImplicitAccessRights(*access, *access_control));

    if (trace_log)
    {
        if (roles_info && !roles_info->getCurrentRolesNames().empty())
        {
            LOG_TRACE(trace_log, "Current_roles: {}, enabled_roles: {}",
                boost::algorithm::join(roles_info->getCurrentRolesNames(), ", "),
                boost::algorithm::join(roles_info->getEnabledRolesNames(), ", "));
        }
        LOG_TRACE(trace_log, "Settings: readonly = {}, allow_ddl = {}, allow_introspection_functions = {}", params.readonly, params.allow_ddl, params.allow_introspection);
        LOG_TRACE(trace_log, "List of all grants: {}", access->toString());
        LOG_TRACE(trace_log, "List of all grants including implicit: {}", access_with_implicit->toString());
    }
}


UserPtr ContextAccess::getUser() const
{
    auto res = tryGetUser();

    if (likely(res))
        return res;

    if (user_was_dropped)
        throw Exception(ErrorCodes::UNKNOWN_USER, "User has been dropped");

    throw Exception(ErrorCodes::LOGICAL_ERROR, "No user in current context, it's a bug");
}


UserPtr ContextAccess::tryGetUser() const
{
    std::lock_guard lock{mutex};
    return user;
}

String ContextAccess::getUserName() const
{
    std::lock_guard lock{mutex};
    return user_name;
}

std::shared_ptr<const EnabledRolesInfo> ContextAccess::getRolesInfo() const
{
    std::lock_guard lock{mutex};
    if (roles_info)
        return roles_info;
    static const auto no_roles = std::make_shared<EnabledRolesInfo>();
    return no_roles;
}

RowPolicyFilterPtr ContextAccess::getRowPolicyFilter(const String & database, const String & table_name, RowPolicyFilterType filter_type) const
{
    std::lock_guard lock{mutex};

    RowPolicyFilterPtr filter;
    if (enabled_row_policies)
        filter = enabled_row_policies->getFilter(database, table_name, filter_type);

    if (row_policies_of_initial_user)
    {
        /// Find and set extra row policies to be used based on `client_info.initial_user`, if the initial user exists.
        /// TODO: we need a better solution here. It seems we should pass the initial row policy
        /// because a shard is allowed to not have the initial user or it might be another user
        /// with the same name.
        filter = row_policies_of_initial_user->getFilter(database, table_name, filter_type, filter);
    }

    return filter;
}

std::shared_ptr<const EnabledQuota> ContextAccess::getQuota() const
{
    std::lock_guard lock{mutex};

    if (!enabled_quota)
    {
        if (roles_info)
        {
            enabled_quota = access_control->getEnabledQuota(*params.user_id,
                                                            user_name,
                                                            roles_info->enabled_roles,
                                                            params.address,
                                                            params.forwarded_address,
                                                            params.quota_key);
        }
        else
        {
            static const auto unlimited_quota = EnabledQuota::getUnlimitedQuota();
            return unlimited_quota;
        }
    }

    return enabled_quota;
}


std::optional<QuotaUsage> ContextAccess::getQuotaUsage() const
{
    return getQuota()->getUsage();
}


SettingsChanges ContextAccess::getDefaultSettings() const
{
    std::lock_guard lock{mutex};
    if (enabled_settings)
    {
        if (auto info = enabled_settings->getInfo())
            return info->settings;
    }
    return {};
}


std::shared_ptr<const SettingsProfilesInfo> ContextAccess::getDefaultProfileInfo() const
{
    std::lock_guard lock{mutex};
    if (enabled_settings)
        return enabled_settings->getInfo();
    static const auto everything_by_default = std::make_shared<SettingsProfilesInfo>(*access_control);
    return everything_by_default;
}


std::shared_ptr<const AccessRights> ContextAccess::getAccessRights() const
{
    std::lock_guard lock{mutex};
    if (access)
        return access;
    static const auto nothing_granted = std::make_shared<AccessRights>();
    return nothing_granted;
}


std::shared_ptr<const AccessRights> ContextAccess::getAccessRightsWithImplicit() const
{
    std::lock_guard lock{mutex};
    if (access_with_implicit)
        return access_with_implicit;
    static const auto nothing_granted = std::make_shared<AccessRights>();
    return nothing_granted;
}


template <bool throw_if_denied, bool grant_option, typename... Args>
bool ContextAccess::checkAccessImplHelper(AccessFlags flags, const Args &... args) const
{
    if (user_was_dropped)
    {
        /// If the current user has been dropped we always throw an exception (even if `throw_if_denied` is false)
        /// because dropping of the current user is considered as a situation which is exceptional enough to stop
        /// query execution.
        throw Exception(ErrorCodes::UNKNOWN_USER, "{}: User has been dropped", getUserName());
    }

    if (params.full_access)
        return true;

    auto access_granted = [&]
    {
        if (trace_log)
            LOG_TRACE(trace_log, "Access granted: {}{}", (AccessRightsElement{flags, args...}.toStringWithoutOptions()),
                      (grant_option ? " WITH GRANT OPTION" : ""));
        return true;
    };

    auto access_denied = [&]<typename... FmtArgs>(int error_code [[maybe_unused]],
                                               FormatStringHelper<String, FmtArgs...> fmt_string [[maybe_unused]],
                                               FmtArgs && ...fmt_args [[maybe_unused]])
    {
        if (trace_log)
            LOG_TRACE(trace_log, "Access denied: {}{}", (AccessRightsElement{flags, args...}.toStringWithoutOptions()),
                      (grant_option ? " WITH GRANT OPTION" : ""));
        if constexpr (throw_if_denied)
            throw Exception(error_code, std::move(fmt_string), getUserName(), std::forward<FmtArgs>(fmt_args)...);
        return false;
    };

    if (flags & AccessType::CLUSTER && !access_control->doesOnClusterQueriesRequireClusterGrant())
        flags &= ~AccessType::CLUSTER;

    if (!flags)
        return true;

    const auto parameter_type = flags.getParameterType();
    if (parameter_type == AccessFlags::NONE)
    {
        /// Access to temporary tables is controlled in an unusual way, not like normal tables.
        /// Creating of temporary tables is controlled by AccessType::CREATE_TEMPORARY_TABLES grant,
        /// and other grants are considered as always given.
        /// The DatabaseCatalog class won't resolve StorageID for temporary tables
        /// which shouldn't be accessed.
        if (getDatabase(args...) == DatabaseCatalog::TEMPORARY_DATABASE)
            return access_granted();
    }

    auto acs = getAccessRightsWithImplicit();
    bool granted;
    if constexpr (grant_option)
        granted = acs->hasGrantOption(flags, args...);
    else
        granted = acs->isGranted(flags, args...);

    if (!granted)
    {
        if (grant_option && acs->isGranted(flags, args...))
        {
            return access_denied(ErrorCodes::ACCESS_DENIED,
                "{}: Not enough privileges. "
                "The required privileges have been granted, but without grant option. "
                "To execute this query, it's necessary to have the grant {} WITH GRANT OPTION",
                AccessRightsElement{flags, args...}.toStringWithoutOptions());
        }

        return access_denied(ErrorCodes::ACCESS_DENIED,
            "{}: Not enough privileges. To execute this query, it's necessary to have the grant {}",
            AccessRightsElement{flags, args...}.toStringWithoutOptions() + (grant_option ? " WITH GRANT OPTION" : ""));
    }

    struct PrecalculatedFlags
    {
        const AccessFlags table_ddl = AccessType::CREATE_DATABASE | AccessType::CREATE_TABLE | AccessType::CREATE_VIEW
            | AccessType::ALTER_TABLE | AccessType::ALTER_VIEW | AccessType::DROP_DATABASE | AccessType::DROP_TABLE | AccessType::DROP_VIEW
            | AccessType::TRUNCATE;

        const AccessFlags dictionary_ddl = AccessType::CREATE_DICTIONARY | AccessType::DROP_DICTIONARY;
        const AccessFlags function_ddl = AccessType::CREATE_FUNCTION | AccessType::DROP_FUNCTION;
        const AccessFlags table_and_dictionary_ddl = table_ddl | dictionary_ddl;
        const AccessFlags table_and_dictionary_and_function_ddl = table_ddl | dictionary_ddl | function_ddl;
        const AccessFlags write_table_access = AccessType::INSERT | AccessType::OPTIMIZE;
        const AccessFlags write_dcl_access = AccessType::ACCESS_MANAGEMENT - AccessType::SHOW_ACCESS;

        const AccessFlags not_readonly_flags = write_table_access | table_and_dictionary_and_function_ddl | write_dcl_access | AccessType::SYSTEM | AccessType::KILL_QUERY;
        const AccessFlags not_readonly_1_flags = AccessType::CREATE_TEMPORARY_TABLE;

        const AccessFlags ddl_flags = table_ddl | dictionary_ddl | function_ddl;
        const AccessFlags introspection_flags = AccessType::INTROSPECTION;
    };
    static const PrecalculatedFlags precalc;

    if (params.readonly)
    {
        if constexpr (grant_option)
            return access_denied(ErrorCodes::READONLY, "{}: Cannot change grants in readonly mode.");
        if ((flags & precalc.not_readonly_flags) ||
            ((params.readonly == 1) && (flags & precalc.not_readonly_1_flags)))
        {
            if (params.interface == ClientInfo::Interface::HTTP && params.http_method == ClientInfo::HTTPMethod::GET)
            {
                return access_denied(ErrorCodes::READONLY,
                    "{}: Cannot execute query in readonly mode. "
                    "For queries over HTTP, method GET implies readonly. "
                    "You should use method POST for modifying queries");
            }
            else
                return access_denied(ErrorCodes::READONLY, "{}: Cannot execute query in readonly mode");
        }
    }

    if (!params.allow_ddl && !grant_option)
    {
        if (flags & precalc.ddl_flags)
            return access_denied(ErrorCodes::QUERY_IS_PROHIBITED,
                                 "Cannot execute query. DDL queries are prohibited for the user {}");
    }

    if (!params.allow_introspection && !grant_option)
    {
        if (flags & precalc.introspection_flags)
            return access_denied(ErrorCodes::FUNCTION_NOT_ALLOWED, "{}: Introspection functions are disabled, "
                                 "because setting 'allow_introspection_functions' is set to 0");
    }

    return access_granted();
}

template <bool throw_if_denied, bool grant_option>
bool ContextAccess::checkAccessImpl(const AccessFlags & flags) const
{
    return checkAccessImplHelper<throw_if_denied, grant_option>(flags);
}

template <bool throw_if_denied, bool grant_option, typename... Args>
bool ContextAccess::checkAccessImpl(const AccessFlags & flags, std::string_view database, const Args &... args) const
{
    return checkAccessImplHelper<throw_if_denied, grant_option>(flags, database.empty() ? params.current_database : database, args...);
}

template <bool throw_if_denied, bool grant_option>
bool ContextAccess::checkAccessImplHelper(const AccessRightsElement & element) const
{
    assert(!element.grant_option || grant_option);
    if (element.isGlobalWithParameter())
    {
        if (element.any_parameter)
            return checkAccessImpl<throw_if_denied, grant_option>(element.access_flags);
        else
            return checkAccessImpl<throw_if_denied, grant_option>(element.access_flags, element.parameter);
    }
    else if (element.any_database)
        return checkAccessImpl<throw_if_denied, grant_option>(element.access_flags);
    else if (element.any_table)
        return checkAccessImpl<throw_if_denied, grant_option>(element.access_flags, element.database);
    else if (element.any_column)
        return checkAccessImpl<throw_if_denied, grant_option>(element.access_flags, element.database, element.table);
    else
        return checkAccessImpl<throw_if_denied, grant_option>(element.access_flags, element.database, element.table, element.columns);
}

template <bool throw_if_denied, bool grant_option>
bool ContextAccess::checkAccessImpl(const AccessRightsElement & element) const
{
    if constexpr (grant_option)
    {
        return checkAccessImplHelper<throw_if_denied, true>(element);
    }
    else
    {
        if (element.grant_option)
            return checkAccessImplHelper<throw_if_denied, true>(element);
        else
            return checkAccessImplHelper<throw_if_denied, false>(element);
    }
}

template <bool throw_if_denied, bool grant_option>
bool ContextAccess::checkAccessImpl(const AccessRightsElements & elements) const
{
    for (const auto & element : elements)
        if (!checkAccessImpl<throw_if_denied, grant_option>(element))
            return false;
    return true;
}

bool ContextAccess::isGranted(const AccessFlags & flags) const { return checkAccessImpl<false, false>(flags); }
bool ContextAccess::isGranted(const AccessFlags & flags, std::string_view database) const { return checkAccessImpl<false, false>(flags, database); }
bool ContextAccess::isGranted(const AccessFlags & flags, std::string_view database, std::string_view table) const { return checkAccessImpl<false, false>(flags, database, table); }
bool ContextAccess::isGranted(const AccessFlags & flags, std::string_view database, std::string_view table, std::string_view column) const { return checkAccessImpl<false, false>(flags, database, table, column); }
bool ContextAccess::isGranted(const AccessFlags & flags, std::string_view database, std::string_view table, const std::vector<std::string_view> & columns) const { return checkAccessImpl<false, false>(flags, database, table, columns); }
bool ContextAccess::isGranted(const AccessFlags & flags, std::string_view database, std::string_view table, const Strings & columns) const { return checkAccessImpl<false, false>(flags, database, table, columns); }
bool ContextAccess::isGranted(const AccessRightsElement & element) const { return checkAccessImpl<false, false>(element); }
bool ContextAccess::isGranted(const AccessRightsElements & elements) const { return checkAccessImpl<false, false>(elements); }

bool ContextAccess::hasGrantOption(const AccessFlags & flags) const { return checkAccessImpl<false, true>(flags); }
bool ContextAccess::hasGrantOption(const AccessFlags & flags, std::string_view database) const { return checkAccessImpl<false, true>(flags, database); }
bool ContextAccess::hasGrantOption(const AccessFlags & flags, std::string_view database, std::string_view table) const { return checkAccessImpl<false, true>(flags, database, table); }
bool ContextAccess::hasGrantOption(const AccessFlags & flags, std::string_view database, std::string_view table, std::string_view column) const { return checkAccessImpl<false, true>(flags, database, table, column); }
bool ContextAccess::hasGrantOption(const AccessFlags & flags, std::string_view database, std::string_view table, const std::vector<std::string_view> & columns) const { return checkAccessImpl<false, true>(flags, database, table, columns); }
bool ContextAccess::hasGrantOption(const AccessFlags & flags, std::string_view database, std::string_view table, const Strings & columns) const { return checkAccessImpl<false, true>(flags, database, table, columns); }
bool ContextAccess::hasGrantOption(const AccessRightsElement & element) const { return checkAccessImpl<false, true>(element); }
bool ContextAccess::hasGrantOption(const AccessRightsElements & elements) const { return checkAccessImpl<false, true>(elements); }

void ContextAccess::checkAccess(const AccessFlags & flags) const { checkAccessImpl<true, false>(flags); }
void ContextAccess::checkAccess(const AccessFlags & flags, std::string_view database) const { checkAccessImpl<true, false>(flags, database); }
void ContextAccess::checkAccess(const AccessFlags & flags, std::string_view database, std::string_view table) const { checkAccessImpl<true, false>(flags, database, table); }
void ContextAccess::checkAccess(const AccessFlags & flags, std::string_view database, std::string_view table, std::string_view column) const { checkAccessImpl<true, false>(flags, database, table, column); }
void ContextAccess::checkAccess(const AccessFlags & flags, std::string_view database, std::string_view table, const std::vector<std::string_view> & columns) const { checkAccessImpl<true, false>(flags, database, table, columns); }
void ContextAccess::checkAccess(const AccessFlags & flags, std::string_view database, std::string_view table, const Strings & columns) const { checkAccessImpl<true, false>(flags, database, table, columns); }
void ContextAccess::checkAccess(const AccessRightsElement & element) const { checkAccessImpl<true, false>(element); }
void ContextAccess::checkAccess(const AccessRightsElements & elements) const { checkAccessImpl<true, false>(elements); }

void ContextAccess::checkGrantOption(const AccessFlags & flags) const { checkAccessImpl<true, true>(flags); }
void ContextAccess::checkGrantOption(const AccessFlags & flags, std::string_view database) const { checkAccessImpl<true, true>(flags, database); }
void ContextAccess::checkGrantOption(const AccessFlags & flags, std::string_view database, std::string_view table) const { checkAccessImpl<true, true>(flags, database, table); }
void ContextAccess::checkGrantOption(const AccessFlags & flags, std::string_view database, std::string_view table, std::string_view column) const { checkAccessImpl<true, true>(flags, database, table, column); }
void ContextAccess::checkGrantOption(const AccessFlags & flags, std::string_view database, std::string_view table, const std::vector<std::string_view> & columns) const { checkAccessImpl<true, true>(flags, database, table, columns); }
void ContextAccess::checkGrantOption(const AccessFlags & flags, std::string_view database, std::string_view table, const Strings & columns) const { checkAccessImpl<true, true>(flags, database, table, columns); }
void ContextAccess::checkGrantOption(const AccessRightsElement & element) const { checkAccessImpl<true, true>(element); }
void ContextAccess::checkGrantOption(const AccessRightsElements & elements) const { checkAccessImpl<true, true>(elements); }


template <bool throw_if_denied, typename Container, typename GetNameFunction>
bool ContextAccess::checkAdminOptionImplHelper(const Container & role_ids, const GetNameFunction & get_name_function) const
{
    auto show_error = []<typename... FmtArgs>(int error_code [[maybe_unused]],
                                                  FormatStringHelper<FmtArgs...> fmt_string [[maybe_unused]],
                                                  FmtArgs && ...fmt_args [[maybe_unused]])
    {
        if constexpr (throw_if_denied)
            throw Exception(error_code, std::move(fmt_string), std::forward<FmtArgs>(fmt_args)...);
        return false;
    };

    if (params.full_access)
        return true;

    if (user_was_dropped)
    {
        show_error(ErrorCodes::UNKNOWN_USER, "User has been dropped");
        return false;
    }

    if (!std::size(role_ids))
        return true;

    if (isGranted(AccessType::ROLE_ADMIN))
        return true;

    auto info = getRolesInfo();
    size_t i = 0;
    for (auto it = std::begin(role_ids); it != std::end(role_ids); ++it, ++i)
    {
        const UUID & role_id = *it;
        if (info->enabled_roles_with_admin_option.count(role_id))
            continue;

        if (throw_if_denied)
        {
            auto role_name = get_name_function(role_id, i);
            if (!role_name)
                role_name = "ID {" + toString(role_id) + "}";

            if (info->enabled_roles.count(role_id))
                show_error(ErrorCodes::ACCESS_DENIED,
                           "Not enough privileges. "
                           "Role {} is granted, but without ADMIN option. "
                           "To execute this query, it's necessary to have the role {} granted with ADMIN option.",
                           backQuote(*role_name), backQuoteIfNeed(*role_name));
            else
                show_error(ErrorCodes::ACCESS_DENIED, "Not enough privileges. "
                           "To execute this query, it's necessary to have the role {} granted with ADMIN option.",
                           backQuoteIfNeed(*role_name));
        }

        return false;
    }

    return true;
}

template <bool throw_if_denied>
bool ContextAccess::checkAdminOptionImpl(const UUID & role_id) const
{
    return checkAdminOptionImplHelper<throw_if_denied>(to_array(role_id), [this](const UUID & id, size_t) { return access_control->tryReadName(id); });
}

template <bool throw_if_denied>
bool ContextAccess::checkAdminOptionImpl(const UUID & role_id, const String & role_name) const
{
    return checkAdminOptionImplHelper<throw_if_denied>(to_array(role_id), [&role_name](const UUID &, size_t) { return std::optional<String>{role_name}; });
}

template <bool throw_if_denied>
bool ContextAccess::checkAdminOptionImpl(const UUID & role_id, const std::unordered_map<UUID, String> & names_of_roles) const
{
    return checkAdminOptionImplHelper<throw_if_denied>(to_array(role_id), [&names_of_roles](const UUID & id, size_t) { auto it = names_of_roles.find(id); return (it != names_of_roles.end()) ? it->second : std::optional<String>{}; });
}

template <bool throw_if_denied>
bool ContextAccess::checkAdminOptionImpl(const std::vector<UUID> & role_ids) const
{
    return checkAdminOptionImplHelper<throw_if_denied>(role_ids, [this](const UUID & id, size_t) { return access_control->tryReadName(id); });
}

template <bool throw_if_denied>
bool ContextAccess::checkAdminOptionImpl(const std::vector<UUID> & role_ids, const Strings & names_of_roles) const
{
    return checkAdminOptionImplHelper<throw_if_denied>(role_ids, [&names_of_roles](const UUID &, size_t i) { return std::optional<String>{names_of_roles[i]}; });
}

template <bool throw_if_denied>
bool ContextAccess::checkAdminOptionImpl(const std::vector<UUID> & role_ids, const std::unordered_map<UUID, String> & names_of_roles) const
{
    return checkAdminOptionImplHelper<throw_if_denied>(role_ids, [&names_of_roles](const UUID & id, size_t) { auto it = names_of_roles.find(id); return (it != names_of_roles.end()) ? it->second : std::optional<String>{}; });
}

bool ContextAccess::hasAdminOption(const UUID & role_id) const { return checkAdminOptionImpl<false>(role_id); }
bool ContextAccess::hasAdminOption(const UUID & role_id, const String & role_name) const { return checkAdminOptionImpl<false>(role_id, role_name); }
bool ContextAccess::hasAdminOption(const UUID & role_id, const std::unordered_map<UUID, String> & names_of_roles) const { return checkAdminOptionImpl<false>(role_id, names_of_roles); }
bool ContextAccess::hasAdminOption(const std::vector<UUID> & role_ids) const { return checkAdminOptionImpl<false>(role_ids); }
bool ContextAccess::hasAdminOption(const std::vector<UUID> & role_ids, const Strings & names_of_roles) const { return checkAdminOptionImpl<false>(role_ids, names_of_roles); }
bool ContextAccess::hasAdminOption(const std::vector<UUID> & role_ids, const std::unordered_map<UUID, String> & names_of_roles) const { return checkAdminOptionImpl<false>(role_ids, names_of_roles); }

void ContextAccess::checkAdminOption(const UUID & role_id) const { checkAdminOptionImpl<true>(role_id); }
void ContextAccess::checkAdminOption(const UUID & role_id, const String & role_name) const { checkAdminOptionImpl<true>(role_id, role_name); }
void ContextAccess::checkAdminOption(const UUID & role_id, const std::unordered_map<UUID, String> & names_of_roles) const { checkAdminOptionImpl<true>(role_id, names_of_roles); }
void ContextAccess::checkAdminOption(const std::vector<UUID> & role_ids) const { checkAdminOptionImpl<true>(role_ids); }
void ContextAccess::checkAdminOption(const std::vector<UUID> & role_ids, const Strings & names_of_roles) const { checkAdminOptionImpl<true>(role_ids, names_of_roles); }
void ContextAccess::checkAdminOption(const std::vector<UUID> & role_ids, const std::unordered_map<UUID, String> & names_of_roles) const { checkAdminOptionImpl<true>(role_ids, names_of_roles); }


void ContextAccess::checkGranteeIsAllowed(const UUID & grantee_id, const IAccessEntity & grantee) const
{
    if (params.full_access)
        return;

    auto current_user = getUser();
    if (!current_user->grantees.match(grantee_id))
        throw Exception(ErrorCodes::ACCESS_DENIED, "{} is not allowed as grantee", grantee.formatTypeWithName());
}

void ContextAccess::checkGranteesAreAllowed(const std::vector<UUID> & grantee_ids) const
{
    if (params.full_access)
        return;

    auto current_user = getUser();
    if (current_user->grantees == RolesOrUsersSet::AllTag{})
        return;

    for (const auto & id : grantee_ids)
    {
        auto entity = access_control->tryRead(id);
        if (auto role_entity = typeid_cast<RolePtr>(entity))
            checkGranteeIsAllowed(id, *role_entity);
        else if (auto user_entity = typeid_cast<UserPtr>(entity))
            checkGranteeIsAllowed(id, *user_entity);
    }
}

}