packages/sql-semantics-mysql/src/Lowering/Account/UserListRule.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Lowering\Account;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\MySql\Lowering\Lowering;
9use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
10use SqlSemantics\Platform\MySql\Model\Diagnostic\ImplementationGap;
11use SqlSemantics\Platform\MySql\Model\Lowering\Form;
12use SqlSemantics\Platform\MySql\Model\Lowering\Lists;
13use SqlSemantics\Platform\MySql\Statement\Account\User\Credential;
14use SqlSemantics\Platform\MySql\Statement\Account\User\FactorAction;
15use SqlSemantics\Platform\MySql\Statement\Account\User\FactorChange;
16use SqlSemantics\Platform\MySql\Statement\Account\User\FactorStep;
17use SqlSemantics\Platform\MySql\Statement\Account\User\Identification;
18use SqlSemantics\Platform\MySql\Statement\Account\User\UserAlteration;
19use SqlSemantics\Platform\MySql\Statement\Account\User\UserSpecification;
20use SqlSemantics\Platform\MySql\Statement\Name\Account;
21
22/**
23 * Lowers the account lists of CREATE USER, ALTER USER and MySQL 5.x GRANT.
24 *
25 * Rule: MYSQL-ACCOUNT-LIST-001. Scope: create_user_list, create_user,
26 * alter_user_list, alter_user (8.0+), grant_list, grant_user (5.x). Each
27 * entry is the account with what the statement sets for it, as LEX_USER
28 * holds it; the multi-factor forms of ALTER USER are factor changes.
29 * Constructs: UserSpecification, FactorChange, FactorStep. Terminates: the
30 * lists are flattened iteratively; every other child is a strict subtree.
31 * Source: https://dev.mysql.com/doc/refman/8.4/en/create-user.html,
32 * https://dev.mysql.com/doc/refman/8.4/en/alter-user.html,
33 * https://dev.mysql.com/doc/refman/5.7/en/grant.html. Status: Implemented.
34 *
35 * @visibility SqlSemantics\Platform\MySql
36 */
37final class UserListRule
38{
39    /**
40     * The alter_user productions that set an authentication method, by the position of REPLACE's string (or null).
41     */
42    private const CHANGES = [
43        'alter_user: user identified_by_password REPLACE_SYM TEXT_STRING_password opt_retain_current_password' => 3,
44        'alter_user: user identified_with_plugin_by_password REPLACE_SYM TEXT_STRING_password opt_retain_current_password' => 3,
45        'alter_user: user identified_by_random_password REPLACE_SYM TEXT_STRING_password opt_retain_current_password' => 3,
46        'alter_user: user identified_by_password opt_retain_current_password' => null,
47        'alter_user: user identified_by_random_password opt_retain_current_password' => null,
48        'alter_user: user identified_with_plugin_as_auth opt_retain_current_password' => null,
49        'alter_user: user identified_with_plugin_by_password opt_retain_current_password' => null,
50        'alter_user: user identified_with_plugin_by_random_password opt_retain_current_password' => null,
51    ];
52
53    /**
54     * The alter_user productions that change factors, by the action and the number of factors.
55     */
56    private const FACTORS = [
57        'alter_user: user ADD factor identification' => [FactorAction::Add, 1],
58        'alter_user: user ADD factor identification ADD factor identification' => [FactorAction::Add, 2],
59        'alter_user: user MODIFY_SYM factor identification' => [FactorAction::Modify, 1],
60        'alter_user: user MODIFY_SYM factor identification MODIFY_SYM factor identification' => [FactorAction::Modify, 2],
61        'alter_user: user DROP factor' => [FactorAction::Drop, 1],
62        'alter_user: user DROP factor DROP factor' => [FactorAction::Drop, 2],
63    ];
64
65    /**
66     * The list productions this rule flattens.
67     */
68    private const LISTS = [
69        'create_user_list: create_user' => true, 'create_user_list: create_user_list , create_user' => true,
70        'alter_user_list: alter_user' => true, 'alter_user_list: alter_user_list , alter_user' => true,
71        'grant_list: grant_user' => true, 'grant_list: grant_list , grant_user' => true,
72    ];
73
74    /**
75     * @param Lowering $lowering The lowering this rule belongs to
76     * @param IdentificationRule $identifications The authentication clause rules
77     */
78    public function __construct(private readonly Lowering $lowering, private readonly IdentificationRule $identifications)
79    {
80    }
81
82    /**
83     * Lowers a create_user_list.
84     *
85     * @return list<UserSpecification>
86     * @throws ImplementationGap When a production has no rule
87     */
88    public function created(Node $list): array
89    {
90        $users = [];
91        foreach ($this->spine($list) as $item) {
92            $users[] = $this->create($item);
93        }
94
95        return $users;
96    }
97
98    /**
99     * Lowers one create_user.
100     *
101     * @throws ImplementationGap When the production has no rule
102     */
103    public function create(Node $user): UserSpecification
104    {
105        $form = $this->lowering->form($user);
106        $account = $this->lowering->users->account($form->node(0));
107
108        return match ($form->signature) {
109            'create_user: user identification opt_create_user_with_mfa' => new UserSpecification($account, $this->identifications->identification($form->node(1)), $this->identifications->factors($form->node(2))),
110            'create_user: user identified_with_plugin opt_initial_auth' => new UserSpecification($account, $this->identifications->identification($form->node(1)), [], $this->identifications->initial($form->node(2))),
111            'create_user: user opt_create_user_with_mfa' => new UserSpecification($account, null, $this->identifications->factors($form->node(1))),
112            default => throw ImplementationGap::production($form),
113        };
114    }
115
116    /**
117     * Lowers an 8.0 alter_user_list.
118     *
119     * @return list<UserAlteration>
120     * @throws ImplementationGap When a production has no rule
121     */
122    public function altered(Node $list): array
123    {
124        $users = [];
125        foreach ($this->spine($list) as $item) {
126            $users[] = $this->alter($item);
127        }
128
129        return $users;
130    }
131
132    /**
133     * Lowers one 8.0 alter_user.
134     *
135     * @throws ImplementationGap When the production has no rule
136     */
137    public function alter(Node $user): UserAlteration
138    {
139        $form = $this->lowering->form($user);
140        $account = $this->lowering->users->account($form->node(0));
141        if (array_key_exists($form->signature, self::CHANGES)) {
142            $replace = self::CHANGES[$form->signature];
143            $identification = $this->identifications->identification($form->node(1));
144            $text = $replace === null ? null : $this->lowering->literals->text($form->node($replace));
145
146            return new UserSpecification($account, $identification, [], null, $text, $this->identifications->retain($form->node(count($form->node->children) - 1)));
147        }
148        if (isset(self::FACTORS[$form->signature])) {
149            return $this->factors($form, $account);
150        }
151
152        return match ($form->signature) {
153            'alter_user: user identified_with_plugin' => new UserSpecification($account, $this->identifications->identification($form->node(1))),
154            'alter_user: user opt_discard_old_password' => new UserSpecification($account, null, [], null, null, false, $this->identifications->discard($form->node(1))),
155            default => throw ImplementationGap::production($form),
156        };
157    }
158
159    /**
160     * Lowers the factor change forms of alter_user.
161     */
162    public function factors(Form $form, Account $account): FactorChange
163    {
164        [$action, $count] = self::FACTORS[$form->signature];
165        $width = $action === FactorAction::Drop ? 2 : 3;
166        $steps = [];
167        for ($index = 0; $index < $count; $index++) {
168            $start = 1 + $index * $width;
169            $factor = $this->identifications->factor($form->node($start + 1));
170            $steps[] = new FactorStep($factor, $action === FactorAction::Drop ? null : $this->identifications->identification($form->node($start + 2)));
171        }
172
173        return new FactorChange($account, $action, $steps);
174    }
175
176    /**
177     * Lowers a MySQL 5.x grant_list.
178     *
179     * @return non-empty-list<UserSpecification>
180     * @throws ImplementationGap When a production has no rule
181     */
182    public function granted(Node $list): array
183    {
184        $users = [];
185        foreach ($this->spine($list) as $item) {
186            $users[] = $this->grant($item);
187        }
188
189        return $users;
190    }
191
192    /**
193     * Lowers one MySQL 5.x grant_user.
194     *
195     * @throws ImplementationGap When the production has no rule
196     */
197    public function grant(Node $user): UserSpecification
198    {
199        $form = $this->lowering->form($user);
200        $account = $this->lowering->users->account($form->node(0));
201        $clauses = new ClauseRule($this->lowering);
202
203        return new UserSpecification($account, match ($form->signature) {
204            'grant_user: user' => null,
205            'grant_user: user IDENTIFIED_SYM BY TEXT_STRING' => new Identification(null, Credential::Password, $clauses->string($form, 3)),
206            'grant_user: user IDENTIFIED_SYM BY PASSWORD TEXT_STRING' => new Identification(null, Credential::PasswordHash, $clauses->string($form, 4)),
207            'grant_user: user IDENTIFIED_SYM WITH ident_or_text' => new Identification($this->lowering->names->identifier($form->node(3)), Credential::None),
208            'grant_user: user IDENTIFIED_SYM WITH ident_or_text AS TEXT_STRING_sys' => new Identification($this->lowering->names->identifier($form->node(3)), Credential::Hash, $this->lowering->literals->text($form->node(5))),
209            'grant_user: user IDENTIFIED_SYM WITH ident_or_text BY TEXT_STRING_sys' => new Identification($this->lowering->names->identifier($form->node(3)), Credential::Password, $this->lowering->literals->text($form->node(5))),
210            default => throw ImplementationGap::production($form),
211        });
212    }
213
214    /**
215     * Answers the items of a list production of this rule, in source order.
216     *
217     * @return non-empty-list<Node>
218     * @throws ImplementationGap When the production has no rule
219     */
220    public function spine(Node $list): array
221    {
222        $form = $this->lowering->form($list);
223        if (!isset(self::LISTS[$form->signature])) {
224            throw ImplementationGap::production($form);
225        }
226        $items = (new Lists())->items($list);
227        Check::invariant($items !== [], 'A list production holds at least one item.');
228
229        return $items;
230    }
231}
232