poad 2.10.1 → 2.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/global/run.js +24 -14
- package/package.json +1 -1
- package/project/cli.js +1 -0
- package/project/kc.js +47 -0
- package/utils/keycloak.js +328 -68
- package/utils/services.js +16 -19
package/global/run.js
CHANGED
|
@@ -101,16 +101,19 @@ module.exports = async (args = {}) => {
|
|
|
101
101
|
|
|
102
102
|
if (!(await pullIfMissing(docker, kc.IMAGE))) return;
|
|
103
103
|
|
|
104
|
-
|
|
105
|
-
|
|
104
|
+
// Identifiants des utilisateurs du Keycloak qui tourne (projets antérieurs),
|
|
105
|
+
// puis jeu de test du projet (poad/keycloak.json) et secrets (data/keycloak)
|
|
106
|
+
await kc.adoptRunningIds(root, config);
|
|
107
|
+
const project = kc.loadProject(root, config);
|
|
108
|
+
const { secrets } = project;
|
|
106
109
|
// Dossier à part : Keycloak importe tous les fichiers JSON qu'il y trouve
|
|
107
|
-
const importDir = path.join(
|
|
110
|
+
const importDir = path.join(kc.dataDir(root), 'import');
|
|
108
111
|
fs.mkdirSync(importDir, { recursive: true });
|
|
109
112
|
fs.chmodSync(importDir, 0o755);
|
|
110
|
-
fs.
|
|
111
|
-
|
|
112
|
-
});
|
|
113
|
-
fs.chmodSync(
|
|
113
|
+
for (const old of fs.readdirSync(importDir)) fs.rmSync(path.join(importDir, old));
|
|
114
|
+
const realmFile = path.join(importDir, `${project.realm}-realm.json`);
|
|
115
|
+
fs.writeFileSync(realmFile, JSON.stringify(kc.realmOf(config, project), null, 2) + '\n', { mode: 0o644 });
|
|
116
|
+
fs.chmodSync(realmFile, 0o644);
|
|
114
117
|
|
|
115
118
|
const name = kc.containerName(config);
|
|
116
119
|
const progress = ora('Starting Keycloak').start();
|
|
@@ -139,7 +142,7 @@ module.exports = async (args = {}) => {
|
|
|
139
142
|
});
|
|
140
143
|
await container.start();
|
|
141
144
|
|
|
142
|
-
const issuer = `http://localhost:${port}/realms/${
|
|
145
|
+
const issuer = `http://localhost:${port}/realms/${project.realm}`;
|
|
143
146
|
for (let i = 0; ; i++) {
|
|
144
147
|
const ok = await fetch(`${issuer}/.well-known/openid-configuration`).then(
|
|
145
148
|
(r) => r.ok,
|
|
@@ -149,7 +152,10 @@ module.exports = async (args = {}) => {
|
|
|
149
152
|
if (i > 120) throw new Error(`Keycloak does not answer after 120 s (docker logs ${name})`);
|
|
150
153
|
await new Promise((r) => setTimeout(r, 1000));
|
|
151
154
|
}
|
|
152
|
-
kc.register(config,
|
|
155
|
+
kc.register(config, project);
|
|
156
|
+
await kc.enableUserAttributes(port, secrets, project.realm).catch(() => {
|
|
157
|
+
/* sans effet sur la connexion : seuls les attributs ajoutés dans la console seraient perdus */
|
|
158
|
+
});
|
|
153
159
|
progress.succeed(chalk.bold('Keycloak started.'));
|
|
154
160
|
} catch (err) {
|
|
155
161
|
progress.fail(chalk.redBright(`Keycloak failed to start: ${err.message}`));
|
|
@@ -157,15 +163,19 @@ module.exports = async (args = {}) => {
|
|
|
157
163
|
}
|
|
158
164
|
|
|
159
165
|
console.log(' ');
|
|
166
|
+
const base = `http://localhost:${port}`;
|
|
160
167
|
const info = {
|
|
161
|
-
'Keycloak URL':
|
|
162
|
-
Issuer:
|
|
163
|
-
'Admin console':
|
|
168
|
+
'Keycloak URL': base,
|
|
169
|
+
Issuer: `${base}/realms/${project.realm}`,
|
|
170
|
+
'Admin console': `${base}/admin (admin ${secrets.admin_password})`,
|
|
164
171
|
Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
|
|
165
|
-
'Test users':
|
|
172
|
+
'Test users': project.users.map(
|
|
173
|
+
(u) => `${u.username.padEnd(6)} ${u.password} ${u.email}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
|
|
174
|
+
),
|
|
175
|
+
'Test set': path.relative(process.cwd(), project.fixturePath),
|
|
166
176
|
};
|
|
167
177
|
console.log(prettyoutput(info));
|
|
168
|
-
console.log(chalk.grey(` The realm is re-imported on each run: changes made in the admin console
|
|
178
|
+
console.log(chalk.grey(` The realm is re-imported from ${path.relative(process.cwd(), project.fixturePath)} on each run: "poad kc export" saves changes made in the admin console.`));
|
|
169
179
|
console.log(' ');
|
|
170
180
|
}
|
|
171
181
|
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
module.exports = {
|
|
10
10
|
info: `Information about your project`,
|
|
11
|
+
kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
|
|
11
12
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
12
13
|
gen: {
|
|
13
14
|
description: 'Génération automatique des éléments clés pour votre projet',
|
package/project/kc.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// poad kc export réécrit poad/keycloak.json depuis le Keycloak qui tourne
|
|
2
|
+
// (rôles, groupes, utilisateurs créés ou modifiés dans la console)
|
|
3
|
+
// poad kc affiche le jeu de test du projet
|
|
4
|
+
module.exports = async (args = {}) => {
|
|
5
|
+
const chalk = require('chalk-v2');
|
|
6
|
+
const toml = require('toml');
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const Docker = require('dockerode');
|
|
10
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
11
|
+
const kc = require('../utils/keycloak');
|
|
12
|
+
const { containerState } = require('../utils/services');
|
|
13
|
+
|
|
14
|
+
const root = findPoadDir(process.cwd());
|
|
15
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
16
|
+
const config = toml.parse(fs.readFileSync(root, 'utf-8'));
|
|
17
|
+
console.log(' ');
|
|
18
|
+
|
|
19
|
+
if (args.export) {
|
|
20
|
+
if (!(config.keycloak && config.keycloak.port) || (await containerState(new Docker(), kc.containerName(config))) !== 'running') {
|
|
21
|
+
return console.log(chalk.redBright('Keycloak is not running: "poad run kc" first.'));
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
const { file, users, fresh } = await kc.exportRealm(root, config);
|
|
25
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), file))} : ${users} user(s) exported`);
|
|
26
|
+
if (fresh.length) {
|
|
27
|
+
console.log(chalk.yellowBright(` New password for ${fresh.join(', ')} (unknown to the file): applied at the next "poad run kc".`));
|
|
28
|
+
}
|
|
29
|
+
} catch (err) {
|
|
30
|
+
console.log(chalk.redBright(`Export failed: ${err.message}`));
|
|
31
|
+
}
|
|
32
|
+
console.log(' ');
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const project = kc.loadProject(root, config, { create: false });
|
|
37
|
+
if (!project) return console.log(chalk.grey(' No Keycloak test set yet: "poad run kc" creates poad/keycloak.json.'));
|
|
38
|
+
console.log(`${chalk.bold('Keycloak test set')} ${chalk.grey(path.relative(process.cwd(), project.fixturePath))} realm ${chalk.bold(project.realm)}`);
|
|
39
|
+
console.log(' ');
|
|
40
|
+
for (const u of project.users) {
|
|
41
|
+
const flags = [u.roles.length ? `[${u.roles.join(', ')}]` : '', u.emailVerified ? '' : '(email not verified)'].filter(Boolean).join(' ');
|
|
42
|
+
console.log(` ${chalk.bold(u.username.padEnd(10))} ${u.password} ${u.email || ''} ${chalk.grey(flags)}`);
|
|
43
|
+
}
|
|
44
|
+
console.log(' ');
|
|
45
|
+
console.log(chalk.grey(' Edit the file then "poad run kc" to apply it; "poad kc export" saves changes made in the admin console.'));
|
|
46
|
+
console.log(' ');
|
|
47
|
+
};
|
package/utils/keycloak.js
CHANGED
|
@@ -3,11 +3,19 @@
|
|
|
3
3
|
//
|
|
4
4
|
// - un conteneur par projet : <project_uuid>-keycloak ;
|
|
5
5
|
// - port choisi au premier lancement, gardé dans config.toml ([keycloak]) ;
|
|
6
|
-
// - realm
|
|
7
|
-
//
|
|
6
|
+
// - un realm au nom du projet (project_id), client « poad » ;
|
|
7
|
+
// - LE JEU DE TEST DU PROJET est dans poad/keycloak.json, VERSIONNÉ : rôles,
|
|
8
|
+
// groupes, utilisateurs (mots de passe en clair : comptes de test). Toute
|
|
9
|
+
// l'équipe a les mêmes comptes ; `poad kc export` y réécrit l'état du
|
|
10
|
+
// Keycloak qui tourne (comptes créés dans la console d'admin) ;
|
|
11
|
+
// - les secrets du realm restent hors git, dans poad/data/keycloak/users.json :
|
|
12
|
+
// clé de signature, secret du client, mot de passe admin, identifiants
|
|
13
|
+
// Keycloak des utilisateurs (stables : sans eux, chaque réimport change le
|
|
14
|
+
// « sub » et poad ne reconnaît plus les identités déjà liées) ;
|
|
8
15
|
// - le realm est réimporté à chaque lancement (Keycloak en mode dev, sans
|
|
9
|
-
// persistance)
|
|
10
|
-
// -
|
|
16
|
+
// persistance) ;
|
|
17
|
+
// - les rôles du realm arrivent dans la claim « roles » des jetons ; le
|
|
18
|
+
// fournisseur « keycloak » est déclaré au projet avec roles_claim: "roles".
|
|
11
19
|
//
|
|
12
20
|
// Le navigateur joint Keycloak par http://localhost:<port>, l'engine par le
|
|
13
21
|
// réseau du projet, sous le nom « keycloak » (http://keycloak:8080, option
|
|
@@ -20,16 +28,37 @@ const crypto = require('crypto');
|
|
|
20
28
|
const { execFileSync } = require('child_process');
|
|
21
29
|
|
|
22
30
|
const IMAGE = 'quay.io/keycloak/keycloak:26.0.7';
|
|
23
|
-
const REALM = 'poad';
|
|
24
31
|
const CLIENT = 'poad';
|
|
25
32
|
const PROVIDER = 'keycloak';
|
|
26
33
|
const NAMES = ['keycloak', 'kc'];
|
|
27
34
|
const ALIAS = 'keycloak';
|
|
35
|
+
const ROLES_CLAIM = 'roles';
|
|
28
36
|
|
|
29
37
|
const containerName = (config) => `${config.project_uuid}-keycloak`;
|
|
30
38
|
const dataDir = (root) => path.join(path.dirname(root), 'data', 'keycloak');
|
|
39
|
+
/** Jeu de test versionné du projet : poad/keycloak.json */
|
|
40
|
+
const fixtureFile = (root) => path.join(path.dirname(root), 'keycloak.json');
|
|
31
41
|
const random = (n) => crypto.randomBytes(n).toString('base64url');
|
|
32
42
|
|
|
43
|
+
/** Realm du projet : celui de keycloak.json, sinon le nom du projet */
|
|
44
|
+
const slug = (s) =>
|
|
45
|
+
String(s || 'poad')
|
|
46
|
+
.normalize('NFD')
|
|
47
|
+
.replace(/[̀-ͯ]/g, '')
|
|
48
|
+
.toLowerCase()
|
|
49
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
50
|
+
.replace(/^-+|-+$/g, '') || 'poad';
|
|
51
|
+
const realmName = (config, fixture) => (fixture && fixture.realm) || slug(config.project_id);
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Mot de passe à recopier : lettres et chiffres seulement. Un « - » ou un
|
|
55
|
+
* « _ » coupe la sélection au double-clic dans un terminal, et le mot de
|
|
56
|
+
* passe collé est alors tronqué.
|
|
57
|
+
*/
|
|
58
|
+
const ALNUM = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
|
|
59
|
+
const typeable = (n) => Array.from({ length: n }, () => ALNUM[crypto.randomInt(ALNUM.length)]).join('');
|
|
60
|
+
const isTypeable = (p) => typeof p === 'string' && /^[A-Za-z0-9]+$/.test(p);
|
|
61
|
+
|
|
33
62
|
/** Le drapeau désigne-t-il Keycloak ? ({ kc: true }, { keycloak: true }) */
|
|
34
63
|
const wanted = (args = {}) => NAMES.some((n) => args[n]);
|
|
35
64
|
|
|
@@ -60,73 +89,296 @@ const savePort = (root, port) => {
|
|
|
60
89
|
const rsaKey = () =>
|
|
61
90
|
crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' });
|
|
62
91
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
92
|
+
const writeJson = (file, data, mode) => {
|
|
93
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
94
|
+
fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n', mode ? { mode } : undefined);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const capitalize = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);
|
|
98
|
+
|
|
99
|
+
/** Jeu de test par défaut : deux rôles, alice administratrice, bob utilisateur non vérifié */
|
|
100
|
+
const defaultFixture = (realm, old = []) => {
|
|
101
|
+
const pass = (name) => {
|
|
102
|
+
const p = (old.find((u) => u.username === name) || {}).password;
|
|
103
|
+
return isTypeable(p) ? p : typeable(12);
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
$comment:
|
|
107
|
+
'Comptes de test Keycloak du projet (poad run kc). Fichier versionné : mots de passe en clair, pour le test seulement. `poad kc export` réécrit ce fichier depuis le Keycloak qui tourne.',
|
|
108
|
+
realm,
|
|
109
|
+
roles: ['admin', 'user'],
|
|
110
|
+
groups: [],
|
|
82
111
|
users: [
|
|
83
|
-
{ username: 'alice', email: 'alice@poad.test', password:
|
|
84
|
-
{ username: 'bob', email: 'bob@poad.test', password:
|
|
112
|
+
{ username: 'alice', email: 'alice@poad.test', firstName: 'Alice', lastName: 'Poad', password: pass('alice'), emailVerified: true, roles: ['admin', 'user'], groups: [], attributes: {} },
|
|
113
|
+
{ username: 'bob', email: 'bob@poad.test', firstName: 'Bob', lastName: 'Poad', password: pass('bob'), emailVerified: false, roles: ['user'], groups: [], attributes: {} },
|
|
85
114
|
],
|
|
86
115
|
};
|
|
87
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
88
|
-
fs.writeFileSync(file, JSON.stringify(secrets, null, 2) + '\n', { mode: 0o600 });
|
|
89
|
-
return { file, secrets };
|
|
90
116
|
};
|
|
91
117
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
118
|
+
/**
|
|
119
|
+
* Charge le jeu de test (poad/keycloak.json) et les secrets (data/keycloak/users.json),
|
|
120
|
+
* crée ce qui manque, et renvoie les utilisateurs complets (id stable, mot de passe).
|
|
121
|
+
*
|
|
122
|
+
* Reprise des projets antérieurs : les utilisateurs de l'ancien users.json
|
|
123
|
+
* passent dans keycloak.json avec leurs mots de passe ; users.json ne garde
|
|
124
|
+
* plus que les secrets. Appelé par `poad run kc` (Keycloak est recréé juste
|
|
125
|
+
* après) et, en lecture seule (create: false), par `poad info`.
|
|
126
|
+
*/
|
|
127
|
+
const loadProject = (root, config, { create = true } = {}) => {
|
|
128
|
+
const secretsFile = path.join(dataDir(root), 'users.json');
|
|
129
|
+
const fixturePath = fixtureFile(root);
|
|
130
|
+
let secrets = fs.existsSync(secretsFile) ? JSON.parse(fs.readFileSync(secretsFile, 'utf-8')) : null;
|
|
131
|
+
let fixture = fs.existsSync(fixturePath) ? JSON.parse(fs.readFileSync(fixturePath, 'utf-8')) : null;
|
|
132
|
+
if (!create) {
|
|
133
|
+
if (!secrets || !fixture) return null;
|
|
134
|
+
}
|
|
135
|
+
let secretsChanged = false;
|
|
136
|
+
if (!secrets) {
|
|
137
|
+
secrets = {};
|
|
138
|
+
secretsChanged = true;
|
|
139
|
+
}
|
|
140
|
+
if (!secrets.signing_key) {
|
|
141
|
+
secrets.signing_key = rsaKey();
|
|
142
|
+
secretsChanged = true;
|
|
143
|
+
}
|
|
144
|
+
if (!secrets.client_secret) {
|
|
145
|
+
secrets.client_secret = random(24);
|
|
146
|
+
secretsChanged = true;
|
|
147
|
+
}
|
|
148
|
+
if (!isTypeable(secrets.admin_password)) {
|
|
149
|
+
secrets.admin_password = typeable(16);
|
|
150
|
+
secretsChanged = true;
|
|
151
|
+
}
|
|
152
|
+
if (!fixture) {
|
|
153
|
+
fixture = defaultFixture(realmName(config), secrets.users || []);
|
|
154
|
+
if (create) writeJson(fixturePath, fixture);
|
|
155
|
+
}
|
|
156
|
+
if (secrets.users) {
|
|
157
|
+
// Ancien format : les comptes vivent maintenant dans keycloak.json
|
|
158
|
+
delete secrets.users;
|
|
159
|
+
secretsChanged = true;
|
|
160
|
+
}
|
|
161
|
+
secrets.ids = secrets.ids || {};
|
|
162
|
+
secrets.passwords = secrets.passwords || {};
|
|
163
|
+
|
|
164
|
+
const users = (fixture.users || []).map((u) => {
|
|
165
|
+
if (!secrets.ids[u.username]) {
|
|
166
|
+
secrets.ids[u.username] = crypto.randomUUID();
|
|
167
|
+
secretsChanged = true;
|
|
168
|
+
}
|
|
169
|
+
let password = u.password;
|
|
170
|
+
if (!password) {
|
|
171
|
+
// Pas de mot de passe dans le fichier : généré, gardé hors git
|
|
172
|
+
if (!secrets.passwords[u.username]) {
|
|
173
|
+
secrets.passwords[u.username] = typeable(12);
|
|
174
|
+
secretsChanged = true;
|
|
175
|
+
}
|
|
176
|
+
password = secrets.passwords[u.username];
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
...u,
|
|
180
|
+
id: secrets.ids[u.username],
|
|
181
|
+
password,
|
|
182
|
+
emailVerified: u.emailVerified !== false,
|
|
183
|
+
roles: u.roles || [],
|
|
184
|
+
groups: u.groups || [],
|
|
185
|
+
attributes: u.attributes || {},
|
|
186
|
+
};
|
|
187
|
+
});
|
|
188
|
+
if (secretsChanged && create) writeJson(secretsFile, secrets, 0o600);
|
|
189
|
+
return { secretsFile, fixturePath, secrets, fixture, users, realm: realmName(config, fixture) };
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
const asList = (v) => (Array.isArray(v) ? v : [v]);
|
|
193
|
+
|
|
194
|
+
/** Représentation Keycloak du realm, importée au démarrage */
|
|
195
|
+
const realmOf = (config, project) => {
|
|
196
|
+
const { secrets, fixture, users, realm } = project;
|
|
197
|
+
const roles = [...new Set([...(fixture.roles || []), ...users.flatMap((u) => u.roles)])];
|
|
198
|
+
const groups = [...new Set([...(fixture.groups || []), ...users.flatMap((u) => u.groups)])];
|
|
199
|
+
return {
|
|
200
|
+
realm,
|
|
201
|
+
enabled: true,
|
|
202
|
+
registrationAllowed: false,
|
|
203
|
+
components: {
|
|
204
|
+
'org.keycloak.keys.KeyProvider': [
|
|
205
|
+
{
|
|
206
|
+
name: 'poad-rsa',
|
|
207
|
+
providerId: 'rsa',
|
|
208
|
+
subComponents: {},
|
|
209
|
+
config: { privateKey: [secrets.signing_key], priority: ['200'], algorithm: ['RS256'], active: ['true'], enabled: ['true'] },
|
|
210
|
+
},
|
|
211
|
+
],
|
|
212
|
+
},
|
|
213
|
+
roles: { realm: roles.map((name) => ({ name })) },
|
|
214
|
+
groups: groups.map((name) => ({ name, path: `/${name}` })),
|
|
215
|
+
clients: [
|
|
98
216
|
{
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
217
|
+
clientId: CLIENT,
|
|
218
|
+
enabled: true,
|
|
219
|
+
protocol: 'openid-connect',
|
|
220
|
+
publicClient: false,
|
|
221
|
+
secret: secrets.client_secret,
|
|
222
|
+
standardFlowEnabled: true,
|
|
223
|
+
directAccessGrantsEnabled: false,
|
|
224
|
+
redirectUris: [`http://localhost:${config.web.port}/auth/v1/callback`],
|
|
225
|
+
webOrigins: ['+'],
|
|
226
|
+
attributes: { 'pkce.code.challenge.method': 'S256' },
|
|
227
|
+
// Rôles du realm, à plat, dans la claim « roles » (jeton d'identité,
|
|
228
|
+
// jeton d'accès, userinfo) : poad les recopie dans app_metadata.roles
|
|
229
|
+
protocolMappers: [
|
|
230
|
+
{
|
|
231
|
+
name: 'realm roles',
|
|
232
|
+
protocol: 'openid-connect',
|
|
233
|
+
protocolMapper: 'oidc-usermodel-realm-role-mapper',
|
|
234
|
+
config: {
|
|
235
|
+
'claim.name': ROLES_CLAIM,
|
|
236
|
+
multivalued: 'true',
|
|
237
|
+
'jsonType.label': 'String',
|
|
238
|
+
'id.token.claim': 'true',
|
|
239
|
+
'access.token.claim': 'true',
|
|
240
|
+
'userinfo.token.claim': 'true',
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
],
|
|
103
244
|
},
|
|
104
245
|
],
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
246
|
+
users: users.map((u) => ({
|
|
247
|
+
id: u.id,
|
|
248
|
+
username: u.username,
|
|
249
|
+
email: u.email,
|
|
250
|
+
emailVerified: u.emailVerified,
|
|
251
|
+
firstName: u.firstName || capitalize(u.username),
|
|
252
|
+
lastName: u.lastName || '',
|
|
109
253
|
enabled: true,
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
254
|
+
attributes: Object.fromEntries(Object.entries(u.attributes).map(([k, v]) => [k, asList(v).map(String)])),
|
|
255
|
+
credentials: [{ type: 'password', value: u.password, temporary: false }],
|
|
256
|
+
realmRoles: u.roles,
|
|
257
|
+
groups: u.groups.map((g) => `/${g}`),
|
|
258
|
+
})),
|
|
259
|
+
};
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
/** Jeton d'administration du Keycloak qui tourne (realm master) */
|
|
263
|
+
const adminToken = async (port, secrets) => {
|
|
264
|
+
const body = new URLSearchParams({ grant_type: 'password', client_id: 'admin-cli', username: 'admin', password: secrets.admin_password });
|
|
265
|
+
const res = await fetch(`http://localhost:${port}/realms/master/protocol/openid-connect/token`, { method: 'POST', body });
|
|
266
|
+
if (!res.ok) throw new Error(`Keycloak admin login refused (${res.status})`);
|
|
267
|
+
return (await res.json()).access_token;
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* État du realm qui tourne : rôles, groupes, utilisateurs (avec leurs rôles et
|
|
272
|
+
* groupes). Les mots de passe ne se relisent pas : ceux du fichier sont gardés.
|
|
273
|
+
*/
|
|
274
|
+
const readRunningRealm = async (port, secrets, realm) => {
|
|
275
|
+
const token = await adminToken(port, secrets);
|
|
276
|
+
const get = async (p) => {
|
|
277
|
+
const res = await fetch(`http://localhost:${port}/admin/realms/${encodeURIComponent(realm)}${p}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
278
|
+
if (!res.ok) throw new Error(`Keycloak admin API ${p}: ${res.status}`);
|
|
279
|
+
return res.json();
|
|
280
|
+
};
|
|
281
|
+
// Rôles techniques créés par Keycloak dans chaque realm
|
|
282
|
+
const builtin = (n) => n === 'offline_access' || n === 'uma_authorization' || n.startsWith('default-roles-');
|
|
283
|
+
const roles = (await get('/roles')).map((r) => r.name).filter((n) => !builtin(n)).sort();
|
|
284
|
+
const flatten = (gs) => gs.flatMap((g) => [g.name, ...flatten(g.subGroups || [])]);
|
|
285
|
+
const groups = flatten(await get('/groups?briefRepresentation=true')).sort();
|
|
286
|
+
const users = [];
|
|
287
|
+
for (const u of await get('/users?max=1000&briefRepresentation=false')) {
|
|
288
|
+
const userRoles = (await get(`/users/${u.id}/role-mappings/realm`)).map((r) => r.name).filter((n) => !builtin(n)).sort();
|
|
289
|
+
const userGroups = (await get(`/users/${u.id}/groups`)).map((g) => g.name).sort();
|
|
290
|
+
users.push({
|
|
291
|
+
id: u.id,
|
|
292
|
+
username: u.username,
|
|
293
|
+
email: u.email,
|
|
294
|
+
firstName: u.firstName,
|
|
295
|
+
lastName: u.lastName,
|
|
296
|
+
emailVerified: Boolean(u.emailVerified),
|
|
297
|
+
roles: userRoles,
|
|
298
|
+
groups: userGroups,
|
|
299
|
+
attributes: Object.fromEntries(Object.entries(u.attributes || {}).map(([k, v]) => [k, v.length === 1 ? v[0] : v])),
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
users.sort((a, b) => a.username.localeCompare(b.username));
|
|
303
|
+
return { roles, groups, users };
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Autorise les attributs libres sur les utilisateurs du realm (Keycloak 24+ les
|
|
308
|
+
* ignore sinon quand on les ajoute par la console d'admin) : sans ça, un
|
|
309
|
+
* attribut saisi dans la console disparaîtrait avant `poad kc export`.
|
|
310
|
+
*/
|
|
311
|
+
const enableUserAttributes = async (port, secrets, realm) => {
|
|
312
|
+
const token = await adminToken(port, secrets);
|
|
313
|
+
const url = `http://localhost:${port}/admin/realms/${encodeURIComponent(realm)}/users/profile`;
|
|
314
|
+
const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
|
|
315
|
+
const profile = await (await fetch(url, { headers })).json();
|
|
316
|
+
if (profile.unmanagedAttributePolicy === 'ENABLED') return;
|
|
317
|
+
const res = await fetch(url, { method: 'PUT', headers, body: JSON.stringify({ ...profile, unmanagedAttributePolicy: 'ENABLED' }) });
|
|
318
|
+
if (!res.ok) throw new Error(`user profile: ${res.status}`);
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Reprise : avant de recréer un Keycloak qui tourne, garde les identifiants de
|
|
323
|
+
* ses utilisateurs qui n'en ont pas encore dans les secrets (projets antérieurs,
|
|
324
|
+
* où chaque réimport en tirait de nouveaux). Ainsi le « sub » ne change plus et
|
|
325
|
+
* les identités déjà liées dans poad restent valables. Sans effet si rien ne tourne.
|
|
326
|
+
*/
|
|
327
|
+
const adoptRunningIds = async (root, config) => {
|
|
328
|
+
const secretsFile = path.join(dataDir(root), 'users.json');
|
|
329
|
+
if (!fs.existsSync(secretsFile) || !(config.keycloak && config.keycloak.port)) return 0;
|
|
330
|
+
const secrets = JSON.parse(fs.readFileSync(secretsFile, 'utf-8'));
|
|
331
|
+
if (!secrets.admin_password) return 0;
|
|
332
|
+
const fixture = fs.existsSync(fixtureFile(root)) ? JSON.parse(fs.readFileSync(fixtureFile(root), 'utf-8')) : null;
|
|
333
|
+
secrets.ids = secrets.ids || {};
|
|
334
|
+
let adopted = 0;
|
|
335
|
+
// Realm du projet, ou « poad », nom unique des versions antérieures
|
|
336
|
+
for (const realm of [...new Set([realmName(config, fixture), 'poad'])]) {
|
|
337
|
+
let running;
|
|
338
|
+
try {
|
|
339
|
+
running = await readRunningRealm(config.keycloak.port, secrets, realm);
|
|
340
|
+
} catch {
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
for (const u of running.users) {
|
|
344
|
+
if (!secrets.ids[u.username]) {
|
|
345
|
+
secrets.ids[u.username] = u.id;
|
|
346
|
+
adopted++;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
351
|
+
if (adopted) writeJson(secretsFile, secrets, 0o600);
|
|
352
|
+
return adopted;
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* `poad kc export` : réécrit keycloak.json depuis le Keycloak qui tourne.
|
|
357
|
+
* Mots de passe : ceux du fichier pour les comptes connus ; un compte créé
|
|
358
|
+
* dans la console reçoit un nouveau mot de passe, appliqué au prochain `poad run kc`.
|
|
359
|
+
*/
|
|
360
|
+
const exportRealm = async (root, config) => {
|
|
361
|
+
const project = loadProject(root, config);
|
|
362
|
+
const running = await readRunningRealm(config.keycloak.port, project.secrets, project.realm);
|
|
363
|
+
const known = Object.fromEntries((project.fixture.users || []).map((u) => [u.username, u]));
|
|
364
|
+
const fresh = [];
|
|
365
|
+
const users = running.users.map((u) => {
|
|
366
|
+
const before = known[u.username] || {};
|
|
367
|
+
let password = before.password || project.secrets.passwords[u.username];
|
|
368
|
+
if (!password) {
|
|
369
|
+
password = typeable(12);
|
|
370
|
+
fresh.push(u.username);
|
|
371
|
+
}
|
|
372
|
+
// Garde l'identifiant Keycloak : le « sub » reste le même au prochain lancement
|
|
373
|
+
project.secrets.ids[u.username] = u.id;
|
|
374
|
+
const { id, ...rest } = u;
|
|
375
|
+
return { ...rest, password };
|
|
376
|
+
});
|
|
377
|
+
const fixture = { ...project.fixture, realm: project.realm, roles: running.roles, groups: running.groups, users };
|
|
378
|
+
writeJson(project.fixturePath, fixture);
|
|
379
|
+
writeJson(project.secretsFile, project.secrets, 0o600);
|
|
380
|
+
return { file: project.fixturePath, users: users.length, fresh };
|
|
381
|
+
};
|
|
130
382
|
|
|
131
383
|
const isLocalProvider = (params) =>
|
|
132
384
|
/\/\/(keycloak:8080|host\.docker\.internal|localhost|127\.0\.0\.1)[:/]/.test(String(params && params.issuer));
|
|
@@ -142,13 +394,15 @@ const assertCanRegister = (config) => {
|
|
|
142
394
|
}
|
|
143
395
|
};
|
|
144
396
|
|
|
145
|
-
const register = (config,
|
|
397
|
+
const register = (config, project) => {
|
|
146
398
|
assertCanRegister(config);
|
|
147
399
|
const params = {
|
|
148
|
-
issuer: `http://${ALIAS}:8080/realms/${
|
|
400
|
+
issuer: `http://${ALIAS}:8080/realms/${project.realm}`,
|
|
149
401
|
client_id: CLIENT,
|
|
150
|
-
client_secret: secrets.client_secret,
|
|
402
|
+
client_secret: project.secrets.client_secret,
|
|
151
403
|
scopes: 'openid email profile',
|
|
404
|
+
// Rôles du realm recopiés dans app_metadata.roles à chaque connexion
|
|
405
|
+
roles_claim: ROLES_CLAIM,
|
|
152
406
|
};
|
|
153
407
|
psql(
|
|
154
408
|
config,
|
|
@@ -171,16 +425,22 @@ const unregister = (config) => {
|
|
|
171
425
|
|
|
172
426
|
module.exports = {
|
|
173
427
|
IMAGE,
|
|
174
|
-
REALM,
|
|
175
428
|
PROVIDER,
|
|
176
429
|
NAMES,
|
|
177
430
|
ALIAS,
|
|
431
|
+
ROLES_CLAIM,
|
|
178
432
|
containerName,
|
|
179
433
|
dataDir,
|
|
434
|
+
fixtureFile,
|
|
435
|
+
realmName,
|
|
180
436
|
wanted,
|
|
181
437
|
savePort,
|
|
182
|
-
|
|
438
|
+
loadProject,
|
|
183
439
|
realmOf,
|
|
440
|
+
readRunningRealm,
|
|
441
|
+
adoptRunningIds,
|
|
442
|
+
enableUserAttributes,
|
|
443
|
+
exportRealm,
|
|
184
444
|
assertCanRegister,
|
|
185
445
|
register,
|
|
186
446
|
unregister,
|
package/utils/services.js
CHANGED
|
@@ -8,17 +8,8 @@
|
|
|
8
8
|
const kc = require('./keycloak');
|
|
9
9
|
const valkey = require('./valkey');
|
|
10
10
|
const mail = require('./mail');
|
|
11
|
-
const fs = require('fs');
|
|
12
11
|
const path = require('path');
|
|
13
12
|
|
|
14
|
-
const readKeycloakUsers = (root) => {
|
|
15
|
-
if (!root) return null;
|
|
16
|
-
try {
|
|
17
|
-
return JSON.parse(fs.readFileSync(path.join(kc.dataDir(root), 'users.json'), 'utf-8'));
|
|
18
|
-
} catch {
|
|
19
|
-
return null;
|
|
20
|
-
}
|
|
21
|
-
};
|
|
22
13
|
|
|
23
14
|
const SERVICES = [
|
|
24
15
|
{
|
|
@@ -38,16 +29,22 @@ const SERVICES = [
|
|
|
38
29
|
container: (config) => kc.containerName(config),
|
|
39
30
|
configured: (config) => Boolean(config.keycloak && config.keycloak.port),
|
|
40
31
|
info: (config, root) => {
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
out['
|
|
50
|
-
|
|
32
|
+
const base = `http://localhost:${config.keycloak.port}`;
|
|
33
|
+
// Lecture seule : rien n'est créé tant que `poad run kc` n'a pas tourné
|
|
34
|
+
const project = root ? kc.loadProject(root, config, { create: false }) : null;
|
|
35
|
+
const realm = project ? project.realm : kc.realmName(config);
|
|
36
|
+
const out = { URL: base, Issuer: `${base}/realms/${realm}`, Provider: `"${kc.PROVIDER}"` };
|
|
37
|
+
if (project) {
|
|
38
|
+
// Deux realms, deux usages : ne pas essayer alice sur la console d'admin
|
|
39
|
+
out['Admin console'] = [`${base}/admin`, `admin ${project.secrets.admin_password}`];
|
|
40
|
+
out['Test users'] = [
|
|
41
|
+
`realm "${realm}" : "Continuer avec Keycloak" in the app, or ${base}/realms/${realm}/account`,
|
|
42
|
+
...project.users.map(
|
|
43
|
+
(u) =>
|
|
44
|
+
`${u.username.padEnd(6)} ${u.password} ${u.email || ''}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
|
|
45
|
+
),
|
|
46
|
+
];
|
|
47
|
+
out['Test set'] = `${path.relative(process.cwd(), project.fixturePath)} (poad kc export saves the running realm)`;
|
|
51
48
|
}
|
|
52
49
|
return out;
|
|
53
50
|
},
|