Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
ericsciple committed Mar 2, 2020
1 parent d0b21e9 commit 744fdac
Show file tree
Hide file tree
Showing 6 changed files with 5 additions and 539 deletions.
306 changes: 1 addition & 305 deletions __test__/git-auth-helper.test.ts
Expand Up @@ -3,11 +3,9 @@ import * as fs from 'fs'
import * as gitAuthHelper from '../lib/git-auth-helper'
import * as io from '@actions/io'
import * as path from 'path'
import * as stateHelper from '../lib/state-helper'
import {IGitCommandManager} from '../lib/git-command-manager'
import {IGitSourceSettings} from '../lib/git-source-settings'

const isWindows = process.platform === 'win32'
const testWorkspace = path.join(__dirname, '_temp', 'git-auth-helper')
const originalRunnerTemp = process.env['RUNNER_TEMP']
const originalHome = process.env['HOME']
Expand All @@ -18,24 +16,14 @@ let runnerTemp: string
let tempHomedir: string
let git: IGitCommandManager & {env: {[key: string]: string}}
let settings: IGitSourceSettings
let sshPath: string

describe('git-auth-helper tests', () => {
beforeAll(async () => {
// SSH
sshPath = await io.which('ssh')

// Clear test workspace
await io.rmRF(testWorkspace)
})

beforeEach(() => {
// Mock state-helper
jest.spyOn(stateHelper, 'setSshKeyPath').mockImplementation(jest.fn())
jest
.spyOn(stateHelper, 'setSshKnownHostsPath')
.mockImplementation(jest.fn())

// Mock setSecret
jest.spyOn(core, 'setSecret').mockImplementation((secret: string) => {})

Expand Down Expand Up @@ -120,40 +108,6 @@ describe('git-auth-helper tests', () => {
}
)

const configureAuth_copiesUserKnownHosts =
'configureAuth copies user known hosts'
it(configureAuth_copiesUserKnownHosts, async () => {
if (!sshPath) {
process.stdout.write(
`Skipped test "${configureAuth_copiesUserKnownHosts}". Executable 'ssh' not found in the PATH.\n`
)
return
}

// Arange
await setup(configureAuth_copiesUserKnownHosts)
expect(settings.sshKey).toBeTruthy() // sanity check
await fs.promises.mkdir(path.join(tempHomedir, '.ssh'))
await fs.promises.writeFile(
path.join(tempHomedir, '.ssh', 'known_hosts'),
'some-domain.com ssh-rsa ABCDEF'
)

// Act
const authHelper = gitAuthHelper.createAuthHelper(git, settings)
await authHelper.configureAuth()

// Assert known hosts
const actualSshKnownHostsPath = await getActualSshKnownHostsPath()
const actualSshKnownHostsContent = (
await fs.promises.readFile(actualSshKnownHostsPath)
).toString()
expect(actualSshKnownHostsContent).toMatch(
/some-domain\.com ssh-rsa ABCDEF/
)
expect(actualSshKnownHostsContent).toMatch(/github\.com ssh-rsa AAAAB3N/)
})

const configureAuth_registersBasicCredentialAsSecret =
'configureAuth registers basic credential as secret'
it(configureAuth_registersBasicCredentialAsSecret, async () => {
Expand All @@ -175,149 +129,6 @@ describe('git-auth-helper tests', () => {
expect(setSecretSpy).toHaveBeenCalledWith(expectedSecret)
})

const configureAuth_setsSshCommandEnvVarWhenPersistCredentialsFalse =
'configureAuth sets SSH command env var when persist-credentials false'
it(
configureAuth_setsSshCommandEnvVarWhenPersistCredentialsFalse,
async () => {
if (!sshPath) {
process.stdout.write(
`Skipped test "${configureAuth_setsSshCommandEnvVarWhenPersistCredentialsFalse}". Executable 'ssh' not found in the PATH.\n`
)
return
}

// Arrange
await setup(configureAuth_setsSshCommandEnvVarWhenPersistCredentialsFalse)
settings.persistCredentials = false
const authHelper = gitAuthHelper.createAuthHelper(git, settings)

// Act
await authHelper.configureAuth()

// Assert git env var
const actualKeyPath = await getActualSshKeyPath()
const actualKnownHostsPath = await getActualSshKnownHostsPath()
const expectedSshCommand = `"${sshPath}" -i "$RUNNER_TEMP/${path.basename(
actualKeyPath
)}" -o StrictHostKeyChecking=yes -o CheckHostIP=no -o "UserKnownHostsFile=$RUNNER_TEMP/${path.basename(
actualKnownHostsPath
)}"`
expect(git.env['GIT_SSH_COMMAND']).toBe(expectedSshCommand)

// Asserty git config
const gitConfigLines = (await fs.promises.readFile(localGitConfigPath))
.toString()
.split('\n')
.filter(x => x)
expect(gitConfigLines).toHaveLength(1)
expect(gitConfigLines[0]).toMatch(/^http\./)
}
)

const configureAuth_setsSshCommandWhenPersistCredentialsTrue =
'configureAuth sets SSH command when persist-credentials true'
it(configureAuth_setsSshCommandWhenPersistCredentialsTrue, async () => {
if (!sshPath) {
process.stdout.write(
`Skipped test "${configureAuth_setsSshCommandWhenPersistCredentialsTrue}". Executable 'ssh' not found in the PATH.\n`
)
return
}

// Arrange
await setup(configureAuth_setsSshCommandWhenPersistCredentialsTrue)
const authHelper = gitAuthHelper.createAuthHelper(git, settings)

// Act
await authHelper.configureAuth()

// Assert git env var
const actualKeyPath = await getActualSshKeyPath()
const actualKnownHostsPath = await getActualSshKnownHostsPath()
const expectedSshCommand = `"${sshPath}" -i "$RUNNER_TEMP/${path.basename(
actualKeyPath
)}" -o StrictHostKeyChecking=yes -o CheckHostIP=no -o "UserKnownHostsFile=$RUNNER_TEMP/${path.basename(
actualKnownHostsPath
)}"`
expect(git.env['GIT_SSH_COMMAND']).toBe(expectedSshCommand)

// Asserty git config
expect(git.config).toHaveBeenCalledWith(
'core.sshCommand',
expectedSshCommand
)
})

const configureAuth_writesExplicitKnownHosts =
'configureAuth writes explicit known hosts'
it(configureAuth_writesExplicitKnownHosts, async () => {
if (!sshPath) {
process.stdout.write(
`Skipped test "${configureAuth_writesExplicitKnownHosts}". Executable 'ssh' not found in the PATH.\n`
)
return
}

// Arrange
await setup(configureAuth_writesExplicitKnownHosts)
expect(settings.sshKey).toBeTruthy() // sanity check
settings.sshKnownHosts = 'my-custom-host.com ssh-rsa ABC123'
const authHelper = gitAuthHelper.createAuthHelper(git, settings)

// Act
await authHelper.configureAuth()

// Assert known hosts
const actualSshKnownHostsPath = await getActualSshKnownHostsPath()
const actualSshKnownHostsContent = (
await fs.promises.readFile(actualSshKnownHostsPath)
).toString()
expect(actualSshKnownHostsContent).toMatch(
/my-custom-host\.com ssh-rsa ABC123/
)
expect(actualSshKnownHostsContent).toMatch(/github\.com ssh-rsa AAAAB3N/)
})

const configureAuth_writesSshKeyAndImplicitKnownHosts =
'configureAuth writes SSH key and implicit known hosts'
it(configureAuth_writesSshKeyAndImplicitKnownHosts, async () => {
if (!sshPath) {
process.stdout.write(
`Skipped test "${configureAuth_writesSshKeyAndImplicitKnownHosts}". Executable 'ssh' not found in the PATH.\n`
)
return
}

// Arrange
await setup(configureAuth_writesSshKeyAndImplicitKnownHosts)
expect(settings.sshKey).toBeTruthy() // sanity check
const authHelper = gitAuthHelper.createAuthHelper(git, settings)

// Act
await authHelper.configureAuth()

// Assert SSH key
const actualSshKeyPath = await getActualSshKeyPath()
expect(actualSshKeyPath).toBeTruthy()
const actualSshKeyContent = (
await fs.promises.readFile(actualSshKeyPath)
).toString()
expect(actualSshKeyContent).toBe(settings.sshKey + '\n')
if (!isWindows) {
expect((await fs.promises.stat(actualSshKeyPath)).mode & 0o777).toBe(
0o600
)
}

// Assert known hosts
const actualSshKnownHostsPath = await getActualSshKnownHostsPath()
const actualSshKnownHostsContent = (
await fs.promises.readFile(actualSshKnownHostsPath)
).toString()
expect(actualSshKnownHostsContent).toMatch(/github\.com ssh-rsa AAAAB3N/)
})

const configureGlobalAuth_copiesGlobalGitConfig =
'configureGlobalAuth copies global git config'
it(configureGlobalAuth_copiesGlobalGitConfig, async () => {
Expand Down Expand Up @@ -431,7 +242,6 @@ describe('git-auth-helper tests', () => {
await setup(
configureSubmoduleAuth_configuresTokenWhenPersistCredentialsTrue
)
settings.sshKey = ''
const authHelper = gitAuthHelper.createAuthHelper(git, settings)
await authHelper.configureAuth()
;(git.submoduleForeach as jest.Mock<any, any>).mockClear() // reset calls
Expand All @@ -444,90 +254,6 @@ describe('git-auth-helper tests', () => {
}
)

const configureSubmoduleAuth_configuresSshCommandWhenPersistCredentialsTrue =
'configureSubmoduleAuth configures SSH command when persist credentials true'
it(
configureSubmoduleAuth_configuresSshCommandWhenPersistCredentialsTrue,
async () => {
if (!sshPath) {
process.stdout.write(
`Skipped test "${configureSubmoduleAuth_configuresSshCommandWhenPersistCredentialsTrue}". Executable 'ssh' not found in the PATH.\n`
)
return
}

// Arrange
await setup(
configureSubmoduleAuth_configuresSshCommandWhenPersistCredentialsTrue
)
const authHelper = gitAuthHelper.createAuthHelper(git, settings)
await authHelper.configureAuth()
;(git.submoduleForeach as jest.Mock<any, any>).mockClear() // reset calls

// Act
await authHelper.configureSubmoduleAuth()

// Assert
expect(git.submoduleForeach).toHaveBeenCalledTimes(2)
}
)

const removeAuth_removesSsh = 'removeAuth removes SSH'
it(removeAuth_removesSsh, async () => {
if (!sshPath) {
process.stdout.write(
`Skipped test "${removeAuth_removesSsh}". Executable 'ssh' not found in the PATH.\n`
)
return
}

// Arrange
await setup(removeAuth_removesSsh)
const authHelper = gitAuthHelper.createAuthHelper(git, settings)
await authHelper.configureAuth()
let gitConfigContent = (
await fs.promises.readFile(localGitConfigPath)
).toString()
expect(gitConfigContent.indexOf('core.sshCommand')).toBeGreaterThanOrEqual(
0
) // sanity check
const actualKeyPath = await getActualSshKeyPath()
expect(actualKeyPath).toBeTruthy()
await fs.promises.stat(actualKeyPath)
const actualKnownHostsPath = await getActualSshKnownHostsPath()
expect(actualKnownHostsPath).toBeTruthy()
await fs.promises.stat(actualKnownHostsPath)

// Act
await authHelper.removeAuth()

// Assert git config
gitConfigContent = (
await fs.promises.readFile(localGitConfigPath)
).toString()
expect(gitConfigContent.indexOf('core.sshCommand')).toBeLessThan(0)

// Assert SSH key file
try {
await fs.promises.stat(actualKeyPath)
throw new Error('SSH key should have been deleted')
} catch (err) {
if (err.code !== 'ENOENT') {
throw err
}
}

// Assert known hosts file
try {
await fs.promises.stat(actualKnownHostsPath)
throw new Error('SSH known hosts should have been deleted')
} catch (err) {
if (err.code !== 'ENOENT') {
throw err
}
}
})

const removeAuth_removesToken = 'removeAuth removes token'
it(removeAuth_removesToken, async () => {
// Arrange
Expand Down Expand Up @@ -675,36 +401,6 @@ async function setup(testName: string): Promise<void> {
ref: 'refs/heads/master',
repositoryName: 'my-repo',
repositoryOwner: 'my-org',
repositoryPath: '',
sshKey: sshPath ? 'some ssh private key' : '',
sshKnownHosts: '',
sshStrict: true
repositoryPath: ''
}
}

async function getActualSshKeyPath(): Promise<string> {
let actualTempFiles = (await fs.promises.readdir(runnerTemp))
.sort()
.map(x => path.join(runnerTemp, x))
if (actualTempFiles.length === 0) {
return ''
}

expect(actualTempFiles).toHaveLength(2)
expect(actualTempFiles[0].endsWith('_known_hosts')).toBeFalsy()
return actualTempFiles[0]
}

async function getActualSshKnownHostsPath(): Promise<string> {
let actualTempFiles = (await fs.promises.readdir(runnerTemp))
.sort()
.map(x => path.join(runnerTemp, x))
if (actualTempFiles.length === 0) {
return ''
}

expect(actualTempFiles).toHaveLength(2)
expect(actualTempFiles[1].endsWith('_known_hosts')).toBeTruthy()
expect(actualTempFiles[1].startsWith(actualTempFiles[0])).toBeTruthy()
return actualTempFiles[1]
}

0 comments on commit 744fdac

Please sign in to comment.