rob-revisited/ide/ui/js/symfony-security.js

614 lines
42 KiB
JavaScript

// The Security window (Symfony): config/packages/security.yaml as forms. Firewalls (in their order: pattern, host,
// provider, lazy, stateless, and the ways to log in: form_login, json_login, login_link, remember_me, logout, http_basic,
// custom authenticators, JWT when lexik/jwt-authentication-bundle is installed...), providers (entity, memory, chain,
// service), password hashers, role_hierarchy drawn as a graph, access_control as an ordered table with a tester ("which
// rule gets this URL / method / IP, and why not the ones before"), routes x roles ("who can access what", from
// access_control and the #[IsGranted] of the controllers, which it adds or removes), generators (user entity, login
// form, registration, reset password, voter, custom authenticator, JWT API) and `debug:firewall` through the Console
// window's runner. Mistakes are pointed out while editing (a rule hidden by an earlier one, a firewall without provider,
// a plaintext hasher...). Saving rewrites only the changed YAML nodes (comments stay), shown as a difference first.
// The PHP side: ide/src/Symfony/Security*.php.
import { backend } from './backend.js';
import { el, clear, icon, notify, t, dialog, debounce, prompt } from './ui.js';
import { reviewChanges, symfonyToolsStyle } from './symfony-diff.js';
const TABS = ['firewalls', 'providers', 'hashers', 'roles', 'access', 'routes', 'generate', 'debug'];
const FIREWALL_FIELDS = [['pattern', 'text', '^/'], ['host', 'text'], ['methods', 'list'], ['provider', 'provider'], ['lazy', 'bool'], ['stateless', 'bool'],
['security', 'bool'], ['context', 'text'], ['entry_point', 'text'], ['user_checker', 'text'], ['access_denied_url', 'text']];
// the ways to log in (and out) of a firewall, with their options; [name, kind, value given when it is switched on]
const AUTHENTICATORS = {
form_login: [['login_path', 'text', 'app_login'], ['check_path', 'text', 'app_login'], ['enable_csrf', 'bool', true], ['default_target_path', 'text'],
['always_use_default_target_path', 'bool'], ['username_parameter', 'text'], ['password_parameter', 'text'], ['use_referer', 'bool']],
json_login: [['check_path', 'text', '/api/login'], ['username_path', 'text'], ['password_path', 'text'], ['success_handler', 'text'], ['failure_handler', 'text']],
login_link: [['check_route', 'text', 'login_check'], ['signature_properties', 'list', ['id']], ['lifetime', 'int'], ['max_uses', 'int']],
http_basic: [['realm', 'text']],
remember_me: [['secret', 'text', '%kernel.secret%'], ['lifetime', 'int', 604800], ['path', 'text', '/'], ['always_remember_me', 'bool'], ['signature_properties', 'list']],
logout: [['path', 'text', 'app_logout'], ['target', 'text'], ['invalidate_session', 'bool'], ['clear_site_data', 'list']],
custom_authenticators: 'classes',
access_token: [['token_handler', 'text', 'App\\Security\\AccessTokenHandler'], ['token_extractors', 'list']],
login_throttling: [['max_attempts', 'int', 5], ['interval', 'text', '1 minute']],
switch_user: [['role', 'text', 'ROLE_ALLOWED_TO_SWITCH'], ['parameter', 'text']],
jwt: 'flag',
};
const ALGORITHMS = ['auto', 'bcrypt', 'sodium', 'argon2i', 'argon2id', 'native', 'plaintext', 'md5', 'sha512'];
const SPECIAL_ROLES = ['PUBLIC_ACCESS', 'IS_AUTHENTICATED', 'IS_AUTHENTICATED_FULLY', 'IS_AUTHENTICATED_REMEMBERED', 'ROLE_USER', 'ROLE_ADMIN'];
const list = (v) => (v === null || v === undefined || v === '' ? [] : Array.isArray(v) ? v.map(String) : String(v).split(',').map((s) => s.trim()).filter(Boolean));
const one = (l) => (l.length === 1 ? l[0] : l);
/** the words of a warning (codes of SecurityConfig::warnings) */
export function warningText(w) {
const p = w.params || {};
switch (w.code) {
case 'no-provider': return t('Firewall {firewall} logs users in but no user provider is declared.', p);
case 'ambiguous-provider': return t('Firewall {firewall} has no provider while {count} are declared: say which one it uses.', p);
case 'unknown-provider': return t('Firewall {firewall} uses the provider {provider}, which does not exist.', p);
case 'catch-all': return t('Firewall {firewall} has no pattern: it takes every request, so {next} is never used. Put it last.', p);
case 'plaintext': return t('{class} uses the {algorithm} hasher: passwords are not really hashed. Use auto (only tests may lower the cost).', p);
case 'shadowed': return t('Rule {rule} ({path}) never applies: rule {by} ({byPath}) matches all its URLs first.', p);
case 'maybe-shadowed': return t('Rule {rule} ({path}) may be hidden by rule {by} ({byPath}), which matches its URLs too.', p);
case 'unanchored': return t('Rule {rule}: {path} has no ^ and matches anywhere in the URL.', p);
case 'bad-regex': return t('Rule {rule}: {path} is not a valid regular expression.', p);
case 'cycle': return t('{role} inherits itself through role_hierarchy.', p);
case 'stateless-form': return t('Firewall {firewall} is stateless but logs in with a form or remember_me, which need a session.', p);
case 'security-false-auth': return t('Firewall {firewall} has security: false, so {keys} does nothing.', p);
default: return w.code;
}
}
export class SecurityPanel {
constructor(app) {
this.app = app;
this.node = el('div.sx-view');
this.tab = 'firewalls';
this.data = null;
this.draft = null;
this.warnings = [];
this.firewall = null;
this.tester = { path: '/admin', method: 'GET', ip: '127.0.0.1', host: 'localhost', result: null };
this.routes = null;
this.debug = { firewall: '', output: '', busy: false };
this.selectedRole = null;
this.check = debounce(() => this.recheck(), 250);
symfonyToolsStyle();
this.render();
app.editors.on('saved', (path) => { if (path === 'config/packages/security.yaml' && !this.dirty()) this.load(); });
}
title() { return t('Security'); }
actions() {
return [el('button', { title: t('Refresh'), onclick: () => this.load() }, icon('refresh'))];
}
shown() { if (!this.data) this.load(); }
async load() {
try {
this.data = await backend.invoke('security.read', {});
this.draft = structuredClone(this.data.security || {});
this.warnings = this.data.warnings || [];
this.routes = null;
} catch (e) { notify(e.message, 'error', { title: t('Security') }); }
this.render();
}
dirty() { return this.data && JSON.stringify(this.draft) !== JSON.stringify(this.data.security); }
changed() { this.check(); this.renderBar(); }
async recheck() {
try { this.warnings = await backend.invoke('security.check', { security: this.draft }); } catch { /* the draft is half typed */ }
this.renderWarnings();
this.renderTabs();
}
async save() {
try {
const r = await backend.invoke('security.preview', { security: this.draft });
if (await reviewChanges(this.app, r.files, { title: 'security.yaml' })) await this.load();
} catch (e) { notify(e.message, 'error', { title: t('Security') }); }
}
render() {
clear(this.node);
this.barNode = el('div.sx-bar');
this.tabsNode = el('div.sx-tabs');
this.warnNode = el('div', { style: { padding: '0 10px' } });
this.bodyNode = el('div.sx-body');
this.node.append(this.barNode, this.tabsNode, this.warnNode, this.bodyNode);
this.renderBar();
if (!this.data) { this.bodyNode.append(el('div.sx-empty', {}, t('Loading…'))); return; }
this.renderTabs();
this.renderWarnings();
this.renderBody();
}
renderBar() {
if (!this.barNode) return;
clear(this.barNode);
const d = this.data;
this.barNode.append(...[
el('span.sx-link', { onclick: () => this.app.editors.open('config/packages/security.yaml') }, 'config/packages/security.yaml'),
d && !d.exists ? el('span.sx-badge', {}, t('new file')) : null,
el('span', { style: { flex: 1 } }),
this.dirty() ? el('span.sx-dirty', {}, t('Not saved')) : null,
this.dirty() ? el('button.btn.small', { onclick: () => { this.draft = structuredClone(this.data.security); this.warnings = this.data.warnings; this.render(); } }, t('Revert')) : null,
el('button.btn.small.primary', { disabled: !this.dirty(), onclick: () => this.save() }, t('Review and save…'))].filter(Boolean));
if (d?.error) this.barNode.append(el('div.sx-warn.error', { style: { width: '100%' } }, icon('warning'), el('span', {}, d.error)));
}
renderTabs() {
clear(this.tabsNode);
const labels = { firewalls: t('Firewalls'), providers: t('Providers'), hashers: t('Password hashers'), roles: t('Roles'), access: t('Access control'),
routes: t('Who can access what'), generate: t('Generate'), debug: 'debug:firewall' };
const count = (tab) => this.warnings.filter((w) => ({ firewalls: 'firewalls', hashers: 'password_hashers', roles: 'role_hierarchy', access: 'access_control' })[tab] === w.section).length;
for (const id of TABS) {
const n = count(id);
this.tabsNode.append(el(`div.sx-tab${this.tab === id ? '.on' : ''}`, { 'data-tour': 'security-tab-' + id, onclick: () => { this.tab = id; this.renderTabs(); this.renderBody(); } }, labels[id], n ? el('span.sx-count', {}, `⚠${n}`) : null));
}
}
renderWarnings() {
clear(this.warnNode);
for (const w of this.warnings) {
this.warnNode.append(el(`div.sx-warn${w.level === 'error' ? '.error' : ''}`, { style: { cursor: 'pointer' }, onclick: () => {
this.tab = { firewalls: 'firewalls', password_hashers: 'hashers', role_hierarchy: 'roles', access_control: 'access' }[w.section] || this.tab;
if (w.section === 'firewalls' && w.key) this.firewall = w.key;
this.renderTabs(); this.renderBody();
} }, icon('warning'), el('span', {}, warningText(w))));
}
}
renderBody() {
clear(this.bodyNode);
const view = { firewalls: () => this.firewallsView(), providers: () => this.providersView(), hashers: () => this.hashersView(), roles: () => this.rolesView(),
access: () => this.accessView(), routes: () => this.routesView(), generate: () => this.generateView(), debug: () => this.debugView() }[this.tab];
this.bodyNode.append(view());
}
// ---- fields ----
field(obj, key, kind, { placeholder = '', onchange } = {}) {
const done = () => { this.changed(); onchange?.(); };
const v = obj?.[key];
const set = (x) => { if (x === undefined) delete obj[key]; else obj[key] = x; done(); };
if (kind === 'bool') {
return el('select.input', { onchange: (e) => set(e.target.value === '' ? undefined : e.target.value === 'true') },
el('option', { value: '' }, t('(default)')), el('option', { value: 'true', selected: v === true }, 'true'), el('option', { value: 'false', selected: v === false }, 'false'));
}
if (kind === 'int') return el('input.input', { type: 'number', value: v ?? '', placeholder, oninput: (e) => set(e.target.value === '' ? undefined : Number(e.target.value)) });
if (kind === 'list') return el('input.input', { value: list(v).join(', '), placeholder, oninput: (e) => set(e.target.value.trim() === '' ? undefined : one(list(e.target.value))) });
if (kind === 'provider') {
return el('select.input', { onchange: (e) => set(e.target.value || undefined) }, el('option', { value: '' }, t('(none)')),
...Object.keys(this.draft.providers || {}).map((p) => el('option', { value: p, selected: v === p }, p)));
}
return el('input.input', { value: v ?? '', placeholder, oninput: (e) => set(e.target.value === '' ? undefined : e.target.value) });
}
form(obj, fields) {
const f = el('div.sx-form');
for (const [key, kind, def] of fields) f.append(el('label', { title: key }, key), this.field(obj, key, kind, { placeholder: def !== undefined && typeof def !== 'boolean' ? String(def) : '' }));
return f;
}
// ---- firewalls ----
firewallsView() {
const fws = this.draft.firewalls ||= {};
const names = Object.keys(fws);
if (!this.firewall || !(this.firewall in fws)) this.firewall = names.find((n) => fws[n]?.security !== false) || names[0] || null;
const side = el('div.sx-list');
names.forEach((n, i) => side.append(el(`div.sx-item${n === this.firewall ? '.on' : ''}${fws[n]?.security === false ? '.off' : ''}`, { onclick: () => { this.firewall = n; this.renderBody(); } },
el('span.sx-grow', {}, n),
i > 0 ? el('button.sx-icon', { title: t('Move up'), onclick: (e) => { e.stopPropagation(); this.moveKey('firewalls', n, -1); } }, icon('collapse')) : null)));
side.append(el('button.btn.small', { onclick: () => this.addFirewall() }, icon('plus'), t('Firewall')));
const detail = el('div.sx-detail');
const fw = this.firewall ? (fws[this.firewall] ||= {}) : null;
if (fw) {
detail.append(el('div.sx-head', {}, el('h3', {}, this.firewall),
el('span.sx-link', { onclick: () => this.renameFirewall() }, t('Rename')),
el('span.sx-link', { onclick: () => { delete fws[this.firewall]; this.firewall = null; this.changed(); this.renderBody(); } }, t('Delete')),
this.app.project.capabilities?.console ? el('span.sx-link', { onclick: () => { this.debug.firewall = this.firewall; this.tab = 'debug'; this.renderTabs(); this.renderBody(); this.runDebug(); } }, 'debug:firewall') : null));
detail.append(this.form(fw, FIREWALL_FIELDS));
if (fw.security === false) detail.append(el('p.sx-muted', {}, t('security: false — this firewall lets everything through (assets, profiler).')));
detail.append(el('div.sx-section', {}, t('Authentication')));
for (const [key, spec] of Object.entries(AUTHENTICATORS)) {
if (key === 'jwt' && !this.data.bundles?.jwt && !('jwt' in fw)) continue;
detail.append(this.authBox(fw, key, spec));
}
} else detail.append(el('div.sx-empty', {}, t('No firewall. Add one, or generate a login form.')));
return el('div.sx-split', {}, side, detail);
}
authBox(fw, key, spec) {
const on = key in fw;
const box = el('div.sx-auth');
const toggle = el('input', { type: 'checkbox', checked: on, onclick: (e) => e.stopPropagation(), onchange: (e) => {
if (e.target.checked) {
if (spec === 'flag') fw[key] = null;
else if (spec === 'classes') fw[key] = [...(this.data.classes?.authenticators || []).slice(0, 1)];
else { const v = {}; for (const [k, , def] of spec) if (def !== undefined) v[k] = def; fw[key] = key === 'switch_user' && !Object.keys(v).length ? true : v; }
} else delete fw[key];
this.changed(); this.renderBody();
} });
const hint = { form_login: t('a login form (POST _username / _password)'), json_login: t('JSON login (APIs)'), login_link: t('passwordless links by e-mail'),
http_basic: t('HTTP basic authentication'), remember_me: t('stay logged in (cookie)'), logout: t('the logout route'), custom_authenticators: t('your own authenticator classes'),
access_token: t('Bearer tokens'), login_throttling: t('limit login attempts'), switch_user: t('impersonate users'), jwt: 'lexik/jwt-authentication-bundle' }[key];
box.append(el('div.sx-auth-head', { onclick: () => toggle.click() }, toggle, el('b', {}, key), el('span.sx-grow', {}, hint)));
if (!on) return box;
if (spec === 'flag') return box;
if (spec === 'classes') {
const values = list(fw[key]);
const known = [...new Set([...(this.data.classes?.authenticators || []), ...values])];
const f = el('div.sx-form');
for (const c of known) f.append(el('label.sx-full', { style: { display: 'flex', gap: '6px' } }, el('input', { type: 'checkbox', checked: values.includes(c), onchange: (e) => {
const now = list(fw[key]).filter((x) => x !== c);
fw[key] = e.target.checked ? [...now, c] : now;
this.changed();
} }), c));
const free = el('input.input', { placeholder: 'App\\Security\\MyAuthenticator' });
f.append(el('div.sx-row.sx-full', {}, free, el('button.btn.small', { onclick: () => { if (free.value.trim()) { fw[key] = [...list(fw[key]), free.value.trim()]; this.changed(); this.renderBody(); } } }, icon('plus'))));
box.append(f);
return box;
}
if (fw[key] === null || fw[key] === true) fw[key] = {};
box.append(this.form(fw[key], spec));
return box;
}
async addFirewall() {
const n = ((await prompt(t('Firewall name'), { value: 'api' })) || '').trim();
if (!n) return;
const fws = this.draft.firewalls ||= {};
// before the catch-all one (main), after dev
const entries = Object.entries(fws);
const at = entries.findIndex(([, f]) => f && f.pattern === undefined && f.security !== false);
entries.splice(at < 0 ? entries.length : at, 0, [n, { pattern: '^/' + n, lazy: true }]);
this.draft.firewalls = Object.fromEntries(entries);
this.firewall = n;
this.changed(); this.renderBody();
}
async renameFirewall() {
const n = ((await prompt(t('Firewall name'), { value: this.firewall })) || '').trim();
if (!n || n === this.firewall) return;
this.draft.firewalls = Object.fromEntries(Object.entries(this.draft.firewalls).map(([k, v]) => [k === this.firewall ? n : k, v]));
this.firewall = n;
this.changed(); this.renderBody();
}
moveKey(section, key, dir) {
const entries = Object.entries(this.draft[section]);
const i = entries.findIndex(([k]) => k === key);
const j = i + dir;
if (j < 0 || j >= entries.length) return;
[entries[i], entries[j]] = [entries[j], entries[i]];
this.draft[section] = Object.fromEntries(entries);
this.changed(); this.renderBody();
}
// ---- providers ----
providersView() {
const providers = this.draft.providers ||= {};
const box = el('div');
for (const [name, p] of Object.entries(providers)) {
const type = p && typeof p === 'object' ? ['entity', 'memory', 'chain', 'id', 'ldap'].find((k) => k in p) || 'id' : 'id';
const card = el('div.sx-member');
card.append(el('div.sx-member-head', {}, el('b', {}, name), el('span.sx-badge.blue', {}, type), el('span.sx-grow'),
el('button.sx-icon', { title: t('Remove'), onclick: () => { delete providers[name]; this.changed(); this.renderBody(); } }, icon('trash'))));
if (type === 'entity') {
const e = (p.entity ||= {});
const classes = this.data.classes?.users || [];
const f = el('div.sx-form');
f.append(el('label', {}, 'class'), el('input.input', { value: e.class || '', list: 'sx-users', oninput: (ev) => { e.class = ev.target.value; this.changed(); } }),
el('datalist', { id: 'sx-users' }, ...classes.map((c) => el('option', { value: c }))),
el('label', {}, 'property'), this.field(e, 'property', 'text', { placeholder: 'email' }),
el('label', {}, 'manager_name'), this.field(e, 'manager_name', 'text'));
card.append(f);
} else if (type === 'memory') {
if (!p.memory || typeof p.memory !== 'object') p.memory = {};
const users = (p.memory.users ||= {});
const tbl = el('table.sx-table', {}, el('tr', {}, el('th', {}, t('User')), el('th', {}, t('Password (hashed)')), el('th', {}, t('Roles')), el('th')));
for (const [u, info] of Object.entries(users)) {
tbl.append(el('tr', {}, el('td', {}, u), el('td', {}, this.field(info, 'password', 'text')), el('td', {}, this.field(info, 'roles', 'list')),
el('td', {}, el('button.sx-icon', { onclick: () => { delete users[u]; this.changed(); this.renderBody(); } }, icon('close')))));
}
const nu = el('input.input', { placeholder: 'admin' });
card.append(tbl, el('div.sx-row', {}, nu, el('button.btn.small', { onclick: () => { const u = nu.value.trim(); if (u) { users[u] = { password: '', roles: ['ROLE_USER'] }; this.changed(); this.renderBody(); } } }, icon('plus'), t('User'))),
el('p.sx-muted', {}, t('Hash passwords with: bin/console security:hash-password')));
} else if (type === 'chain') {
const c = (p.chain ||= {});
card.append(this.form(c, [['providers', 'list']]));
} else if (type === 'id') {
card.append(el('div.sx-form', {}, el('label', {}, 'id'), el('input.input', { value: p?.id ?? '', placeholder: 'App\\Security\\UserProvider', oninput: (e) => { providers[name] = { id: e.target.value }; this.changed(); } })));
} else card.append(el('pre.sx-pre', {}, JSON.stringify(p, null, 2)));
box.append(card);
}
const nameIn = el('input.input', { placeholder: 'app_user_provider' });
const typeIn = el('select.input', {}, ...['entity', 'memory', 'chain', 'id'].map((x) => el('option', { value: x }, x)));
box.append(el('div.sx-row', {}, nameIn, typeIn, el('button.btn.small', { onclick: () => {
const n = nameIn.value.trim();
if (!n) return;
providers[n] = { entity: { class: this.data.classes?.users?.[0] || 'App\\Entity\\User', property: 'email' }, memory: { memory: { users: {} } }, chain: { chain: { providers: [] } }, id: { id: '' } }[typeIn.value];
if (typeIn.value === 'memory') providers[n] = { memory: { users: {} } };
this.changed(); this.renderBody();
} }, icon('plus'), t('Provider'))));
return box;
}
// ---- hashers ----
hashersView() {
const hashers = this.draft.password_hashers ||= {};
const tbl = el('table.sx-table', {}, el('tr', {}, el('th', {}, t('Class')), el('th', {}, 'algorithm'), el('th', {}, 'cost'), el('th', {}, 'migrate_from'), el('th')));
for (const [cls, h] of Object.entries(hashers)) {
const obj = typeof h === 'string' ? { algorithm: h } : (h || {});
const write = () => { const keys = Object.keys(obj).filter((k) => obj[k] !== undefined); hashers[cls] = keys.length === 1 && keys[0] === 'algorithm' && typeof h === 'string' ? obj.algorithm : obj; this.changed(); };
const algo = el('select.input', { onchange: (e) => { obj.algorithm = e.target.value; write(); } }, ...ALGORITHMS.map((a) => el('option', { value: a, selected: obj.algorithm === a }, a)));
if (obj.algorithm && !ALGORITHMS.includes(obj.algorithm)) algo.append(el('option', { value: obj.algorithm, selected: true }, obj.algorithm));
tbl.append(el('tr', {}, el('td', { style: { fontFamily: 'var(--mono)', fontSize: '11.5px', wordBreak: 'break-all' } }, cls), el('td', {}, algo),
el('td', {}, el('input.input', { type: 'number', value: obj.cost ?? '', style: { width: '60px' }, oninput: (e) => { if (e.target.value === '') delete obj.cost; else obj.cost = Number(e.target.value); write(); } })),
el('td', {}, el('input.input', { value: list(obj.migrate_from).join(', '), oninput: (e) => { const l = list(e.target.value); if (l.length) obj.migrate_from = l; else delete obj.migrate_from; write(); } })),
el('td', {}, el('button.sx-icon', { onclick: () => { delete hashers[cls]; this.changed(); this.renderBody(); } }, icon('close')))));
}
const cls = el('input.input', { list: 'sx-hash-classes', placeholder: 'Symfony\\Component\\Security\\Core\\User\\PasswordAuthenticatedUserInterface' });
const box = el('div', {}, tbl, el('div.sx-row', {}, cls,
el('datalist', { id: 'sx-hash-classes' }, el('option', { value: 'Symfony\\Component\\Security\\Core\\User\\PasswordAuthenticatedUserInterface' }), ...(this.data.classes?.users || []).map((c) => el('option', { value: c }))),
el('button.btn.small', { onclick: () => { const c = cls.value.trim(); if (c) { hashers[c] = 'auto'; this.changed(); this.renderBody(); } } }, icon('plus'), t('Hasher'))));
if (this.data.envs?.test?.password_hashers) box.append(el('p.sx-muted', {}, t('when@test lowers the cost for the tests (kept as it is).')));
return box;
}
// ---- roles ----
rolesView() {
const h = this.draft.role_hierarchy ||= {};
const box = el('div');
box.append(el('p.sx-muted', {}, t('A role on the left holds the roles on its right (and theirs). Click a role of the graph to see what it reaches.')));
box.append(this.graph(h));
const tbl = el('table.sx-table', {}, el('tr', {}, el('th', {}, t('Role')), el('th', {}, t('Inherits')), el('th')));
for (const [role, kids] of Object.entries(h)) {
tbl.append(el('tr', {}, el('td', { style: { fontFamily: 'var(--mono)' } }, role),
el('td', {}, el('input.input', { value: list(kids).join(', '), oninput: (e) => { h[role] = one(list(e.target.value)); this.changed(); this.redrawGraph(); } })),
el('td', {}, el('button.sx-icon', { onclick: () => { delete h[role]; this.changed(); this.renderBody(); } }, icon('close')))));
}
const r = el('input.input', { placeholder: 'ROLE_ADMIN' });
const k = el('input.input', { placeholder: 'ROLE_USER, ROLE_EDITOR' });
box.append(tbl, el('div.sx-row', {}, r, k, el('button.btn.small', { onclick: () => {
const role = r.value.trim().toUpperCase();
if (!role) return;
h[role] = one([...new Set([...list(h[role]), ...list(k.value.toUpperCase())])]);
this.changed(); this.renderBody();
} }, icon('plus'), t('Role'))));
return box;
}
redrawGraph() { const old = this.bodyNode.querySelector('.sx-graph'); if (old) old.replaceWith(this.graph(this.draft.role_hierarchy || {})); }
/** role_hierarchy as a layered graph: parents above, the roles they hold below */
graph(h) {
const edges = [];
const nodes = new Set();
for (const [role, kids] of Object.entries(h)) { nodes.add(role); for (const k of list(kids)) { nodes.add(k); edges.push([role, k]); } }
const box = el('div.sx-graph');
if (!nodes.size) { box.append(el('div.sx-empty', {}, t('No role_hierarchy yet: add a role below.'))); return box; }
const depth = {};
const visit = (n, d, seen) => { if (seen.has(n)) return; depth[n] = Math.max(depth[n] ?? 0, d); for (const [a, b] of edges) if (a === n) visit(b, d + 1, new Set([...seen, n])); };
const children = new Set(edges.map((e) => e[1]));
for (const n of nodes) if (!children.has(n)) visit(n, 0, new Set());
for (const n of nodes) depth[n] ??= 0;
const layers = [];
for (const n of [...nodes].sort()) (layers[depth[n]] ||= []).push(n);
const reach = new Set();
if (this.selectedRole) { const go = (n) => { if (reach.has(n)) return; reach.add(n); for (const [a, b] of edges) if (a === n) go(b); }; go(this.selectedRole); }
const W = (n) => n.length * 7 + 18;
const pos = {};
const widths = layers.map((l) => l.reduce((s, n) => s + W(n) + 16, 0));
const width = Math.max(320, ...widths) + 20;
layers.forEach((l, d) => { let x = (width - widths[d]) / 2 + 8; for (const n of l) { pos[n] = { x, y: 14 + d * 62, w: W(n) }; x += W(n) + 16; } });
const height = layers.length * 62 + 10;
const NS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(NS, 'svg');
svg.setAttribute('width', width); svg.setAttribute('height', height);
const mk = (tag, attrs, parent = svg) => { const e = document.createElementNS(NS, tag); for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v); parent.append(e); return e; };
const defs = mk('defs', {});
const marker = mk('marker', { id: 'sx-arrow', viewBox: '0 0 8 8', refX: 7, refY: 4, markerWidth: 7, markerHeight: 7, orient: 'auto' }, defs);
mk('path', { d: 'M0,0 L8,4 L0,8 z', class: 'arrow' }, marker);
for (const [a, b] of edges) {
const p = pos[a]; const q = pos[b];
const x1 = p.x + p.w / 2; const y1 = p.y + 24; const x2 = q.x + q.w / 2; const y2 = q.y;
mk('path', { class: 'edge', d: `M${x1},${y1} C${x1},${(y1 + y2) / 2} ${x2},${(y1 + y2) / 2} ${x2},${y2 - 2}`, 'marker-end': 'url(#sx-arrow)' });
}
for (const n of nodes) {
const p = pos[n];
const g = mk('g', { class: `node${h[n] === undefined ? ' leaf' : ''}${reach.has(n) ? ' sel' : ''}`, style: 'cursor:pointer' });
g.addEventListener('click', () => { this.selectedRole = this.selectedRole === n ? null : n; this.redrawGraph(); });
mk('rect', { x: p.x, y: p.y, width: p.w, height: 24, rx: 5 }, g);
const tx = mk('text', { x: p.x + p.w / 2, y: p.y + 16, 'text-anchor': 'middle' }, g);
tx.textContent = n;
}
box.append(svg);
if (this.selectedRole) box.append(el('div.sx-muted', { style: { padding: '4px 8px' } }, t('{role} holds: {roles}', { role: this.selectedRole, roles: [...reach].join(', ') })));
return box;
}
// ---- access control ----
accessView() {
const rules = this.draft.access_control ||= [];
const box = el('div');
const s = this.tester;
const shadow = new Set(this.warnings.filter((w) => w.section === 'access_control' && w.code.includes('shadowed')).map((w) => w.key));
box.append(el('p.sx-muted', {}, t('The first rule that matches a request decides; the others are not looked at.')));
// the tester
const path = el('input.input', { value: s.path, placeholder: '/admin/users', oninput: (e) => { s.path = e.target.value; this.runTester(); } });
const method = el('select.input', { onchange: (e) => { s.method = e.target.value; this.runTester(); } }, ...['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map((m) => el('option', { selected: s.method === m }, m)));
const ip = el('input.input', { value: s.ip, placeholder: 'IP', oninput: (e) => { s.ip = e.target.value; this.runTester(); } });
const host = el('input.input', { value: s.host, placeholder: 'host', oninput: (e) => { s.host = e.target.value; this.runTester(); } });
box.append(el('div.sx-test', {}, el('b', {}, t('Which rule matches this request?')), el('div.sx-tester', {}, method, path, ip, host, el('button.btn.small', { onclick: () => this.runTester() }, icon('play'))),
this.testerResult = el('div.sx-trace')));
const tbl = el('table.sx-table');
tbl.append(el('tr', {}, el('th'), el('th', {}, 'path'), el('th', {}, 'roles'), el('th', {}, 'methods'), el('th', {}, 'ips'), el('th', {}, 'host'), el('th', {}, 'allow_if'), el('th')));
this.ruleRows = [];
rules.forEach((r, i) => {
const cell = (key, kind, ph) => el('td', {}, this.field(r, key, kind, { placeholder: ph, onchange: () => this.runTester() }));
const row = el(`tr${shadow.has(i) ? '.shadow' : ''}`, {}, el('td.sx-num', {}, String(i + 1)), cell('path', 'text', '^/admin'), cell('roles', 'list', 'ROLE_ADMIN'),
cell('methods', 'list', 'GET, POST'), cell('ips', 'list', ''), cell('host', 'text', ''), cell('allow_if', 'text', ''),
el('td', { style: { whiteSpace: 'nowrap' } }, i > 0 ? el('button.sx-icon', { title: t('Move up'), onclick: () => { [rules[i - 1], rules[i]] = [rules[i], rules[i - 1]]; this.changed(); this.renderBody(); } }, icon('collapse')) : null,
el('button.sx-icon', { title: t('Remove'), onclick: () => { rules.splice(i, 1); this.changed(); this.renderBody(); } }, icon('close'))));
this.ruleRows.push(row);
tbl.append(row);
});
box.append(tbl, el('div.sx-row', {}, el('button.btn.small', { onclick: () => { rules.push({ path: '^/', roles: 'PUBLIC_ACCESS' }); this.changed(); this.renderBody(); } }, icon('plus'), t('Rule')),
el('span.sx-muted', {}, t('roles: any of them is enough. Special ones: {roles}', { roles: SPECIAL_ROLES.slice(0, 4).join(', ') }))));
this.runTester();
return box;
}
async runTester() {
const s = this.tester;
if (!this.testerResult) return;
let r;
try { r = await backend.invoke('security.match', { rules: this.draft.access_control || [], request: { path: s.path || '/', method: s.method, ip: s.ip, host: s.host } }); } catch (e) { this.testerResult.textContent = e.message; return; }
const reason = { path: t('the path does not match'), host: t('another host'), methods: t('another method'), ips: t('another IP'), port: t('another port'), route: t('another route') };
clear(this.testerResult);
this.ruleRows?.forEach((row, i) => { row.classList.toggle('match', i === r.index); row.classList.toggle('skipped', r.index >= 0 && i > r.index); });
const rule = r.index >= 0 ? (this.draft.access_control || [])[r.index] : null;
this.testerResult.append(el('div', {}, r.firewall ? t('Firewall: {name}', { name: r.firewall }) : t('No firewall handles it'), ' · ',
rule ? el('b', {}, t('Rule {n}: roles {roles}', { n: r.index + 1, roles: list(rule.roles).join(', ') || '—' })) : el('b', {}, t('No rule: anyone gets in (unless the controller asks)'))));
for (const tr of r.trace.filter((x) => !x.matched)) this.testerResult.append(el('div', {}, `#${tr.index + 1}: ${tr.error || reason[tr.failed] || tr.failed}`));
}
// ---- routes x roles ----
routesView() {
const box = el('div');
box.append(el('p.sx-muted', {}, t('From access_control and the #[IsGranted] of the controllers (the edited config, not yet saved, included). voter: an attribute a voter decides; expr: an expression.')));
const holder = el('div', {}, t('Loading…'));
box.append(holder);
backend.invoke('security.routes', { security: this.draft }).then((m) => {
clear(holder);
if (!m.rows.length) { holder.append(el('div.sx-empty', {}, t('No route with #[Route] in src/Controller.'))); return; }
const tbl = el('table.sx-table.sx-matrix');
tbl.append(el('tr', {}, el('th', {}, t('Route')), el('th', {}, 'path'), el('th', {}, t('Firewall')), el('th', {}, t('Rule')), el('th.role', {}, t('anonymous')), ...m.roles.map((r) => el('th.role', {}, r)), el('th', {}, '#[IsGranted]')));
for (const row of m.rows) {
const grants = row.grants.filter((g) => g.level !== 'call');
tbl.append(el('tr', {},
el('td', {}, el('span.sx-link', { onclick: () => this.app.editors.open(row.file, { line: row.line }) }, row.name)),
el('td.path', {}, (row.methods.length ? row.methods.join('|') + ' ' : '') + row.path),
el('td', {}, row.firewall || '—', row.off ? el('span.sx-muted', {}, ' (off)') : null),
el('td', {}, row.rule >= 0 ? `#${row.rule + 1}` : '—'),
...row.cells.map((c) => el(`td.cell.${c}`, { title: c }, { yes: '✓', no: '✗', voter: 'voter', expression: 'expr' }[c])),
el('td', { style: { whiteSpace: 'nowrap' } }, ...grants.map((g) => el('span.sx-chip', { title: g.level }, el('span', {}, g.attribute + (g.subject ? ` (${g.subject})` : '')),
el('button', { title: t('Remove'), onclick: () => this.isGranted(row, { action: 'remove', method: g.level === 'class' ? '' : row.action, index: g.index }) }, icon('close')))),
el('button.sx-icon', { title: t('Add #[IsGranted]'), onclick: () => this.addIsGranted(row, m.roles) }, icon('plus')))));
}
holder.append(el('div', { style: { overflowX: 'auto' } }, tbl));
}, (e) => { clear(holder); holder.append(el('div.sx-warn.error', {}, icon('warning'), e.message)); });
return box;
}
addIsGranted(row, roles) {
const attrs = [...new Set([...roles, ...SPECIAL_ROLES])];
const attr = el('input.input', { list: 'sx-attrs', value: 'ROLE_USER' });
const subject = el('input.input', { placeholder: t('(optional) an argument of the action, e.g. post') });
const where = el('select.input', {}, el('option', { value: 'action' }, t('This action: {name}', { name: row.action })), el('option', { value: 'class' }, t('The whole controller')));
dialog({
title: '#[IsGranted]',
body: el('div.sx-form', {}, el('label', {}, t('Attribute')), attr, el('datalist', { id: 'sx-attrs' }, ...attrs.map((a) => el('option', { value: a }))),
el('label', {}, 'subject'), subject, el('label', {}, t('On')), where),
buttons: [{ label: 'Cancel' }, { label: t('Preview'), primary: true, action: () => this.isGranted(row, { action: 'add', method: where.value === 'class' ? '' : row.action, attribute: attr.value.trim(), subject: subject.value.trim() || undefined }) }],
});
}
async isGranted(row, p) {
try {
const r = await backend.invoke('security.isGranted', { file: row.file, ...p });
if (await reviewChanges(this.app, r.files, { title: row.class })) this.renderBody();
} catch (e) { notify(e.message, 'error', { title: '#[IsGranted]' }); }
}
// ---- generators ----
generateView() {
const b = this.data.bundles || {};
const cards = [
['user', t('User entity'), t('A Doctrine entity with an identifier, roles and a hashed password, its repository, and the entity provider.'), b.doctrine ? null : t('needs doctrine/orm')],
['login', t('Login form'), t('SecurityController (login, logout), its template, form_login or an authenticator class, remember me.'), null],
['registration', t('Registration form'), t('A form type, a controller that hashes the password and saves the user, a template.'), b.doctrine ? null : t('needs doctrine/orm')],
['reset', t('Reset password'), t('Request, e-mail, check and reset pages with symfonycasts/reset-password-bundle.'), b.resetPassword ? null : t('needs symfonycasts/reset-password-bundle')],
['voter', t('Voter'), t('Decides attributes like POST_EDIT on a subject: supports() and voteOnAttribute() ready to fill.'), null],
['authenticator', t('Custom authenticator'), t('An authenticator class (an API token header) added to a firewall.'), null],
['jwt', t('JWT API'), t('login and api firewalls (json_login giving a token, jwt), their access_control rules and the login route.'), b.jwt ? null : t('needs lexik/jwt-authentication-bundle')],
];
const box = el('div');
if (this.dirty()) box.append(el('div.sx-warn', {}, icon('warning'), el('span', {}, t('Save or revert your changes first: generators start from the file.'))));
box.append(el('div.sx-cards', {}, ...cards.map(([id, title, text, missing]) => el(`div.sx-card${missing ? '.disabled' : ''}`, { onclick: () => !missing && !this.dirty() && this.generator(id) },
el('b', {}, title), el('small', {}, text), missing ? el('span.sx-badge.red', {}, missing) : null))));
return box;
}
generator(kind) {
const users = this.data.classes?.users || [];
const fws = Object.keys(this.draft.firewalls || {}).filter((n) => this.draft.firewalls[n]?.security !== false);
const spec = {};
const F = [];
const text = (key, label, def) => { spec[key] = def; F.push(el('label', {}, label), el('input.input', { value: def, oninput: (e) => { spec[key] = e.target.value.trim(); } })); };
const check = (key, label, def) => { spec[key] = def; F.push(el('label', {}, label), el('input', { type: 'checkbox', checked: def, style: { justifySelf: 'start' }, onchange: (e) => { spec[key] = e.target.checked; } })); };
const pick = (key, label, options, def) => { spec[key] = def; F.push(el('label', {}, label), el('select.input', { onchange: (e) => { spec[key] = e.target.value; } }, ...options.map((o) => el('option', { value: o, selected: o === def }, o)))); };
const userPick = () => { if (users.length) pick('userClass', t('User class'), users, users[0]); else text('userClass', t('User class'), 'App\\Entity\\User'); };
const title = { user: t('User entity'), login: t('Login form'), registration: t('Registration form'), reset: t('Reset password'), voter: t('Voter'), authenticator: t('Custom authenticator'), jwt: t('JWT API') }[kind];
if (kind === 'user') { text('class', t('Class name'), 'User'); text('identifier', t('Identifier property'), 'email'); check('password', t('Passwords (hashed)'), true); }
if (kind === 'login') {
pick('firewall', t('Firewall'), fws.length ? fws : ['main'], fws.includes('main') ? 'main' : fws[0] || 'main');
text('controller', t('Controller'), 'SecurityController'); text('identifierLabel', t('Identifier label'), 'Email'); text('target', t('After login, go to'), '/');
check('authenticator', t('An authenticator class instead of form_login'), false); check('rememberMe', 'remember_me', true); check('logout', 'logout', true);
}
if (kind === 'registration') { userPick(); text('identifier', t('Identifier property'), 'email'); text('redirect', t('After registering, go to the route'), 'app_login'); }
if (kind === 'reset') { userPick(); text('identifier', t('Identifier property'), 'email'); text('from', t('Sender e-mail'), '[email protected]'); text('fromName', t('Sender name'), 'Website'); text('redirect', t('After the reset, go to the route'), 'app_login'); }
if (kind === 'voter') {
text('name', t('Name'), 'PostVoter');
spec.attributes = ['POST_VIEW', 'POST_EDIT'];
F.push(el('label', {}, t('Attributes')), el('input.input', { value: spec.attributes.join(', '), oninput: (e) => { spec.attributes = list(e.target.value); } }));
spec.subject = '';
F.push(el('label', {}, t('Subject class')), el('select.input', { onchange: (e) => { spec.subject = e.target.value; } }, el('option', { value: '' }, t('(any)')), ...(this.data.classes?.entities || []).map((c) => el('option', { value: c }, c))));
}
if (kind === 'authenticator') { text('name', t('Name'), 'ApiTokenAuthenticator'); text('header', t('Token header'), 'X-AUTH-TOKEN'); pick('firewall', t('Firewall'), fws.length ? fws : ['main'], fws.includes('main') ? 'main' : fws[0] || 'main'); }
if (kind === 'jwt') { text('prefix', t('API prefix'), '/api'); text('usernamePath', 'username_path', 'email'); }
dialog({
title,
body: el('div.sx-form', {}, ...F),
buttons: [{ label: 'Cancel' }, { label: t('Preview'), primary: true, action: async () => {
const r = await backend.invoke('security.generate', { kind, spec });
if (await reviewChanges(this.app, r.files, { title })) await this.load();
} }],
});
}
// ---- debug:firewall ----
debugView() {
const d = this.debug;
const box = el('div');
if (!this.app.project.capabilities?.console) { box.append(el('div.sx-empty', {}, t('This project has no bin/console.'))); return box; }
const names = Object.keys(this.data.security?.firewalls || {});
const sel = el('select.input', { onchange: (e) => { d.firewall = e.target.value; } }, el('option', { value: '' }, t('(all the firewalls)')), ...names.map((n) => el('option', { value: n, selected: d.firewall === n }, n)));
box.append(el('div.sx-row', {}, sel, el('button.btn.small.primary', { disabled: d.busy, onclick: () => this.runDebug() }, icon('play'), d.busy ? t('Running…') : t('Run'))),
el('p.sx-muted', {}, t('bin/console debug:firewall, run where the Console window runs commands (the saved file).')));
if (d.output) box.append(el('pre.sx-pre', { style: { maxHeight: 'none' } }, d.output));
return box;
}
async runDebug() {
const d = this.debug;
d.busy = true; this.renderBody();
try {
const r = await backend.invoke('console.run', { argv: ['debug:firewall', ...(d.firewall ? [d.firewall] : []), ...(d.firewall ? ['--events'] : [])] });
d.output = r.output || `exit ${r.code}`;
} catch (e) { d.output = e.message; }
d.busy = false;
if (this.tab === 'debug') this.renderBody();
}
}