winzik/docs/ide/validation-security.md

85 lines
7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Validation and security
Symfony projects (with `symfony/validator`, `symfony/security-bundle` or a `config/packages/security.yaml`) get two windows on the
right tool bar: **Validation** and **Security** (also Tools > Validation Constraints, Tools > Security). They work on the project's
files, on the desktop and on the web. "Test a value" and `debug:firewall` need `bin/console`: they run where the
[Symfony console](symfony-console.md) window runs commands (the site's container or the computer's PHP).
**Nothing is written without being shown first**: every change opens a window with the difference of each file (new files against
nothing); **Apply** writes them, open tabs reload. A file open with unsaved changes is refused (save it first), and so is a file
that changed on disk in the meantime.
## Validation
![The Validation window](images/validation.png)
The window follows the editor: open an entity or a DTO and its constraints appear (the list at the top has the entities, the DTOs /
models and the other classes of `src/` that have constraints).
- **Class constraints** (UniqueEntity, Callback, Expression, GroupSequence...), then each property, promoted constructor parameter
and getter (`get…`, `is…`, `has…`) with its constraints as chips.
- **Click a chip** to edit its options. Each option has the field of its kind: messages, numbers, true / false / default, lists
(`a, b, c`), choices (Email's `mode`, Isbn's `type`...), regular expressions (checked as you type), values, `groups`, `payload`. Code
that is not a plain value (`self::MAX`) is kept as it is. Nested constraints (All, Sequentially, AtLeastOneOf, When's
`constraints` / `otherwise`, Collection's fields) are chips edited the same way. Empty fields keep Symfony's defaults.
- **+** adds a constraint from Symfony's whole catalogue (by family: basic, strings, comparisons, numbers, dates, choices, files,
finance, collections, the class, Doctrine's UniqueEntity) or one of the project's own constraints. The arrow moves a chip up, × removes it.
- **Suggestions** (dashed chips) come from the Doctrine mapping: `Length(max)` for a column length, `NotBlank` for a string that
cannot be null, `Email` for an e-mail property, `UniqueEntity` for a unique column. One click adds it.
- Constraints declared in `config/validator/*.yaml` or `*.xml` are shown beside (yellow chips, read-only); a click opens the line.
- **Validation groups** used by the class, and its **GroupSequence**: groups in order, the next one validated only when the previous
one has no violation (saved as the class's `#[Assert\GroupSequence]`).
- **New constraint…** writes a constraint of your own: a `Constraint` class (a PHP attribute, its options as constructor parameters,
its message, property / class / both) and its `ConstraintValidator` to fill in, or a **Compound** of chosen constraints.
- **Test a value**: one property's value, or the whole object from sample values (converted to the property types), with the groups
you tick, validated by the project's own validator. The first time, a small dev-only command is offered (as a difference):
`src/Command/JumphpValidateCommand.php` (`jumphp:validate`, hidden, `#[When(env: 'dev')]`; delete it when you do not want it).
The violations come back with their path, message and constraint.
The PHP file changes only where the attribute is: the rest of the file stays byte for byte (comments, spacing); a missing
`use Symfony\Component\Validator\Constraints as Assert;` is added.
## Security
![The roles graph](images/security-roles.png)
The tabs:
- **Firewalls**, in their order (the first that matches a request handles it): move, add (put before the catch-all one), rename,
delete. Each one: pattern, host, methods, provider, lazy, stateless, security, context, entry point, user checker, access denied
URL, and the ways to log in, each switched on and set up: `form_login`, `json_login`, `login_link`, `http_basic`, `remember_me`,
`logout`, custom authenticators (the project's classes are offered), `access_token`, `login_throttling`, `switch_user`, and `jwt`
when lexik/jwt-authentication-bundle is installed. A link runs `debug:firewall` on it.
- **Providers**: entity (the project's user classes are offered), memory users, chain, a service id.
- **Password hashers**: class, algorithm, cost, `migrate_from`. `when@test` (lower costs for the tests) is kept as it is.
- **Roles**: `role_hierarchy` as a table and as a graph; click a role to see every role it holds.
- **Access control**: the rules as an ordered table (path, roles, methods, IPs, host, allow_if), and a **tester**: type a method,
path, IP and host, the firewall and the first matching rule are shown (green), with why each rule above did not match.
- **Who can access what**: every route of `src/Controller` (`#[Route]`) with its firewall and access_control rule, and for an
anonymous visitor and each role: ✓, ✗, `voter` (an attribute a voter decides) or `expr` (an expression). It reads access_control,
`#[IsGranted]` on the controller or the action, and `denyAccessUnlessGranted()`. **+** adds an `#[IsGranted]` (a role or a voter
attribute, an optional subject, on the action or the whole controller); × removes one.
- **Generate**: User entity (identifier, roles, hashed password, repository, entity provider); login form (SecurityController, its
template, `form_login` or a LoginFormAuthenticator class, logout, remember me); registration form; reset password (with
symfonycasts/reset-password-bundle); voter (attributes and subject class); custom authenticator (an API token header); JWT API
(with lexik/jwt-authentication-bundle: `login` and `api` firewalls, rules, the login route).
- **debug:firewall**: the console's own view of a firewall (the saved file).
![The access_control tester](images/security-access.png)
Mistakes are pointed out while you edit (a click goes to the tab): a rule that never applies because an earlier one takes all its
URLs, a firewall without provider (or with an unknown one, or with none while several exist), a firewall without pattern before
others, a plaintext or md5 hasher, a path without `^`, a bad regular expression, a role inheriting itself, a stateless firewall with
a form login, `security: false` with authenticators.
**Review and save…** rewrites only what changed in `security.yaml`: a changed value keeps its line and its comment, a new key goes at
the end of its section, removed keys take their lines, reordered firewalls move with their comments, `{ memory: null }` stays on one
line, rules are written `- { path: ^/admin, roles: ROLE_ADMIN }` (under the recipe's commented examples).
## Limits
- Only PHP attributes are edited; YAML / XML mappings are shown, not changed.
- Routes are read from `#[Route]` attributes of `src/Controller` (not from `config/routes/*.yaml`).
- The table of who can access what takes an access_control rule's roles as "any of them" and cannot know what a voter decides.
- `when@<env>` blocks of security.yaml are kept but not edited by the forms.
- Generators start from the saved file: save or revert your edits first.