Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow GHES repository to support deploy key #680

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 82 additions & 1 deletion __tests__/set-tokens.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,27 @@
import {getPublishRepo, setPersonalToken, setGithubToken} from '../src/set-tokens';
import {getPublishRepo, setPersonalToken, setGithubToken, setSSHKey} from '../src/set-tokens';
import {Inputs} from '../src/interfaces';

import fs from 'fs';
import * as exec from '@actions/exec';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import * as core from '@actions/core';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import * as io from '@actions/io';

jest.mock('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn().mockReturnValue({
stderr: '# hostname',
stdout: 'hostinfo',
exitCode: 0
})
}));
jest.mock('@actions/io', () => ({
mkdirP: jest.fn()
}));
jest.mock('@actions/core');
jest.mock('fs');
jest.mock('child_process');

beforeEach(() => {
jest.resetModules();
Expand All @@ -8,6 +31,64 @@ beforeEach(() => {

// });

describe('setSSHKey()', () => {
const createInputs = (): Inputs => ({
DeployKey: 'DEPLOY_KEY',
GithubToken: '',
PersonalToken: '',
PublishBranch: 'gh-pages',
PublishDir: '',
DestinationDir: '',
ExternalRepository: '',
AllowEmptyCommit: false,
KeepFiles: false,
ForceOrphan: false,
UserName: '',
UserEmail: '',
CommitMessage: '',
FullCommitMessage: '',
TagName: '',
TagMessage: '',
DisableNoJekyll: false,
CNAME: '',
ExcludeAssets: ''
});

beforeEach(() => {
jest.resetModules();
});

test('return correct repo address', async () => {
const inps: Inputs = createInputs();
const test = await setSSHKey(inps, 'owner/repo');
expect(test).toMatch('[email protected]:owner/repo.git');
});

test('set known_hosts with the ssh-keyscan output if it succeeded', async () => {
const inps: Inputs = createInputs();
await setSSHKey(inps, 'owner/repo');

const mockGetExecOutput = await exec.getExecOutput('');
expect(fs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('known_hosts'),
mockGetExecOutput.stderr + mockGetExecOutput.stdout
);
});

test('SSH key fallbacks to default value if ssh-keyscan fails', async () => {
const inps: Inputs = createInputs();
(exec.getExecOutput as jest.Mock).mockImplementation(() => {
throw new Error('error');
});

await setSSHKey(inps, 'owner/repo');
expect(fs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('known_hosts'),
expect.stringContaining('# github.com:22 SSH-2.0-babeld-1f0633a6')
);
});
});

describe('getPublishRepo()', () => {
test('return repository name', () => {
const test = getPublishRepo('', 'owner', 'repo');
Expand Down
23 changes: 17 additions & 6 deletions src/set-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,25 @@ export async function setSSHKey(inps: Inputs, publishRepo: string): Promise<stri
await exec.exec('chmod', ['700', sshDir]);

const knownHosts = path.join(sshDir, 'known_hosts');

// ssh-keyscan -t rsa github.com or serverUrl >> ~/.ssh/known_hosts on Ubuntu
const cmdSSHkeyscanOutput = `\
# ${getServerUrl().host}.com:22 SSH-2.0-babeld-1f0633a6
${
getServerUrl().host
} ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
const foundKnownHostKey = await (async () => {
try {
const keyscanOutput = await exec.getExecOutput('ssh-keyscan', [
'-t',
'rsa',
getServerUrl().host
]);
return keyscanOutput.stderr + keyscanOutput.stdout;
} catch (e) {
return `\
# github.com:22 SSH-2.0-babeld-1f0633a6
github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
`;
fs.writeFileSync(knownHosts, cmdSSHkeyscanOutput + '\n');
}
})();

fs.writeFileSync(knownHosts, foundKnownHostKey);
core.info(`[INFO] wrote ${knownHosts}`);
await exec.exec('chmod', ['600', knownHosts]);

Expand Down