diff --git a/src/commands/onprem.ts b/src/commands/onprem.ts index b48d81d..e09cffe 100644 --- a/src/commands/onprem.ts +++ b/src/commands/onprem.ts @@ -7,7 +7,7 @@ export async function onpremCMD(namespace?: string) { const k8s = new K8s(); const utils = new Utils(); - const cfCreds = cf.getCredentials(); + const cfCreds = await cf.getCredentials(); if (cfCreds && cfCreds.baseUrl === 'https://g.codefresh.io/api') { console.error( diff --git a/src/commands/pipelines.ts b/src/commands/pipelines.ts index 055160c..8f0d083 100644 --- a/src/commands/pipelines.ts +++ b/src/commands/pipelines.ts @@ -6,7 +6,7 @@ export async function pipelinesCMD(namespace?: string, runtime?: string) { const cf = new Codefresh(); const k8s = new K8s(); const utils = new Utils(); - const cfCreds = cf.getCredentials(); + const cfCreds = await cf.getCredentials(); if (!namespace) { logger.info('No namespace provided, prompting user to select one.'); diff --git a/src/logic/codefresh.ts b/src/logic/codefresh.ts index 1ec1b6e..48f6700 100644 --- a/src/logic/codefresh.ts +++ b/src/logic/codefresh.ts @@ -7,7 +7,7 @@ export class Codefresh { logger.info('Codefresh class instance created.'); } - getCredentials() { + async getCredentials() { logger.info('Fetching Codefresh credentials...'); const envToken = Deno.env.get('CF_API_KEY'); const envUrl = Deno.env.get('CF_URL'); @@ -15,10 +15,15 @@ export class Codefresh { if (envToken && envUrl) { logger.info('Using Codefresh credentials from environment variables.'); + const formattedUrl = envUrl.endsWith('/') ? envUrl.slice(0, -1) : envUrl; cf_creds = { headers: { Authorization: envToken }, - baseUrl: `${envUrl}/api`, + baseUrl: `${formattedUrl}/api`, }; + const isValid = await this.validateCredentials(cf_creds); + if (!isValid) { + return null; + } return cf_creds; } @@ -36,10 +41,31 @@ export class Codefresh { headers: { Authorization: currentContext.token }, baseUrl: `${currentContext.url}/api`, }; + const isValid = await this.validateCredentials(cf_creds); + if (!isValid) { + return null; + } } + return cf_creds; } + async validateCredentials(cfCreds: CodefreshCredentials) { + logger.info('Validating Codefresh credentials...'); + const tokenID = cfCreds.headers['Authorization'].split('.')[0]; + const response = await fetch(`${cfCreds.baseUrl}/auth/key/${tokenID}`, { + method: 'GET', + headers: cfCreds.headers, + }); + + if (!response.ok) { + logger.error(`Invalid Codefresh credentials. Status: ${response.status}`); + return false; + } + logger.info('Codefresh credentials are valid.'); + return true; + } + async getAccountRuntimes(cfCreds: CodefreshCredentials) { logger.info('Fetching account runtimes...'); const response = await fetch(`${cfCreds.baseUrl}/runtime-environments`, { @@ -47,6 +73,7 @@ export class Codefresh { headers: cfCreds.headers, }); const runtimes = await response.json(); + console.debug(runtimes); return runtimes; }