|
| 1 | +/* eslint-disable camelcase */ |
| 2 | +/* eslint-disable @typescript-eslint/explicit-function-return-type */ |
| 3 | +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ |
| 4 | + |
| 5 | +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; |
| 6 | +import { CommonService } from '@credebl/common'; |
| 7 | +import { KeycloakUrlService } from '@credebl/keycloak-url'; |
| 8 | +import { ClientRegistrationService } from '@credebl/client-registration'; |
| 9 | + |
| 10 | +@Injectable() |
| 11 | +export class KeycloakConfigService implements OnModuleInit { |
| 12 | + constructor( |
| 13 | + private readonly commonService: CommonService, |
| 14 | + private readonly keycloakUrlService: KeycloakUrlService, |
| 15 | + private readonly clientRegistrationService: ClientRegistrationService |
| 16 | + ) {} |
| 17 | + |
| 18 | + private readonly logger = new Logger('KeycloakConfigService'); |
| 19 | + |
| 20 | + async onModuleInit(): Promise<void> { |
| 21 | + this.logger.log('=== Keycloak Ecosystem Configuration Starting ==='); |
| 22 | + try { |
| 23 | + await this.configureEcosystemAccess(); |
| 24 | + this.logger.log('=== Keycloak Ecosystem Configuration Finished Successfully ==='); |
| 25 | + } catch (error) { |
| 26 | + this.logger.error(`=== Keycloak Ecosystem Configuration FAILED ===`); |
| 27 | + this.logger.error(`Error: ${error.message || error}`); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + async configureEcosystemAccess(): Promise<void> { |
| 32 | + this.logger.log('Fetching management token...'); |
| 33 | + const token = await this.clientRegistrationService.getPlatformManagementToken(); |
| 34 | + this.logger.log('Management token obtained successfully'); |
| 35 | + |
| 36 | + const realmName = process.env.KEYCLOAK_REALM; |
| 37 | + this.logger.log(`Target realm: ${realmName}`); |
| 38 | + |
| 39 | + this.logger.log('[Step 1/2] Checking realm-level protocol mapper...'); |
| 40 | + await this.ensureRealmProtocolMapper(realmName, token); |
| 41 | + |
| 42 | + this.logger.log('[Step 2/2] Checking per-client protocol mappers...'); |
| 43 | + await this.ensureAllClientsProtocolMapper(realmName, token); |
| 44 | + |
| 45 | + this.logger.log('Ecosystem access configuration completed'); |
| 46 | + } |
| 47 | + |
| 48 | + private async ensureRealmProtocolMapper(realm: string, token: string): Promise<void> { |
| 49 | + this.logger.log('Looking up "profile" client scope...'); |
| 50 | + const scopeId = await this.getDefaultClientScopeId(realm, token); |
| 51 | + if (!scopeId) { |
| 52 | + this.logger.warn('Default "profile" client scope not found, skipping realm-level mapper'); |
| 53 | + return; |
| 54 | + } |
| 55 | + this.logger.log(`Found "profile" client scope: ${scopeId}`); |
| 56 | + |
| 57 | + const mappersUrl = await this.keycloakUrlService.GetClientScopeProtocolMappersURL(realm, scopeId); |
| 58 | + this.logger.log(`Fetching existing mappers from: ${mappersUrl}`); |
| 59 | + const existingMappers = await this.commonService.httpGet(mappersUrl, this.getAuthHeader(token)); |
| 60 | + |
| 61 | + const mapperExists = |
| 62 | + Array.isArray(existingMappers) && existingMappers.some((m: { name: string }) => 'ecosystem_access' === m.name); |
| 63 | + |
| 64 | + if (mapperExists) { |
| 65 | + this.logger.log('Realm-level "ecosystem_access" mapper already exists - SKIPPED'); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + this.logger.log('Realm-level "ecosystem_access" mapper not found - CREATING...'); |
| 70 | + const mapperPayload = this.buildProtocolMapperPayload('ecosystem_access'); |
| 71 | + await this.commonService.httpPost(mappersUrl, mapperPayload, this.getAuthHeader(token)); |
| 72 | + this.logger.log('Realm-level "ecosystem_access" mapper CREATED on "profile" client scope'); |
| 73 | + } |
| 74 | + |
| 75 | + private async getDefaultClientScopeId(realm: string, token: string): Promise<string | null> { |
| 76 | + const scopesUrl = await this.keycloakUrlService.GetClientScopesURL(realm); |
| 77 | + const scopes = await this.commonService.httpGet(scopesUrl, this.getAuthHeader(token)); |
| 78 | + |
| 79 | + if (!Array.isArray(scopes)) { |
| 80 | + this.logger.warn('Failed to fetch client scopes'); |
| 81 | + return null; |
| 82 | + } |
| 83 | + |
| 84 | + this.logger.log(`Found ${scopes.length} client scopes in realm`); |
| 85 | + const profileScope = scopes.find((s: { name: string }) => 'profile' === s.name); |
| 86 | + return profileScope ? profileScope.id : null; |
| 87 | + } |
| 88 | + |
| 89 | + private async ensureAllClientsProtocolMapper(realm: string, token: string): Promise<void> { |
| 90 | + const clientsUrl = await this.keycloakUrlService.GetClientsURL(realm); |
| 91 | + this.logger.log(`Fetching all clients from: ${clientsUrl}`); |
| 92 | + const clients = await this.commonService.httpGet(clientsUrl, this.getAuthHeader(token)); |
| 93 | + |
| 94 | + if (!Array.isArray(clients)) { |
| 95 | + this.logger.warn('No clients found in realm'); |
| 96 | + return; |
| 97 | + } |
| 98 | + |
| 99 | + this.logger.log(`Found ${clients.length} total clients in realm`); |
| 100 | + |
| 101 | + const orgClients = clients.filter( |
| 102 | + (client: { serviceAccountsEnabled: boolean; clientId: string }) => |
| 103 | + client.serviceAccountsEnabled && !client.clientId.startsWith('realm-') |
| 104 | + ); |
| 105 | + |
| 106 | + this.logger.log(`Found ${orgClients.length} service-account-enabled clients to process`); |
| 107 | + |
| 108 | + let created = 0; |
| 109 | + let skipped = 0; |
| 110 | + let failed = 0; |
| 111 | + |
| 112 | + for (const client of orgClients) { |
| 113 | + const result = await this.ensureClientProtocolMapper(realm, client.id, client.clientId, token); |
| 114 | + if ('created' === result) { |
| 115 | + created++; |
| 116 | + } else if ('skipped' === result) { |
| 117 | + skipped++; |
| 118 | + } else { |
| 119 | + failed++; |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + this.logger.log(`Per-client mapper results: ${created} created, ${skipped} already existed, ${failed} failed`); |
| 124 | + } |
| 125 | + |
| 126 | + private async ensureClientProtocolMapper( |
| 127 | + realm: string, |
| 128 | + clientIdpId: string, |
| 129 | + clientId: string, |
| 130 | + token: string |
| 131 | + ): Promise<'created' | 'skipped' | 'failed'> { |
| 132 | + try { |
| 133 | + const mappersUrl = await this.keycloakUrlService.GetClientProtocolMappersByIdURL(realm, clientIdpId); |
| 134 | + const existingMappers = await this.commonService.httpGet(mappersUrl, this.getAuthHeader(token)); |
| 135 | + |
| 136 | + const mapperExists = |
| 137 | + Array.isArray(existingMappers) && |
| 138 | + existingMappers.some((m: { name: string }) => 'ecosystem_access_mapper' === m.name); |
| 139 | + |
| 140 | + if (mapperExists) { |
| 141 | + this.logger.log(` [${clientId}] ecosystem_access_mapper already exists - SKIPPED`); |
| 142 | + return 'skipped'; |
| 143 | + } |
| 144 | + |
| 145 | + const mapperPayload = this.buildProtocolMapperPayload('ecosystem_access_mapper'); |
| 146 | + await this.commonService.httpPost(mappersUrl, mapperPayload, this.getAuthHeader(token)); |
| 147 | + this.logger.log(` [${clientId}] ecosystem_access_mapper CREATED`); |
| 148 | + return 'created'; |
| 149 | + } catch (error) { |
| 150 | + this.logger.warn(` [${clientId}] FAILED: ${error.message || error}`); |
| 151 | + return 'failed'; |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + private buildProtocolMapperPayload(name: string) { |
| 156 | + return { |
| 157 | + name, |
| 158 | + protocol: 'openid-connect', |
| 159 | + protocolMapper: 'oidc-usermodel-attribute-mapper', |
| 160 | + config: { |
| 161 | + 'user.attribute': 'ecosystem_access', |
| 162 | + 'claim.name': 'ecosystem_access', |
| 163 | + 'jsonType.label': 'JSON', |
| 164 | + 'id.token.claim': 'true', |
| 165 | + 'access.token.claim': 'true', |
| 166 | + 'userinfo.token.claim': 'true' |
| 167 | + } |
| 168 | + }; |
| 169 | + } |
| 170 | + |
| 171 | + private getAuthHeader(token: string) { |
| 172 | + return { headers: { authorization: `Bearer ${token}` } }; |
| 173 | + } |
| 174 | +} |
0 commit comments