Skip to content
Snippets Groups Projects
Select Git revision
21 results Searching

auth.ts

Blame
  • auth.ts 7.65 KiB
    import { PLATFORM_HOST_TYPES } from '../../constants/platforms';
    import { logger } from '../../logger';
    import type { HostRule } from '../../types';
    import { detectPlatform } from '../common';
    import { find, getAll } from '../host-rules';
    import { regEx } from '../regex';
    import { createURLFromHostOrURL, isHttpUrl } from '../url';
    import type { AuthenticationRule } from './types';
    import { parseGitUrl } from './url';
    
    const githubApiUrls = new Set([
      'github.com',
      'api.github.com',
      'https://api.github.com',
      'https://api.github.com/',
    ]);
    
    /**
     * Add authorization to a Git Url and returns a new environment variables object
     * @returns a new NodeJS.ProcessEnv object without modifying any input parameters
     */
    export function getGitAuthenticatedEnvironmentVariables(
      originalGitUrl: string,
      { token, username, password, hostType, matchHost }: HostRule,
      environmentVariables?: NodeJS.ProcessEnv,
    ): NodeJS.ProcessEnv {
      if (!token && !(username && password)) {
        logger.warn(
          // TODO: types (#22198)
          `Could not create environment variable for ${matchHost!} as neither token or username and password was set`,
        );
        return { ...environmentVariables };
      }
    
      // check if the environmentVariables already contain a GIT_CONFIG_COUNT or if the process has one
      const gitConfigCountEnvVariable =
        environmentVariables?.GIT_CONFIG_COUNT ?? process.env.GIT_CONFIG_COUNT;
      let gitConfigCount = 0;
      if (gitConfigCountEnvVariable) {
        // passthrough the gitConfigCountEnvVariable environment variable as start value of the index count
        gitConfigCount = parseInt(gitConfigCountEnvVariable, 10);
        if (Number.isNaN(gitConfigCount)) {
          logger.warn(
            `Found GIT_CONFIG_COUNT env variable, but couldn't parse the value to an integer: ${String(
              process.env.GIT_CONFIG_COUNT,
            )}. Ignoring it.`,
          );
          gitConfigCount = 0;
        }
      }
      let authenticationRules: AuthenticationRule[];
      if (token) {
        authenticationRules = getAuthenticationRulesWithToken(
          originalGitUrl,
          hostType,
          token,
        );
      } else {
        const encodedUsername = encodeURIComponent(username!);
        const encodedPassword = encodeURIComponent(password!);
    
        authenticationRules = getAuthenticationRules(
          originalGitUrl,
          hostType,
          `${encodedUsername}:${encodedPassword}`,
        );
      }
    
      // create a shallow copy of the environmentVariables as base so we don't modify the input parameter object
      // add the two new config key and value to the returnEnvironmentVariables object