Skip to content

Commit

Permalink
Revert "Avoid socket hangup: enhance Keycloak auth in group service w…
Browse files Browse the repository at this point in the history
…ith retry logic; improve error handling in namespace service login"

This reverts commit e964a72.
  • Loading branch information
rustyjux committed Jan 14, 2025
1 parent 5e8d9c0 commit 39c30d4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 49 deletions.
62 changes: 19 additions & 43 deletions src/services/keycloak/group-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,66 +13,43 @@ import UserRepresentation from '@keycloak/keycloak-admin-client/lib/defs/userRep
const logger = Logger('kc.group');

export class KeycloakGroupService {
private static instanceCount = 0; // Track total instances created
private instanceId: string;
private createdAt: Date;
private allGroups: any = undefined;
private kcAdminClient: KeycloakAdminClient;
private clientId: string;
private clientSecret: string;
private lastAuthTime: number = 0;
private readonly AUTH_TIMEOUT = 280 * 1000; // 280 seconds (slightly less than typical 5 min token lifetime)

constructor(issuerUrl: string) {
this.instanceId = `kc-group-${++KeycloakGroupService.instanceCount}`;
this.createdAt = new Date();
logger.info('[Instance Created] id=%s, created=%s', this.instanceId, this.createdAt);

const baseUrl = issuerUrl.substr(0, issuerUrl.indexOf('/realms'));
const realmName = issuerUrl.substr(issuerUrl.lastIndexOf('/') + 1);
logger.debug('%s %s', baseUrl, realmName);
this.kcAdminClient = new KcAdminClient({ baseUrl, realmName });
}

private async ensureAuthenticated(): Promise<void> {
if (this.clientId && (Date.now() - this.lastAuthTime > this.AUTH_TIMEOUT)) {
logger.debug('[ensureAuthenticated] Re-authenticating due to timeout');
await this.login(this.clientId, this.clientSecret);
}
}

public async cacheGroups() {
this.allGroups = await this.getAllGroups();
}

public async login(
clientId: string,
clientSecret: string,
retryAttempts: number = 3
clientSecret: string
): Promise<KeycloakGroupService> {
this.clientId = clientId;
this.clientSecret = clientSecret;

const result = await this._login(retryAttempts);
this.lastAuthTime = Date.now();
return result;
}

private async _login(retryAttempts: number): Promise<KeycloakGroupService> {
logger.debug('[login] %s', this.clientId);
logger.debug('[login] %s', clientId);

for (let attempt = 1; attempt <= retryAttempts; attempt++) {
try {
await this.kcAdminClient
.auth({
grantType: 'client_credentials',
clientId: this.clientId,
clientSecret: this.clientSecret,
});
return this;
} catch (err: any) {
if (attempt === retryAttempts) {
logger.error('[login] Login failed after %d attempts: %s', retryAttempts, err);
throw err;
}
logger.warn('[login] Attempt %d failed, retrying: %s', attempt, err);
// Add exponential backoff
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 100));
}
}
await this.kcAdminClient
.auth({
grantType: 'client_credentials',
clientId: clientId,
clientSecret: clientSecret,
})
.catch((err: any) => {
logger.error('[login] Login failed %s', err);
throw err;
});
return this;
}

Expand Down Expand Up @@ -100,7 +77,6 @@ export class KeycloakGroupService {
}

public async updateGroup(group: GroupRepresentation): Promise<void> {
await this.ensureAuthenticated();
logger.debug('[updateGroup] %j', group);
await this.kcAdminClient.groups.update({ id: group.id }, group);
}
Expand Down
7 changes: 1 addition & 6 deletions src/services/org-groups/namespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,7 @@ export class NamespaceService {
}

async login(clientId: string, clientSecret: string) {
try {
await this.groupService.login(clientId, clientSecret);
} catch (err) {
logger.error('[login] Failed to login to Keycloak: %s', err);
throw new Error('Failed to authenticate with Keycloak');
}
await this.groupService.login(clientId, clientSecret);
}

async markNotification(ns: string, viewed: boolean): Promise<void> {
Expand Down

0 comments on commit 39c30d4

Please sign in to comment.