Skip to content

fix: Fix for GHES to allow variations in GitHub Actions bot user id #222

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

Merged
merged 2 commits into from
Jun 10, 2025
Merged
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
18 changes: 18 additions & 0 deletions __tests__/helpers/octokit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type EndpointNames = {
issues: 'createComment' | 'deleteComment' | 'listComments';
pulls: 'listCommits' | 'listFiles';
repos: 'getCommit' | 'listTags' | 'listReleases' | 'createRelease' | 'deleteRelease';
users: 'getByUsername';
};

// Type guard that ensures the method name is valid for the given namespace K.
Expand Down Expand Up @@ -164,12 +165,26 @@ export function resetMockStore() {
headers: {},
},
},
users: {
getByUsername: {
data: {
login: 'github-actions[bot]',
id: 41898282,
type: 'Bot',
site_admin: false,
},
status: 200,
url: 'https://api.github.com/users/github-actions[bot]',
headers: {},
},
},
},
implementations: {
git: {},
issues: {},
pulls: {},
repos: {},
users: {},
},
};
}
Expand Down Expand Up @@ -302,6 +317,9 @@ export function createDefaultOctokitMock(): OctokitRestApi {
createRelease: vi.fn().mockImplementation(() => getMockResponse('repos.createRelease')),
deleteRelease: vi.fn().mockImplementation(() => getMockResponse('repos.deleteRelease')),
},
users: {
getByUsername: vi.fn().mockImplementation((params) => getMockResponse('users.getByUsername', params)),
},
},
paginate: {
iterator: <T>(
Expand Down
21 changes: 2 additions & 19 deletions __tests__/pull-request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,7 @@ import type { TerraformModule } from '@/terraform-module';
import { stubOctokitImplementation, stubOctokitReturnData } from '@/tests/helpers/octokit';
import { createMockTerraformModule } from '@/tests/helpers/terraform-module';
import type { GitHubRelease } from '@/types';
import {
BRANDING_COMMENT,
GITHUB_ACTIONS_BOT_USER_ID,
PR_RELEASE_MARKER,
PR_SUMMARY_MARKER,
WIKI_STATUS,
} from '@/utils/constants';
import { BRANDING_COMMENT, PR_RELEASE_MARKER, PR_SUMMARY_MARKER, WIKI_STATUS } from '@/utils/constants';
import { debug, endGroup, info, startGroup } from '@actions/core';
import { RequestError } from '@octokit/request-error';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
Expand Down Expand Up @@ -55,25 +49,14 @@ describe('pull-request', () => {
context.useMockOctokit();
});

it('should return false when release marker is found in comments from non github-actions user', async () => {
it('should return true when release marker is found in comments', async () => {
stubOctokitReturnData('issues.listComments', {
data: [
{ user: { id: 123 }, body: 'Some comment' },
{ user: { id: 123 }, body: PR_RELEASE_MARKER },
{ user: { id: 123 }, body: 'Another comment' },
],
});
expect(await hasReleaseComment()).toBe(false);
});

it('should return true when release marker is found in comments from github-actions user', async () => {
stubOctokitReturnData('issues.listComments', {
data: [
{ user: { id: 123 }, body: 'Some comment' },
{ user: { id: GITHUB_ACTIONS_BOT_USER_ID }, body: PR_RELEASE_MARKER },
{ user: { id: 123 }, body: 'Another comment' },
],
});
expect(await hasReleaseComment()).toBe(true);
});

Expand Down
8 changes: 4 additions & 4 deletions __tests__/utils/constants.test.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import {
BRANDING_COMMENT,
BRANDING_WIKI,
GITHUB_ACTIONS_BOT_EMAIL,
GITHUB_ACTIONS_BOT_NAME,
GITHUB_ACTIONS_BOT_USERNAME,
PROJECT_URL,
PR_RELEASE_MARKER,
PR_SUMMARY_MARKER,
WIKI_TITLE_REPLACEMENTS,
} from '@/utils/constants';
import { describe, expect, it } from 'vitest';

describe('constants', () => {
describe('utils/constants', () => {
it('should have the correct GitHub Actions bot name', () => {
expect(GITHUB_ACTIONS_BOT_NAME).toBe('GitHub Actions');
});

it('should have the correct GitHub Actions bot email', () => {
expect(GITHUB_ACTIONS_BOT_EMAIL).toBe('41898282+github-actions[bot]@users.noreply.github.com');
it('should have the correct GitHub Actions bot username', () => {
expect(GITHUB_ACTIONS_BOT_USERNAME).toBe('github-actions[bot]');
});

it('should have the correct PR summary marker', () => {
Expand Down
24 changes: 24 additions & 0 deletions __tests__/utils/github.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { context } from '@/mocks/context';
import { getGitHubActionsBotEmail } from '@/utils/github';
import { beforeAll, describe, expect, it } from 'vitest';

describe('utils/github', () => {
describe('getGitHubActionsBotEmail - real API queries', () => {
beforeAll(async () => {
if (!process.env.GITHUB_TOKEN) {
throw new Error('GITHUB_TOKEN environment variable must be set for these tests');
}
await context.useRealOctokit();
});

it('should return the correct email format for GitHub.com public API', async () => {
// This test uses the real GitHub API and expects the standard GitHub.com user ID
// for the github-actions[bot] user, which is 41898282

const result = await getGitHubActionsBotEmail();

// Assert
expect(result).toBe('41898282+github-actions[bot]@users.noreply.github.com');
});
});
});
22 changes: 14 additions & 8 deletions __tests__/wiki.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ describe('wiki', async () => {

afterAll(() => {
vi.mocked(execFileSync).mockImplementation(vi.fn());
vi.resetAllMocks(); // Unclears the console.log
});

it('should generate all required wiki files', async () => {
Expand Down Expand Up @@ -259,11 +260,16 @@ describe('wiki', async () => {
});

describe('commitAndPushWikiChanges()', () => {
it('should commit and push changes when changes are detected', () => {
beforeAll(() => {
// Ensure we're using the mock octokit, not real one
context.useMockOctokit();
});

it('should commit and push changes when changes are detected', async () => {
// Mock git status to indicate changes exist
vi.mocked(execFileSync).mockImplementationOnce(() => Buffer.from('M _Sidebar.md\n'));

commitAndPushWikiChanges();
await commitAndPushWikiChanges();

// Verify git commands were called in correct order
const gitCalls = vi.mocked(execFileSync).mock.calls.map((call) => call?.[1]?.join(' ') || '');
Expand All @@ -284,11 +290,11 @@ describe('wiki', async () => {
expect(endGroup).toHaveBeenCalled();
});

it('should skip commit and push when no changes are detected', () => {
it('should skip commit and push when no changes are detected', async () => {
// Mock git status to indicate no changes
vi.mocked(execFileSync).mockImplementationOnce(() => Buffer.from(''));

commitAndPushWikiChanges();
await commitAndPushWikiChanges();

// Verify only status check was called
const gitCalls = vi.mocked(execFileSync).mock.calls.map((call) => call?.[1]?.join(' ') || '');
Expand All @@ -301,23 +307,23 @@ describe('wiki', async () => {
expect(endGroup).toHaveBeenCalled();
});

it('should handle git command failures gracefully', () => {
it('should handle git command failures gracefully', async () => {
// Mock git status to indicate changes exist but make add command fail
vi.mocked(execFileSync)
.mockImplementationOnce(() => Buffer.from('M _Sidebar.md\n'))
.mockImplementationOnce(() => {
throw new Error('Git command failed');
});

expect(() => commitAndPushWikiChanges()).toThrow('Git command failed');
await expect(commitAndPushWikiChanges()).rejects.toThrow('Git command failed');

expect(startGroup).toHaveBeenCalledWith('Committing and pushing changes to wiki');
expect(info).toHaveBeenCalledWith('Checking for changes in wiki repository');
expect(info).toHaveBeenCalledWith('git status output: M _Sidebar.md');
expect(endGroup).toHaveBeenCalled();
});

it('should not use complete PR information in commit message', () => {
it('should not use complete PR information in commit message', async () => {
// Set up PR context with multiline body
context.set({
prBody: 'Line 1\nLine 2\nLine 3',
Expand All @@ -328,7 +334,7 @@ describe('wiki', async () => {
// Mock git status to indicate changes exist
vi.mocked(execFileSync).mockImplementationOnce(() => Buffer.from('M _Sidebar.md\n'));

commitAndPushWikiChanges();
await commitAndPushWikiChanges();

// Verify commit message format
const commitCall = vi.mocked(execFileSync).mock.calls.find((call) => call?.[1]?.includes('commit'));
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async function handlePullRequestMergedEvent(
ensureTerraformDocsConfigDoesNotExist();
checkoutWiki();
await generateWikiFiles(terraformModules);
commitAndPushWikiChanges();
await commitAndPushWikiChanges();
}
}

Expand Down
11 changes: 2 additions & 9 deletions src/pull-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,7 @@ import { config } from '@/config';
import { context } from '@/context';
import { TerraformModule } from '@/terraform-module';
import type { CommitDetails, GitHubRelease, WikiStatusResult } from '@/types';
import {
BRANDING_COMMENT,
GITHUB_ACTIONS_BOT_USER_ID,
PROJECT_URL,
PR_RELEASE_MARKER,
PR_SUMMARY_MARKER,
WIKI_STATUS,
} from '@/utils/constants';
import { BRANDING_COMMENT, PROJECT_URL, PR_RELEASE_MARKER, PR_SUMMARY_MARKER, WIKI_STATUS } from '@/utils/constants';

import { getWikiLink } from '@/wiki';
import { debug, endGroup, info, startGroup } from '@actions/core';
Expand Down Expand Up @@ -38,7 +31,7 @@ export async function hasReleaseComment(): Promise<boolean> {

for await (const { data } of iterator) {
for (const comment of data) {
if (comment.user?.id === GITHUB_ACTIONS_BOT_USER_ID && comment.body?.includes(PR_RELEASE_MARKER)) {
if (comment.body?.includes(PR_RELEASE_MARKER)) {
return true;
}
}
Expand Down
6 changes: 4 additions & 2 deletions src/releases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import { config } from '@/config';
import { context } from '@/context';
import { TerraformModule } from '@/terraform-module';
import type { GitHubRelease } from '@/types';
import { GITHUB_ACTIONS_BOT_EMAIL, GITHUB_ACTIONS_BOT_NAME } from '@/utils/constants';
import { GITHUB_ACTIONS_BOT_NAME } from '@/utils/constants';
import { copyModuleContents } from '@/utils/file';
import { getGitHubActionsBotEmail } from '@/utils/github';
import { debug, endGroup, info, startGroup } from '@actions/core';
import type { RestEndpointMethodTypes } from '@octokit/plugin-rest-endpoint-methods';
import { RequestError } from '@octokit/request-error';
Expand Down Expand Up @@ -139,13 +140,14 @@ export async function createTaggedReleases(terraformModules: TerraformModule[]):
// Git operations: commit the changes and tag the release
const commitMessage = `${module.getReleaseTag()}\n\n${prTitle}\n\n${prBody}`.trim();
const gitPath = await which('git');
const githubActionsBotEmail = await getGitHubActionsBotEmail();

// Execute git commands in temp directory without inheriting stdio to avoid output pollution
const gitOpts: ExecSyncOptions = { cwd: tmpDir };

for (const cmd of [
['config', '--local', 'user.name', GITHUB_ACTIONS_BOT_NAME],
['config', '--local', 'user.email', GITHUB_ACTIONS_BOT_EMAIL],
['config', '--local', 'user.email', githubActionsBotEmail],
['add', '.'],
['commit', '-m', commitMessage.trim()],
['tag', releaseTag],
Expand Down
3 changes: 1 addition & 2 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,8 @@ export const WIKI_HOME_FILENAME = 'Home.md';
export const WIKI_SIDEBAR_FILENAME = '_Sidebar.md';
export const WIKI_FOOTER_FILENAME = '_Footer.md';

export const GITHUB_ACTIONS_BOT_USER_ID = 41898282;
export const GITHUB_ACTIONS_BOT_NAME = 'GitHub Actions';
export const GITHUB_ACTIONS_BOT_EMAIL = '41898282+github-actions[bot]@users.noreply.github.com';
export const GITHUB_ACTIONS_BOT_USERNAME = 'github-actions[bot]';

export const PR_SUMMARY_MARKER = '<!-- techpivot/terraform-module-releaser — pr-summary-marker -->';
export const PR_RELEASE_MARKER = '<!-- techpivot/terraform-module-releaser — release-marker -->';
Expand Down
19 changes: 19 additions & 0 deletions src/utils/github.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { context } from '@/context';
import { GITHUB_ACTIONS_BOT_USERNAME } from '@/utils/constants';

/**
* Retrieves the GitHub Actions bot email address dynamically by querying the GitHub API.
* This function handles both GitHub.com and GitHub Enterprise Server environments.
*
* The email format follows GitHub's standard: {user_id}+{username}@users.noreply.github.com
*
* @returns {Promise<string>} The GitHub Actions bot email address
* @throws {Error} If the API request fails or the user information cannot be retrieved
*/
export async function getGitHubActionsBotEmail(): Promise<string> {
const response = await context.octokit.rest.users.getByUsername({
username: GITHUB_ACTIONS_BOT_USERNAME,
});

return `${response.data.id}+${GITHUB_ACTIONS_BOT_USERNAME}@users.noreply.github.com`;
}
10 changes: 6 additions & 4 deletions src/wiki.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import type { TerraformModule } from '@/terraform-module';
import type { ExecSyncError, WikiStatusResult } from '@/types';
import {
BRANDING_WIKI,
GITHUB_ACTIONS_BOT_EMAIL,
GITHUB_ACTIONS_BOT_NAME,
PROJECT_URL,
WIKI_FOOTER_FILENAME,
Expand All @@ -22,6 +21,7 @@ import {
WIKI_TITLE_REPLACEMENTS,
} from '@/utils/constants';
import { removeDirectoryContents } from '@/utils/file';
import { getGitHubActionsBotEmail } from '@/utils/github';
import { endGroup, info, startGroup } from '@actions/core';
import pLimit from 'p-limit';
import which from 'which';
Expand Down Expand Up @@ -558,9 +558,9 @@ export async function generateWikiFiles(terraformModules: TerraformModule[]): Pr
* pushes them to the remote wiki repository. If no changes are detected, it logs a
* message and exits gracefully without creating a commit.
*
* @returns {void}
* @returns {Promise<void>}
*/
export function commitAndPushWikiChanges(): void {
export async function commitAndPushWikiChanges(): Promise<void> {
startGroup('Committing and pushing changes to wiki');

try {
Expand All @@ -583,9 +583,11 @@ export function commitAndPushWikiChanges(): void {

if (status !== null && status.toString().trim() !== '') {
// There are changes, commit and push
const githubActionsBotEmail = await getGitHubActionsBotEmail();

for (const cmd of [
['config', '--local', 'user.name', GITHUB_ACTIONS_BOT_NAME],
['config', '--local', 'user.email', GITHUB_ACTIONS_BOT_EMAIL],
['config', '--local', 'user.email', githubActionsBotEmail],
['add', '.'],
['commit', '-m', commitMessage.trim()],
['push', 'origin'],
Expand Down