keycloak-api-manager 4.0.0 → 5.0.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.
Files changed (48) hide show
  1. package/Handlers/attackDetectionHandler.js +64 -0
  2. package/Handlers/clientPoliciesHandler.js +120 -0
  3. package/Handlers/groupsHandler.js +32 -0
  4. package/Handlers/organizationsHandler.js +243 -0
  5. package/Handlers/serverInfoHandler.js +36 -0
  6. package/Handlers/userProfileHandler.js +121 -0
  7. package/README.md +83 -7157
  8. package/docs/architecture.md +47 -0
  9. package/docs/deployment.md +32 -0
  10. package/docs/keycloak-setup.md +47 -0
  11. package/docs/test-configuration.md +43 -0
  12. package/docs/testing.md +60 -0
  13. package/index.js +156 -240
  14. package/package.json +28 -15
  15. package/test/.mocharc.json +2 -2
  16. package/test/config/secrets.json +12 -0
  17. package/test/docker-keycloak/certs/keycloak.crt +58 -0
  18. package/test/docker-keycloak/certs/keycloak.key +28 -0
  19. package/test/docker-keycloak/docker-compose-https.yml +2 -0
  20. package/test/docker-keycloak/docker-compose.yml +4 -4
  21. package/test/helpers/matrix.js +16 -0
  22. package/test/matrix/auth.json +27 -0
  23. package/test/matrix/clients.json +45 -0
  24. package/test/matrix/realms-components-idp.json +37 -0
  25. package/test/matrix/users-roles-groups.json +26 -0
  26. package/test/package-lock.json +3032 -0
  27. package/test/specs/attackDetection.test.js +102 -0
  28. package/test/specs/clientCredentials.test.js +79 -0
  29. package/test/specs/clientPolicies.test.js +162 -0
  30. package/test/specs/{debugClientLibrary.test.js → diagnostics/debugClientLibrary.test.js} +2 -2
  31. package/test/specs/groupPermissions.test.js +87 -0
  32. package/test/specs/matrix/matrix-auth.test.js +112 -0
  33. package/test/specs/matrix/matrix-clients.test.js +59 -0
  34. package/test/specs/matrix/matrix-realms-components-idp.test.js +111 -0
  35. package/test/specs/matrix/matrix-users-roles-groups.test.js +68 -0
  36. package/test/specs/organizations.test.js +183 -0
  37. package/test/specs/serverInfo.test.js +140 -0
  38. package/test/specs/userProfile.test.js +135 -0
  39. package/test/{enableServerFeatures.js → support/enableServerFeatures.js} +43 -26
  40. package/test/{setup.js → support/setup.js} +3 -3
  41. package/test/support/testConfig.js +69 -0
  42. package/test/testConfig.js +1 -69
  43. package/test-output.log +72 -0
  44. package/test/TESTING.md +0 -327
  45. package/test/config/CONFIGURATION.md +0 -170
  46. package/test/diagnostic-protocol-mappers.js +0 -189
  47. package/test/docker-keycloak/DEPLOYMENT_GUIDE.md +0 -262
  48. package/test/helpers/setup.js +0 -186
@@ -1,262 +0,0 @@
1
- # Keycloak Deployment Setup Guide
2
-
3
- ## Quick Start
4
-
5
- ### Local HTTP (Development)
6
- ```bash
7
- npm run setup-keycloak
8
- # Select: 1 (Local)
9
- # Select: 1 (HTTP)
10
- # ✓ Keycloak accessible at http://localhost:8080
11
- ```
12
-
13
- ### Local HTTPS (Production-like)
14
- ```bash
15
- npm run setup-keycloak
16
- # Select: 1 (Local)
17
- # Select: 2 (HTTPS)
18
- #
19
- # If certificates exist in test/docker-keycloak/certs:
20
- # ✓ Script automatically uses them
21
- #
22
- # Otherwise, enter certificate path when prompted:
23
- # Certificate directory path: /path/to/certs
24
- # (or press Enter to use default location)
25
- #
26
- # ✓ Keycloak accessible at https://localhost:8443
27
- ```
28
-
29
- ### Remote HTTP
30
- ```bash
31
- npm run setup-keycloak
32
- # Choose deployment: Remote (auto-selected, no Docker locally)
33
- # Enable HTTPS: 1 (No - HTTP)
34
- # Remote host/IP: smart@smart-dell-sml.crs4.it
35
- # ✓ Keycloak deployed at http://smart-dell-sml.crs4.it:8080
36
- ```
37
-
38
- ### Remote HTTPS
39
- ```bash
40
- npm run setup-keycloak
41
- # Choose deployment: Remote (auto-selected)
42
- # Enable HTTPS: 2 (Yes - HTTPS)
43
- # → Certificates automatically loaded from: test/docker-keycloak/certs
44
- # Remote host/IP: smart@smart-dell-sml.crs4.it
45
- # ✓ Certificates copied to remote and deployed with HTTPS
46
- # ✓ Keycloak accessible at https://smart-dell-sml.crs4.it:8443
47
- ```
48
-
49
- ## Features
50
-
51
- ### ✅ Local Deployment
52
- - **HTTP Mode**: Development environment, no certificates needed
53
- - **HTTPS Mode**: Production-like environment using SSL/TLS certificates
54
- - **Automatic Health Checks**: Waits for Keycloak to be fully ready
55
- - **Docker Integration**: Uses docker-compose for easy container management
56
-
57
- ### ✅ Remote Deployment via SSH
58
- - **Automatic File Transfer**: Copies docker-compose files via SCP
59
- - **Certificate Management**: Copies certificates to remote server if HTTPS enabled
60
- - **SSH Connectivity**: Verifies SSH connection before deployment
61
- - **Health Checks**: Confirms Keycloak is running on remote server
62
-
63
- ### ✅ Configuration Management
64
- - **.env Files**: Auto-generated configuration files
65
- - **Certificate Mounting**: Automatic mounting of SSL certificates
66
- - **Hostname Configuration**: Sets proper KEYCLOAK_HOSTNAME for remote servers
67
- - **Port Configuration**: Supports custom ports for HTTPS
68
-
69
- ## File Structure
70
-
71
- ```
72
- keycloak-api-manager/
73
- ├── docker-compose.yml # HTTP configuration
74
- ├── docker-compose-https.yml # HTTPS configuration
75
- ├── .env # Generated by setup script (gitignored)
76
- ├── .env.example # Reference configuration
77
- └── test/
78
- └── setup-keycloak.js # Interactive setup script
79
- ```
80
-
81
- ## Certificate Configuration
82
-
83
- ### Default Location
84
- For local HTTPS deployments, the script automatically searches for certificates in:
85
- ```
86
- test/docker-keycloak/certs/
87
- ├── keycloak.crt (X.509 certificate)
88
- └── keycloak.key (Private key)
89
- ```
90
-
91
- **If found**: Script uses them automatically ✅
92
- **If not found**: Script prompts you to enter a custom path
93
-
94
- The default location allows you to:
95
- - Generate certificates once and commit them to the repo
96
- - Run the script without entering certificate path every time
97
- - Keep certificates organized with the deployment infrastructure
98
-
99
- ### For Remote Deployments - Automatic Certificate Handling
100
-
101
- When deploying to a remote server with HTTPS, the script **automatically**:
102
- 1. Loads certificates from the local `test/docker-keycloak/certs/` directory
103
- 2. Verifies they exist (fails with clear error if missing)
104
- 3. Copies them to the remote server in `deployment_path/certs/`
105
- 4. Uses them for the HTTPS configuration
106
-
107
- **No manual prompts** - just ensure you have valid certificates in `test/docker-keycloak/certs/`:
108
- ```bash
109
- test/docker-keycloak/certs/
110
- ├── keycloak.crt
111
- └── keycloak.key
112
- ```
113
-
114
- ### For Local Deployments - Custom Certificate Path
115
-
116
- For local HTTPS deployments, certificates are first sought in `test/docker-keycloak/certs/`.
117
- If not found there, you will be prompted to enter a custom path:
118
- ```bash
119
- Certificate directory path (or press Enter for default): /path/to/your/certs
120
- ```
121
-
122
- ### Certificate Files Required
123
- For HTTPS deployments, ensure the certificate directory contains:
124
- - `keycloak.crt` - X.509 certificate file
125
- - `keycloak.key` - Unencrypted private key file
126
-
127
- Example self-signed certificate generation:
128
- ```bash
129
- # Generate self-signed certificate for testing
130
- openssl req -x509 -newkey rsa:2048 -keyout keycloak.key \
131
- -out keycloak.crt -days 365 -nodes \
132
- -subj "/CN=keycloak.test/O=Test/C=US"
133
-
134
- # Place in the default location
135
- mkdir -p test/docker-keycloak/certs
136
- cp keycloak.crt keycloak.key test/docker-keycloak/certs/
137
- ```
138
-
139
- ## Configuration Details
140
-
141
- ### Environment Variables
142
-
143
- **HTTP Version**:
144
- - `KEYCLOAK_HOSTNAME`: Hostname for Keycloak (localhost for local, hostname for remote)
145
-
146
- **HTTPS Version**:
147
- - `KEYCLOAK_CERT_PATH`: Path to certificate directory
148
- - `KEYCLOAK_HOSTNAME`: Hostname for Keycloak (must match certificate CN for production)
149
-
150
- ### Docker Compose Files
151
-
152
- **docker-compose.yml** (HTTP):
153
- ```yaml
154
- - Image: keycloak/keycloak:latest
155
- - Ports: 8080 (HTTP)
156
- - Database: In-memory (KC_DB: dev-mem)
157
- - Admin Creds: admin:admin
158
- ```
159
-
160
- **docker-compose-https.yml** (HTTPS):
161
- ```yaml
162
- - Image: keycloak/keycloak:latest
163
- - Ports: 8080 (HTTP), 8443 (HTTPS)
164
- - Certificates: Mounted from KEYCLOAK_CERT_PATH
165
- - Admin Creds: admin:admin
166
- ```
167
-
168
- ## Troubleshooting
169
-
170
- ### SSH Connection Failed
171
- ```bash
172
- # Verify SSH access
173
- ssh -v smart@smart-dell-sml.crs4.it 'echo OK'
174
-
175
- # Check SSH key permissions
176
- ls -la ~/.ssh/id_ed25519
177
- chmod 600 ~/.ssh/id_ed25519
178
- ```
179
-
180
- ### HTTPS Certificate Issues
181
- ```bash
182
- # Verify certificate files exist
183
- ls -la /path/to/certs/keycloak.crt
184
- ls -la /path/to/certs/keycloak.key
185
-
186
- # Test certificate validity
187
- openssl x509 -in keycloak.crt -text -noout
188
-
189
- # For browser access with self-signed cert:
190
- # - Use curl -k (insecure flag)
191
- # - Add browser exception for the domain
192
- ```
193
-
194
- ### Keycloak Takes Too Long to Start
195
- ```bash
196
- # Check container logs
197
- docker-compose -f docker-compose.yml logs -f
198
-
199
- # Or remotely
200
- ssh smart@smart-dell-sml.crs4.it 'cd /home/smart/keycloak && docker-compose -f docker-compose-https.yml logs -f'
201
- ```
202
-
203
- ### Port Already in Use
204
- ```bash
205
- # Check what's using the port
206
- lsof -i :8080
207
- lsof -i :8443
208
-
209
- # Kill existing container
210
- docker-compose down
211
- ```
212
-
213
- ## Running Tests with Different Deployments
214
-
215
- After deploying Keycloak with the setup script, run tests:
216
-
217
- ```bash
218
- # Tests will automatically detect and connect to Keycloak
219
- npm test
220
-
221
- # The test setup handles:
222
- # - Local HTTP: Connects to http://localhost:8080
223
- # - Local HTTPS: Connects to https://localhost:8443
224
- # - Remote: Can be configured in test/config/default.json
225
- ```
226
-
227
- ## Advanced Configuration
228
-
229
- ### Custom Keycloak Version
230
- Edit `docker-compose.yml` or `docker-compose-https.yml`:
231
- ```yaml
232
- services:
233
- keycloak:
234
- image: keycloak/keycloak:25.0 # Change version here
235
- ```
236
-
237
- ### Custom Database
238
- Edit docker-compose files, change `KC_DB`:
239
- ```yaml
240
- environment:
241
- KC_DB: postgres # Instead of dev-mem
242
- KC_DB_URL_HOST: postgres-host
243
- KC_DB_URL_PORT: 5432
244
- KC_DB_USERNAME: keycloak
245
- KC_DB_PASSWORD: password
246
- ```
247
-
248
- ### Additional Environment Variables
249
- Add to `.env`:
250
- ```bash
251
- KC_LOG_LEVEL=INFO
252
- KC_METRICS_ENABLED=true
253
- KC_CACHE=ispn
254
- ```
255
-
256
- ## Support
257
-
258
- For issues or questions:
259
- - Check Docker logs: `docker-compose logs -f`
260
- - Check Keycloak admin console: http://localhost:8080
261
- - Review certificates: `openssl x509 -in keycloak.crt -text -noout`
262
- - Test connectivity: `curl -k https://localhost:8443/health/ready`
@@ -1,186 +0,0 @@
1
- /**
2
- * Mocha Root Setup Hook
3
- * Orchestrates Docker container lifecycle and Keycloak initialization
4
- */
5
-
6
- const { startDocker, stopDocker, waitForHealthy, updateConfigFromDocker, createSSHTunnel, closeSSHTunnel } = require('./docker-helpers');
7
- const { initializeAdminClient, setupTestRealm, cleanupTestRealm, resetConfig } = require('./config');
8
-
9
- // Store tunnel state for cleanup
10
- let sshTunnelUrl = null;
11
-
12
- /**
13
- * Attempt to connect to Keycloak, with automatic SSH tunnel retry
14
- */
15
- async function connectWithRetry() {
16
- try {
17
- console.log('Attempting Keycloak connection...');
18
- await initializeAdminClient();
19
- console.log('✓ Connected successfully to Keycloak\n');
20
- } catch (err) {
21
- // Check if connection was refused (tunnel might be needed)
22
- if (err.message && err.message.includes('ECONNREFUSED') && err.message.includes('127.0.0.1:9998')) {
23
- console.log('⚠ Direct connection failed (ECONNREFUSED on 127.0.0.1:9998)');
24
- console.log(' Attempting to create SSH tunnel to smart-dell-sml.crs4.it...\n');
25
-
26
- try {
27
- // Create SSH tunnel
28
- sshTunnelUrl = await createSSHTunnel();
29
-
30
- if (sshTunnelUrl) {
31
- console.log(`✓ SSH tunnel created: http://${sshTunnelUrl}`);
32
-
33
- // Update config to use tunnel
34
- const fs = require('fs');
35
- const path = require('path');
36
- const configPath = path.join(__dirname, '../config/local.json');
37
-
38
- // Create or update local.json
39
- let config = {};
40
- if (fs.existsSync(configPath)) {
41
- config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
42
- }
43
-
44
- if (!config.test) config.test = {};
45
- if (!config.test.keycloak) config.test.keycloak = {};
46
- config.test.keycloak.baseUrl = `http://${sshTunnelUrl}`;
47
-
48
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
49
- console.log(`✓ Updated config to use SSH tunnel\n`);
50
-
51
- // Reset config cache and retry connection
52
- resetConfig();
53
- await initializeAdminClient();
54
- console.log('✓ Connected successfully via SSH tunnel\n');
55
- } else {
56
- throw new Error('SSH tunnel creation failed - returned null');
57
- }
58
- } catch (tunnelErr) {
59
- console.error('✗ SSH tunnel connection failed:');
60
- console.error(` Error: ${tunnelErr.message}`);
61
- console.error('\nTroubleshooting:');
62
- console.error(' 1. Verify SSH key: ~/.ssh/id_ed25519 exists');
63
- console.error(' 2. Verify remote host: smart-dell-sml.crs4.it is reachable');
64
- console.error(' 3. Verify remote Keycloak: running on smart@smart-dell-sml.crs4.it');
65
- console.error(' 4. Manual tunnel alternative: ssh -L 127.0.0.1:9998:127.0.0.1:8080 smart@smart-dell-sml.crs4.it');
66
- throw new Error(`Failed to connect to Keycloak. Direct connection (127.0.0.1:9998) failed and SSH tunnel creation also failed: ${tunnelErr.message}`);
67
- }
68
- } else {
69
- // Not a connection refused error - propagate as-is
70
- throw err;
71
- }
72
- }
73
- }
74
-
75
- // Root hook plugin for Mocha
76
- exports.mochaHooks = {
77
- async beforeAll() {
78
- this.timeout(120000); // 2 minutes max for setup
79
-
80
- console.log('\n========== TEST SETUP ==========');
81
-
82
- if (process.env.SKIP_TEST_SETUP === 'true') {
83
- console.log('Skipping global test setup (SKIP_TEST_SETUP=true)\n');
84
- return;
85
- }
86
-
87
- // Check if using remote Keycloak (skip Docker)
88
- const useRemoteKeycloak = process.env.USE_REMOTE_KEYCLOAK === 'true';
89
- const useRemoteDocker = !!process.env.DOCKER_SSH_HOST;
90
-
91
- try {
92
- if (useRemoteKeycloak) {
93
- console.log('Using remote Keycloak (skip Docker startup)');
94
- console.log('Configuration from test/config/*.json files\n');
95
- } else if (useRemoteDocker) {
96
- console.log(`Starting Docker containers on remote host ${process.env.DOCKER_SSH_HOST}...`);
97
-
98
- // Start Docker Compose on remote host
99
- await startDocker();
100
-
101
- // Wait for services to be healthy on remote host
102
- await waitForHealthy();
103
-
104
- // Update configuration from remote Docker container
105
- await updateConfigFromDocker();
106
-
107
- // Create SSH tunnel for local HTTP access (avoids HTTPS enforcement)
108
- sshTunnelUrl = await createSSHTunnel();
109
-
110
- // Update config to use tunnel
111
- if (sshTunnelUrl) {
112
- const fs = require('fs');
113
- const path = require('path');
114
- const configPath = path.join(__dirname, '../config/local.json');
115
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
116
- config.test.keycloak.baseUrl = `http://${sshTunnelUrl}`;
117
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
118
- console.log(`✓ Updated config to use SSH tunnel: http://${sshTunnelUrl}`);
119
- }
120
-
121
- // Reset config cache so it reloads from updated local.json
122
- resetConfig();
123
- } else {
124
- console.log('Starting Docker containers locally...');
125
-
126
- // Start Docker Compose locally
127
- await startDocker();
128
-
129
- // Wait for services to be healthy locally
130
- await waitForHealthy();
131
-
132
- // Update configuration from local Docker container
133
- await updateConfigFromDocker();
134
- }
135
-
136
- // Connect to Keycloak (with automatic SSH tunnel retry if needed)
137
- await connectWithRetry();
138
-
139
- // Setup test realm
140
- await setupTestRealm();
141
-
142
- console.log('✓ Test environment ready\n');
143
- } catch (err) {
144
- console.error('✗ Test setup failed:', err.message);
145
- throw err;
146
- }
147
- },
148
-
149
- async afterAll() {
150
- this.timeout(60000); // 1 minute max for teardown
151
-
152
- console.log('\n========== TEST TEARDOWN ==========');
153
-
154
- if (process.env.SKIP_TEST_SETUP === 'true') {
155
- console.log('Skipping global test teardown (SKIP_TEST_SETUP=true)\n');
156
- return;
157
- }
158
-
159
- const useRemoteKeycloak = process.env.USE_REMOTE_KEYCLOAK === 'true';
160
- const useRemoteDocker = !!process.env.DOCKER_SSH_HOST;
161
-
162
- try {
163
- // Cleanup Keycloak test realm
164
- await cleanupTestRealm();
165
-
166
- // Close SSH tunnel if open
167
- if (sshTunnelUrl) {
168
- closeSSHTunnel();
169
- sshTunnelUrl = null;
170
- }
171
-
172
- // Stop Docker Compose only if using local or remote Docker (not pre-deployed)
173
- if (!useRemoteKeycloak && !useRemoteDocker) {
174
- await stopDocker();
175
- } else if (useRemoteDocker) {
176
- // Stop Docker on remote host
177
- await stopDocker();
178
- }
179
-
180
- console.log('✓ Test environment cleaned up\n');
181
- } catch (err) {
182
- console.error('✗ Test teardown failed:', err.message);
183
- // Don't throw during cleanup to allow partial cleanup
184
- }
185
- },
186
- };