diff --git a/.github/workflows/close-on-invalid-label.yaml b/.github/workflows/close-on-invalid-label.yaml index eafb1a9a3094..0309aa45f9ef 100644 --- a/.github/workflows/close-on-invalid-label.yaml +++ b/.github/workflows/close-on-invalid-label.yaml @@ -1,6 +1,6 @@ name: Close issue/PR on adding invalid label -# Closes public issues and PRs when the invalid label is added. +# Closes public issues and PRs when the invalid label is added and cancels public PR CI. # Re-closes invalid PRs that someone without write access reopens. # Reopens PRs closed as invalid when maintainers add the skip-spammy-check label. @@ -19,6 +19,7 @@ jobs: if: github.repository == 'github/docs' && github.event.label.name == 'invalid' runs-on: ubuntu-latest permissions: + actions: write contents: read issues: write pull-requests: write @@ -38,6 +39,73 @@ jobs: PR_URL: ${{ github.event.pull_request.html_url }} run: gh pr close "$PR_URL" + - name: Cancel CI for the invalid PR + if: ${{ !cancelled() && github.event_name == 'pull_request_target' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { data: pr } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.payload.pull_request.number, + }) + const labels = pr.labels.map(label => label.name.toLowerCase()) + core.info(`Checking CI cancellation for PR #${pr.number} at ${pr.head.sha}.`) + if (!labels.includes('invalid') || labels.includes('skip-spammy-check')) { + core.info('Skipping cancellation: the PR is no longer invalid or has skip-spammy-check.') + return + } + if (!pr.head.repo) { + core.warning('Cannot safely match workflow runs because the PR source repository is unavailable.') + return + } + + // Preserve rejection, recovery, cleanup, Repo Sync, and notices that reopening cannot restore. + const cancellableWorkflows = new Set([ + 'test.yml', 'headless-tests.yml', 'lint-code.yml', 'content-lint-markdown.yml', + 'local-dev.yml', 'line-endings.yml', 'link-check-on-pr.yml', + 'dont-delete-assets.yml', 'dont-delete-features.yml', 'package-lock-lint.yml', + 'validate-asset-images.yml', 'triage-pull-requests.yml', 'send-to-triage-board.yml', + 'test-changed-content.yml', 'content-linter-rules-docs.yml', + 'article-api-docs.yml', 'move-content.yml', + ].map(file => `.github/workflows/${file}`)) + + const runs = await github.paginate(github.rest.actions.listWorkflowRunsForRepo, { + ...context.repo, + head_sha: pr.head.sha, + per_page: 100, + }) + core.info(`Found ${runs.length} workflow runs for head commit ${pr.head.sha}.`) + let requested = 0 + let conflicts = 0 + let skipped = 0 + for (const run of runs) { + // Fork runs can omit PR associations, so also match their source repository and branch. + const skipReason = + run.status === 'completed' ? 'already completed' : + !['pull_request', 'pull_request_target'].includes(run.event) ? 'not a PR event' : + !cancellableWorkflows.has(run.path) ? 'workflow is not a cancellation target' : + run.head_branch !== pr.head.ref ? 'source branch does not match' : + run.head_repository?.full_name !== pr.head.repo.full_name ? 'source repository does not match' : + run.pull_requests?.length && !run.pull_requests.some(item => item.number === pr.number) ? 'associated with a different PR' : + null + if (skipReason) { + core.info(`Skipping run ${run.id} (${run.path}): ${skipReason}.`) + skipped++ + continue + } + + core.info(`Requesting cancellation of run ${run.id} (${run.path}, status: ${run.status}).`) + try { + await github.rest.actions.cancelWorkflowRun({ ...context.repo, run_id: run.id }) + requested++ + } catch (error) { + if (error.status !== 409) throw error + conflicts++ + core.info(`Run ${run.id} is no longer cancellable.`) + } + } + core.info(`Cancellation summary: ${requested} requested, ${conflicts} no longer cancellable, ${skipped} skipped.`) + - name: Check out repo if: ${{ failure() && github.event_name != 'pull_request_target' }} uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 diff --git a/content/actions/reference/runners/github-hosted-runners.md b/content/actions/reference/runners/github-hosted-runners.md index 387807a888ec..de0b91b8b549 100644 --- a/content/actions/reference/runners/github-hosted-runners.md +++ b/content/actions/reference/runners/github-hosted-runners.md @@ -83,13 +83,13 @@ Windows virtual machines are configured to run as administrators with User Accou ## IP addresses -To get a list of IP address ranges that {% data variables.product.prodname_actions %} uses for {% data variables.product.prodname_dotcom %}-hosted runners, you can use the {% data variables.product.prodname_dotcom %} REST API. For more information, see the `actions` key in the response of the `GET /meta` endpoint. For more information, see [AUTOTITLE](/rest/meta/meta#get-github-meta-information). +To get the full set of IP address ranges from which {% data variables.product.prodname_dotcom %}-hosted runners may be assigned an IP address, use the `actions` key in the response from the `GET /meta` REST API endpoint. For more information, see [AUTOTITLE](/rest/meta/meta#get-github-meta-information). -Eligible Linux runners use a multi-cloud compute pool, so their outbound IP addresses are not limited to Azure datacenter ranges. Keep any IP allowlists or network-based access policies used by your workflows in sync with all ranges in the `actions` array, rather than relying on cloud-provider-specific ranges. Policies that allow only Azure or Microsoft-owned ranges, including Microsoft Entra Conditional Access policies, can block connections or authentication from these runners. +These ranges are not dedicated to {% data variables.product.prodname_actions %}. They cover the broader address space of the cloud provider regions where {% data variables.product.prodname_dotcom %}-hosted runners run, and include IP addresses used by unrelated services and customers. macOS runners are hosted in {% data variables.product.prodname_dotcom %}'s own macOS cloud. -For multi-cloud eligibility, see [Cloud hosts used by {% data variables.product.prodname_dotcom %}-hosted runners](/actions/concepts/runners/github-hosted-runners#cloud-hosts-used-by-github-hosted-runners). macOS runners are hosted in {% data variables.product.prodname_dotcom %}'s own macOS cloud. +If you use an allowlist to control access to your internal resources from {% data variables.product.prodname_dotcom %}-hosted runners, we do not recommend adding these ranges to it. Allowlisting the entire set permits network access from unrelated workloads within those ranges, not just your {% data variables.product.prodname_actions %} runners. This substantially broadens access and undermines the restrictions your allowlist is intended to enforce. Instead, we recommend you use {% data variables.actions.hosted_runner %}s with a static IP address range, or self-hosted runners. For more information, see [AUTOTITLE](/actions/how-tos/manage-runners/larger-runners) or [AUTOTITLE](/actions/concepts/runners/self-hosted-runners). -Since there are so many IP address ranges for {% data variables.product.prodname_dotcom %}-hosted runners, we do not recommend that you use these as allowlists for your internal resources. Instead, we recommend you use {% data variables.actions.hosted_runner %}s with a static IP address range, or self-hosted runners. For more information, see [AUTOTITLE](/actions/how-tos/manage-runners/larger-runners) or [AUTOTITLE](/actions/concepts/runners/self-hosted-runners). +Eligible Linux runners use a multi-cloud compute pool, so their outbound IP addresses are not limited to Azure datacenter ranges. Policies that allow only Azure or Microsoft-owned ranges, including Microsoft Entra Conditional Access policies, can block connections or authentication from these runners. For multi-cloud eligibility, see [Cloud hosts used by {% data variables.product.prodname_dotcom %}-hosted runners](/actions/concepts/runners/github-hosted-runners#cloud-hosts-used-by-github-hosted-runners). The list of {% data variables.product.prodname_actions %} IP addresses returned by the API is updated once a week. diff --git a/content/code-security/how-tos/manage-security-alerts/manage-secret-scanning-alerts/monitoring-alerts.md b/content/code-security/how-tos/manage-security-alerts/manage-secret-scanning-alerts/monitoring-alerts.md index 396fa177f746..bdcaa515368b 100644 --- a/content/code-security/how-tos/manage-security-alerts/manage-secret-scanning-alerts/monitoring-alerts.md +++ b/content/code-security/how-tos/manage-security-alerts/manage-secret-scanning-alerts/monitoring-alerts.md @@ -45,7 +45,7 @@ In addition to displaying an alert in the **{% data variables.product.prodname_s For historical scans, {% data variables.product.github %} notifies the following users: -* Organization owners, enterprise owners, and security managers—whenever a historical scan is complete, even if no secrets are found. +* Organization owners, enterprise owners, and security managers—whenever a historical scan that generated {% data variables.secret-scanning.alerts %} is complete. * Repository administrators, security managers, and users with custom roles with read/write access—whenever a historical scan detects a secret, and according to their notification preferences. We do _not_ notify commit authors. diff --git a/content/copilot/concepts/enterprise/governance-controls.md b/content/copilot/concepts/enterprise/governance-controls.md new file mode 100644 index 000000000000..00e4a81552ad --- /dev/null +++ b/content/copilot/concepts/enterprise/governance-controls.md @@ -0,0 +1,45 @@ +--- +title: Governance controls for GitHub Copilot +shortTitle: Governance controls +intro: Prepare to build your governance framework by understanding the tools at your disposal. +versions: + feature: copilot +contentType: concepts +docsTeamMetrics: + - ai-governance +--- + +Governance of {% data variables.product.prodname_copilot %} depends on a range of features and settings. Some are specific to {% data variables.product.prodname_copilot_short %}, and some apply to the {% data variables.product.github %} platform as a whole. Understanding how these surfaces interact is the first step of setting up your governance framework. + +## Overview + +As a simplified example, you can think of the surfaces interacting like this: + +1. **Assign seats** on your enterprise's {% data variables.product.prodname_copilot_short %} plan. Users who receive seats from your enterprise are governed by your other settings and controls. +1. **Configure your network settings** to control which endpoints {% data variables.product.prodname_copilot_short %} can reach on your corporate network. {% data variables.product.prodname_copilot_short %}'s endpoints are segregated by SKU, so you can block the use of personal {% data variables.product.prodname_copilot_short %} plans on the network. This ensures that everyone using {% data variables.product.prodname_copilot_short %} through the network uses a plan assigned by your organization or enterprise and is subject to the corresponding governance controls. +1. **Set policies** to determine where your licensed users can use {% data variables.product.prodname_copilot_short %} and which features are available in those clients. For example, you can enable {% data variables.product.prodname_vscode_shortname %}, {% data variables.copilot.copilot_cli_short %}, or the {% data variables.copilot.github_copilot_app_short %} separately. +1. **Configure settings** to govern what your licensed users can do in those clients: + + * Model settings control which LLM models users can choose when interacting with {% data variables.product.prodname_copilot_short %}, including custom models from an external provider. + * A `{% data variables.copilot.managed_setting_file %}` file gives you granular control over what users and agents can do in the clients you've enabled. + * Billing settings, such as budgets and cost centers, control the costs associated with usage that's billed to your enterprise. + +1. **Create rulesets** to enforce code and review standards in your enterprise's repositories, for both users and agents. +1. **Use audit logs** to record changes to these settings so you can prevent unintended configuration drift. + +## How each surface works + +{% rowheaders %} + +| Surface | What it does | Where it's defined | Who it affects | Where it applies | +| ------- | ------------ | ------------------ | -------------- | ---------------- | +| Seat assignment | Gives users the right to use {% data variables.product.prodname_copilot_short %}. Determines whose usage is billed to your enterprise and who is affected by your enterprise policies. If you use {% data variables.product.prodname_emus %}, this is the only route for managed accounts to access {% data variables.product.prodname_copilot_short %}. | Enterprise **AI controls**, organization settings, or an external identity provider (via enterprise teams). | Members of the enterprise or organization. | Gives users the right to use {% data variables.product.prodname_copilot_short %}, but where and how they can use it is controlled by the rest of your governance settings. | +| Network settings | Defines which {% data variables.product.github %} endpoints users can access, and with which account. For example: does traffic flow through a proxy? Can users use a personal {% data variables.product.prodname_copilot_short %} plan on your network, or connect to {% data variables.product.github %} with their personal account at all? | A combination of enterprise settings on {% data variables.product.github %} and rules on your corporate proxy or firewall. | Anyone on your corporate network | The {% data variables.product.github %} website and connections to remote resources from local clients. | +| {% data variables.product.prodname_copilot_short %} policies | Sets basic on/off controls, such as whether a feature is enabled or a client is available to users. | Enterprise **AI controls** or organization settings. Enterprises can choose to set blanket policies or let organizations decide. | Generally, all users who receive a {% data variables.product.prodname_copilot_short %} seat from your organization or enterprise. | Each specific client has its own enablement policy. Other policies have varying client support. See [AUTOTITLE](/copilot/reference/supported-surfaces-for-policies). | +| Model settings | Controls which models are available to which users, including models from external providers. | Enterprise **AI controls** or organization settings. Different settings can be rolled out to enterprise teams or organizations with specific requirements. | Users who receive a {% data variables.product.prodname_copilot_short %} seat from your organization or enterprise. | See the **Configure models** row in [AUTOTITLE](/copilot/reference/supported-surfaces-for-policies). | +| Enterprise managed settings | Controls what users and their agents can do in the clients they use. For example, which plugins can they install, which MCP servers can they connect to, and which agent tool calls require approval. | Either a JSON file in a `.github-private` repository, or configuration rolled out directly to users' machines via mobile device management. | Depends on the rollout method: the JSON file targets your licensed {% data variables.product.prodname_copilot_short %} users only; machine configuration targets anyone using that machine. | Different keys are supported in different clients. See [AUTOTITLE](/copilot/reference/enterprise-administrators/enterprise-managed-settings#client-support-by-key). | +| Billing settings | Sets budgets to control your enterprise's usage costs. | Enterprise or organization billing settings: budgets, cost centers, and overage policies. | People whose usage is billed to your enterprise. | All {% data variables.product.prodname_copilot_short %} clients and surfaces. | +| Rulesets | Protects branches from undesired or unreviewed code changes. | Enterprise, organization, or repository settings on {% data variables.product.github %}. | Anyone who contributes to the targeted repositories, including both agents and humans. | Targeted repositories and branches, which you can specify based on naming conventions or custom properties. | +| Audit logs | Allows your enterprise to track agent activity and changes to your governance settings or {% data variables.product.prodname_copilot_short %} plan. | Available to view on {% data variables.product.github %} and optionally stream to an external platform for retention. | Enterprise and organization administrators; not visible to users without the required permission. | Captures activity on the {% data variables.product.github %} website, but does not provide visibility into what users do in local clients or provide a granular breakdown of agent sessions. | + +{% endrowheaders %} diff --git a/content/copilot/concepts/enterprise/index.md b/content/copilot/concepts/enterprise/index.md index 1cde27a53a99..2b11f34f7c42 100644 --- a/content/copilot/concepts/enterprise/index.md +++ b/content/copilot/concepts/enterprise/index.md @@ -6,6 +6,7 @@ versions: feature: copilot children: - /policies + - /governance-controls - /default-availability - /fedramp-models - /learning-about-new-features-and-models diff --git a/content/copilot/concepts/enterprise/policies.md b/content/copilot/concepts/enterprise/policies.md index 3ebe9fac9670..4f817948d28e 100644 --- a/content/copilot/concepts/enterprise/policies.md +++ b/content/copilot/concepts/enterprise/policies.md @@ -10,8 +10,6 @@ redirect_from: - /copilot/concepts/policies category: - Manage Copilot for a team -docsTeamMetrics: - - ai-governance --- ## How do policies work? diff --git a/content/copilot/get-started/enterprise-ai-governance.md b/content/copilot/get-started/enterprise-ai-governance.md index 588e50b48b76..0084c71f04a9 100644 --- a/content/copilot/get-started/enterprise-ai-governance.md +++ b/content/copilot/get-started/enterprise-ai-governance.md @@ -21,8 +21,8 @@ journeyTracks: title: 'Establishing governance controls' description: 'Set a governance posture, configure controls, maintain codebase standards, and verify activity across your enterprise.' guides: + - href: '/copilot/concepts/enterprise/governance-controls' - href: '/copilot/tutorials/roll-out-at-scale/govern-at-scale/govern-for-adoption' - - href: '/copilot/concepts/enterprise/policies' - href: '/copilot/how-tos/administer-copilot/manage-for-enterprise/use-managed-settings/get-started' - href: '/copilot/tutorials/roll-out-at-scale/govern-at-scale/maintain-codebase-standards' - href: '/copilot/how-tos/administer-copilot/manage-for-enterprise/review-audit-logs' diff --git a/content/copilot/reference/supported-surfaces-for-policies.md b/content/copilot/reference/supported-surfaces-for-policies.md index a4e0c4f0fa22..7ca6dfe689db 100644 --- a/content/copilot/reference/supported-surfaces-for-policies.md +++ b/content/copilot/reference/supported-surfaces-for-policies.md @@ -38,7 +38,7 @@ A dedicated policy exists to enable or disable each supported feature or surface [^3]: In the {% data variables.copilot.github_copilot_app %}, this policy applies where {% data variables.copilot.copilot_memory %} is available for the user's account. The app's separate project **Memory** setting is not the same feature. See [AUTOTITLE](/copilot/concepts/prompting-and-context/copilot-memory#where-copilot-memory-is-available). -[^4] For a detailed breakdown by IDE, see [AUTOTITLE](/copilot/concepts/security-governance-and-network-settings/content-exclusion#availability-of-content-exclusion). +[^4]: For a detailed breakdown by IDE, see [AUTOTITLE](/copilot/concepts/security-governance-and-network-settings/content-exclusion#availability-of-content-exclusion). ## More information on {% data variables.copilot.copilot_in_the_cloud_short %} diff --git a/content/site-policy/privacy-policies/github-cookies.md b/content/site-policy/privacy-policies/github-cookies.md index 0fb4c2bc4723..90f11565f90f 100644 --- a/content/site-policy/privacy-policies/github-cookies.md +++ b/content/site-policy/privacy-policies/github-cookies.md @@ -31,6 +31,7 @@ GitHub | `_gh_sess` | This cookie is used for temporary application and framewor GitHub | `gist_oauth_csrf` | This cookie is set by Gist to ensure the user that started the oauth flow is the same user that completes it. | Deleted when oauth state is validated GitHub | `gist_user_session` | This cookie is used by Gist when running on a separate host. | Two weeks GitHub | `has_recent_activity` | This cookie is used to prevent showing the security interstitial to users that have visited the app recently. | One hour +GitHub | `__Host-ghlw` | This cookie is used to ensure that after you make a change, your next requests see that change rather than outdated data. | Session GitHub | `__Host-gist_user_session_same_site` | This cookie is set to ensure that browsers that support SameSite cookies can check to see if a request originates from GitHub. | Two weeks GitHub | `__Host-user_session_same_site` | This cookie is set to ensure that browsers that support SameSite cookies can check to see if a request originates from GitHub. | Two weeks GitHub | `logged_in` | This cookie is used to signal to us that the user is already logged in. | One year diff --git a/src/languages/lib/correct-translation-content.ts b/src/languages/lib/correct-translation-content.ts index 0079e74b950b..4bb83236dfb4 100644 --- a/src/languages/lib/correct-translation-content.ts +++ b/src/languages/lib/correct-translation-content.ts @@ -1733,6 +1733,45 @@ export function correctTranslatedContentStrings( `{%${dashOpen} ${tag} ${body.replace(/\s+/g, ' ').trim()} ${dashClose}%}`, ) + // Translators sometimes translated parts of the reusable path inside a data tag. + // Each key is the exact corrupted path (after the "data" keyword is repaired) and maps + // to the real English reusable. + const translatedReusablePaths: Record = { + 'reusables.release-notes.2024-06-possible-frontend-5-minute-outage-во время горячего обновления': + 'reusables.release-notes.2024-06-possible-frontend-5-minute-outage-during-hotpatch-upgrade', + 'reusables.organizations.navigate-to-спонсирование': + 'reusables.organizations.navigate-to-sponsoring', + 'reusables.sponsors.navigate-to-спонс-dashboard': + 'reusables.sponsors.navigate-to-sponsors-dashboard', + 'reusables.enterprise_installation.configuration-распознаваемой': + 'reusables.enterprise_installation.configuration-recognized', + 'reusables.가능 명령 줄.멀티 OS 터미널을 여세요': + 'reusables.command_line.open_the_multi_os_terminal', + 'reusables.코드ql-cli.man-pages-version-note': 'reusables.codeql-cli.man-pages-version-note', + 'reusables.기업 계정.정책 탭': 'reusables.enterprise-accounts.policies-tab', + 'reusables.기업 계정.옵션 탭': 'reusables.enterprise-accounts.options-tab', + 'reusables.기업 계정.기업 액세스': 'reusables.enterprise-accounts.access-enterprise', + 'reusables.command_line.打开多操作系统终端': + 'reusables.command_line.open_the_multi_os_terminal', + } + for (const [bad, good] of Object.entries(translatedReusablePaths)) { + content = content.replaceAll(`{% data ${bad} %}`, `{% data ${good} %}`) + content = content.replaceAll(`{%- data ${bad} %}`, `{%- data ${good} %}`) + } + // Korean "data reusable" (without a space-separated "가능") joined to the next path part. + content = content.replace( + /\{%(-?) 데이터 재사용가(?:능한?)?\.copilot\.프롬프트-파일-미리보기-노트 %\}/g, + '{%$1 data reusables.copilot.prompt-files-preview-note %}', + ) + content = content.replace( + /\{%(-?) (?:(?:데이터|data) 재사용 ?가능한?|data reusables(?:\.가능한?)?)\.copilot\.프롬프트-파일-추가-읽기 %\}/g, + '{%$1 data reusables.copilot.prompt-files-further-reading %}', + ) + content = content.replace( + /\{%(-?) (?:(?:데이터|data) 재사용 ?가능한?|data reusables(?:\.가능한?)?)\.copilot\.코드-완성-가능-모델 %\}/g, + '{%$1 data reusables.copilot.code-completion-available-models %}', + ) + if (englishContent && content.includes('{% octicon ')) { const englishNames: string[] = [] for (const m of englishContent.matchAll(/\{%-?\s*octicon\s+"([^"]*)"/g)) { diff --git a/src/languages/tests/correct-translation-content.ts b/src/languages/tests/correct-translation-content.ts index 994453102487..dc1b7656f21f 100644 --- a/src/languages/tests/correct-translation-content.ts +++ b/src/languages/tests/correct-translation-content.ts @@ -3880,4 +3880,63 @@ Para más información, consulta "[AUTOTITLE](/path)". expect(fix(ok, 'fr')).toBe(ok) }) }) + + describe('translated reusable names inside data tags', () => { + const cases: Array<[string, string, string]> = [ + [ + 'ru', + '{% данных reusables.organizations.navigate-to-спонсирование %}', + '{% data reusables.organizations.navigate-to-sponsoring %}', + ], + [ + 'ru', + '{% данных reusables.release-notes.2024-06-possible-frontend-5-minute-outage-во время горячего обновления %}', + '{% data reusables.release-notes.2024-06-possible-frontend-5-minute-outage-during-hotpatch-upgrade %}', + ], + [ + 'ko', + '{% 데이터 재사용 가능 명령 줄.멀티 OS 터미널을 여세요 %}', + '{% data reusables.command_line.open_the_multi_os_terminal %}', + ], + [ + 'ko', + '{% 데이터 재사용가능.copilot.프롬프트-파일-미리보기-노트 %}', + '{% data reusables.copilot.prompt-files-preview-note %}', + ], + [ + 'ko', + '{% 데이터 재사용 가능.copilot.프롬프트-파일-추가-읽기 %}', + '{% data reusables.copilot.prompt-files-further-reading %}', + ], + [ + 'ko', + '{%- 데이터 재사용 가능.copilot.프롬프트-파일-추가-읽기 %}', + '{%- data reusables.copilot.prompt-files-further-reading %}', + ], + [ + 'ko', + '{% 데이터 재사용 가능한.copilot.코드-완성-가능-모델 %}', + '{% data reusables.copilot.code-completion-available-models %}', + ], + [ + 'ko', + '{% 데이터 재사용 가능.copilot.코드-완성-가능-모델 %}', + '{% data reusables.copilot.code-completion-available-models %}', + ], + [ + 'ko', + '{% 데이터 재사용 가능 항목.기업 계정.정책 탭 %}', + '{% data reusables.enterprise-accounts.policies-tab %}', + ], + [ + 'zh', + '{% data reusables.command_line.打开多操作系统终端 %}', + '{% data reusables.command_line.open_the_multi_os_terminal %}', + ], + ] + test.each(cases)('[%s] %s', (code, bad, good) => { + expect(fix(bad, code)).toBe(good) + expect(fix(good, code)).toBe(good) + }) + }) }) diff --git a/src/workflows/README.md b/src/workflows/README.md index 7124e17528d3..b4549e69c15a 100644 --- a/src/workflows/README.md +++ b/src/workflows/README.md @@ -65,6 +65,23 @@ and comment markers prevent duplicate entries on reruns or when a label is remov and reapplied. Descriptions longer than 60,000 characters are explicitly truncated with a link back to the full source. +### Cancelling invalid public PR runs + +The invalid-label workflow closes rejected public issues and pull requests. For +PRs, it also requests cancellation of an explicit list of CI and advisory +workflows on the current head commit. It matches the source repository and branch +because fork runs can omit PR associations. Rejection, recovery, cleanup, and +Repo Sync workflows are not cancellation targets. Review guidance and +maintainer-edit notices also keep running because reopening a PR does not +retrigger them. Cancellation is skipped if the PR no longer has `invalid` or has +the `skip-spammy-check` recovery label. Logs report the head commit, runs found, +per-run skip reasons and cancellation requests, and a final count of requests, +cancellation conflicts, and skipped runs. + +This is best-effort cancellation of existing runs, not an acceptance gate. +Later runs, duplicate rejection comments, and in-flight issue workflows are not +prevented. Internal workflows are unchanged. + ## Data & External Dependencies ### Data inputs diff --git a/src/workflows/tests/actions-workflows.ts b/src/workflows/tests/actions-workflows.ts index 9f6bb83dbb1b..0f12f0829525 100644 --- a/src/workflows/tests/actions-workflows.ts +++ b/src/workflows/tests/actions-workflows.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'url' import path from 'path' import fs from 'fs' -import { describe, expect, test } from 'vitest' +import { describe, expect, test, vi } from 'vitest' import { load } from 'js-yaml' import { flatten } from 'flat' import { chain, get } from 'lodash-es' @@ -56,6 +56,123 @@ const workflows: WorkflowMeta[] = fs return { filename, fullpath, data } }) +describe('invalid PR run cancellation', () => { + const repo = { owner: 'github', repo: 'docs' } + const source = { full_name: 'contributor/docs' } + const pr = { number: 123, head: { sha: 'abc123', ref: 'patch-1', repo: source } } + const context = { repo, payload: { pull_request: pr } } + const core = { info: vi.fn() } + const run = { + id: 1, + name: 'Test', + event: 'pull_request', + path: '.github/workflows/test.yml', + status: 'in_progress', + head_branch: pr.head.ref, + head_repository: source, + pull_requests: [] as { number: number }[], + } + const workflow = workflows.find(({ filename }) => filename === 'close-on-invalid-label.yaml')! + const script = workflow.data.jobs['close-on-adding-invalid-label'].steps.find( + ({ name }) => name === 'Cancel CI for the invalid PR', + )!.with!.script + + function cancellationClient(runs = [run], labels = ['invalid']) { + return { + rest: { + pulls: { + get: vi + .fn() + .mockResolvedValue({ data: { ...pr, labels: labels.map((name) => ({ name })) } }), + }, + actions: { listWorkflowRunsForRepo: vi.fn(), cancelWorkflowRun: vi.fn() }, + }, + paginate: vi.fn().mockResolvedValue(runs), + } + } + + async function execute(github: object) { + core.info.mockClear() + await new Function('github', 'context', 'core', `return (async () => { ${script} })()`)( + github, + context, + core, + ) + } + + test('cancels fork CI without PR metadata, but not unrelated runs or protected workflows', async () => { + const github = cancellationClient([ + run, + { + ...run, + id: 2, + event: 'pull_request_target', + path: '.github/workflows/triage-pull-requests.yml', + status: 'queued', + }, + ...[ + 'test-changed-content.yml', + 'content-linter-rules-docs.yml', + 'article-api-docs.yml', + 'move-content.yml', + ].map((file, index) => ({ ...run, id: index + 3, path: `.github/workflows/${file}` })), + { ...run, head_branch: 'another-branch' }, + { ...run, head_repository: { full_name: 'another/docs' } }, + { ...run, pull_requests: [{ number: 456 }] }, + { ...run, event: 'push' }, + { ...run, status: 'completed' }, + ...[ + 'repo-sync.yml', + 'check-for-spammy-prs.yml', + 'close-on-invalid-label.yaml', + 'triage-unallowed-contributions.yml', + 'review-comment.yml', + 'notify-when-maintainers-cannot-edit.yaml', + ].map((file) => ({ ...run, path: `.github/workflows/${file}` })), + ]) + await execute(github) + expect(github.paginate).toHaveBeenCalledWith(github.rest.actions.listWorkflowRunsForRepo, { + ...repo, + head_sha: pr.head.sha, + per_page: 100, + }) + expect(github.rest.actions.cancelWorkflowRun.mock.calls).toEqual([ + [{ ...repo, run_id: 1 }], + [{ ...repo, run_id: 2 }], + ...[3, 4, 5, 6].map((run_id) => [{ ...repo, run_id }]), + ]) + expect(core.info).toHaveBeenCalledWith( + 'Skipping run 1 (.github/workflows/review-comment.yml): workflow is not a cancellation target.', + ) + expect(core.info).toHaveBeenCalledWith( + 'Cancellation summary: 6 requested, 0 no longer cancellable, 11 skipped.', + ) + }) + + test.each([{ labels: [] }, { labels: ['invalid', 'skip-spammy-check'] }])( + 'leaves recovered PRs alone ($labels)', + async ({ labels }) => { + const github = cancellationClient([run], labels) + await execute(github) + expect(github.paginate).not.toHaveBeenCalled() + expect(core.info).toHaveBeenCalledWith(expect.stringContaining('Skipping cancellation:')) + }, + ) + + test('continues past a cancellation race but surfaces permission failures', async () => { + const github = cancellationClient([run, { ...run, id: 2 }]) + github.rest.actions.cancelWorkflowRun.mockRejectedValueOnce({ status: 409 }) + await execute(github) + expect(github.rest.actions.cancelWorkflowRun).toHaveBeenCalledTimes(2) + expect(core.info).toHaveBeenCalledWith( + 'Cancellation summary: 1 requested, 1 no longer cancellable, 0 skipped.', + ) + const error = { status: 403 } + github.rest.actions.cancelWorkflowRun.mockRejectedValueOnce(error) + await expect(execute(github)).rejects.toBe(error) + }) +}) + function actionsUsedInWorkflow(workflow: WorkflowMeta) { return Object.keys(flatten(workflow)) .filter((key) => key.endsWith('.uses'))