-
Notifications
You must be signed in to change notification settings - Fork 2.3k
264 lines (185 loc) · 11.3 KB
/
Shared-ProtectedFiles.yml
File metadata and controls
264 lines (185 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
name: Protected files
permissions:
pull-requests: write
statuses: write
contents: read
on:
workflow_call:
inputs:
PayloadJson:
required: true
type: string
secrets:
AccessToken:
required: true
jobs:
build:
name: Run Script
if: github.repository_owner == 'MicrosoftDocs'
runs-on: ubuntu-latest
steps:
- name: Script
shell: pwsh
env:
ProtectedFileList: '[
".gitignore",
".openpublishing.publish.config.json",
"docfx.json",
"README.md",
"LICENSE",
"LICENSE-CODE",
"ThirdPartyNotices",
".acrolinx-config.edn",
".gitattributes",
"AutoLabelAssign.yml",
"AutoLabelMsftContributor.yml",
"BackgroundTasks.yml",
"BuildValidation.yml",
"compare-live-main.yml",
"LiveMergeCheck.yml",
"M365Endpoints.yml",
"PrFileCount.yml",
"ProtectedFiles.yml",
"Stale.yml",
"StaleBranch.yml",
"TierManagement.yml",
"workflow-status-report.yml",
"Shared-AutoLabelAssign.yml",
"Shared-AutoLabelMsftContributor.yml",
"Shared-BuildValidation.yml",
"Shared-ExtractPayload.yml",
"Shared-LiveMergeCheck.yml",
"Shared-PrFileCount.yml",
"Shared-ProtectedFiles.yml",
"Shared-Stale.yml",
"Shared-StaleBranch.yml",
"Shared-TierManagement.yml"
]'
ApproverList: '["user1"]'
PayloadJson: ${{ inputs.PayloadJson }}
AccessToken: ${{ secrets.AccessToken }}
run: |
# This script outputs nothing if all checks pass. If a check fails, an exception is thrown which results in an
# exit code of 1 being returned to GitHub. An exit code of 1 fails the status check.
# Get GitHub data
$GitHubData = $env:PayloadJson | ConvertFrom-Json -Depth 50
$AccessToken = $env:AccessToken
$GitRequestEvent = $GitHubData.event_name
# Get data from environment variables and convert lists from JSON
$ProtectedFileList = $env:ProtectedFileList | ConvertFrom-Json
$ApproverList = $env:ApproverList | ConvertFrom-Json
# Create github HTTP authentication header
$UserAgent = "officedocs"
$GitHubHeaders = @{}
$GitHubHeaders.Add("Authorization","token $($AccessToken)")
$GitHubHeaders.Add("User-Agent", $UserAgent)
$RepoName = $GitHubData.event.repository.name
$FatalError = $False
Write-Host "Repo: $RepoName"
Write-Host "Sender: $($GitHubData.event.sender.login)"
Write-Host "Request type: $GitRequestEvent"
Write-Host "GitHub action: $($GitHubData.event.action)"
Write-Host "PR URL: $($GitHubData.event.pull_request.url)/files"
# Only process event types of 'pull_request_target' that are either 'opened' (PR created) or 'synchronized' (PR commits updated)
If (($GitRequestEvent -eq "pull_request_target") -and (($GitHubData.event.action -eq "opened") -or ($GitHubData.event.action -eq "synchronize") -or ($GitHubData.event.action -eq "reopened"))) {
# Collect info from payload that we'll need to process the PR
$FileListUrl = "$($GitHubData.event.pull_request.url)/files?per_page=100"
$PrSubmitter = $GitHubData.event.pull_request.user.login
$PrSubmitterPermissionsUrl = $GitHubData.event.repository.collaborators_url.Replace("{/collaborator}", "/$PrSubmitter/permission")
$PrUrl = $GitHubData.event.pull_request.html_url
$StatusUrl = $GitHubData.event.pull_request.statuses_url
$TargetBranch = $GitHubData.event.pull_request.base.ref
$DefaultBranch = $GitHubData.event.repository.default_branch
$PublishBranch = "live"
Write-Host "Processing PR. Default branch: $DefaultBranch. Publish branch: $PublishBranch."
# Short delay so check doesn't finish before others start, which can cause GitHub UI to display confusing behavior.
Start-Sleep 3
# Only process PRs being submitted to $PublishBranch or $DefaultBranch branches. Also skip if a fatal error is encountered.
If ((($TargetBranch -eq $DefaultBranch) -or ($TargetBranch -eq $PublishBranch)) -and (!$FatalError)) {
Write-Host "$DefaultBranch or $PublishBranch branch"
Try {
# Get the list of files modified in the PR.
# Get the permissions of the PR submitter.
$FileListData = Invoke-RestMethod -Method GET -ContentType "application/json" -Headers $GitHubHeaders -Uri $FileListUrl -FollowRelLink -MaximumFollowRelLink 50 -ErrorAction Stop
$PrSubmitterPerms = Invoke-RestMethod -Method GET -ContentType "application/json" -Headers $GitHubHeaders -Uri $PrSubmitterPermissionsUrl -ErrorAction Stop
} Catch {
$FatalError = $True
}
$FileList = @()
# Collapse pages into a single list if there are any and store in $FileList
ForEach ($Page in $FileListData) { $FileList += $Page }
$ProtectedFileFound = $False
# Only process PRs that actually have changed files.
If ($($FileList.Count -gt 0)) {
Write-Host "PR has files`n`rFile list: $($FileList.filename)"
# Process PRs that are submitted by non-admins
If ($PrSubmitterPerms.permission -ne "admin") {
Write-Host "Submitter is not an admin"
# Check to see if submitter is an protected file approver
$ValidApprover = $False
If ($ApproverList.Contains($PrSubmitter)) {
$ValidApprover = $True
}
# Only check if there's a protected file in the PR if the PR submitter isn't a protected file approver.
If ($ValidApprover -eq $False) {
# Setting job summary here just in case there's a protected file. If there's no protected file, the job summary
# will be cleared and this won't be shown.
echo "# Pull request validation error" >> $env:GITHUB_STEP_SUMMARY
echo "" >> $env:GITHUB_STEP_SUMMARY
echo "The following protected files were found in PR: $PrUrl." >> $env:GITHUB_STEP_SUMMARY
echo "" >> $env:GITHUB_STEP_SUMMARY
Write-Host "Not an admin or protected file approver. Checking files."
# Loop through the protected file list and check to see if any of them are present in the changed file list. If we do, set the flag
# and the break out of the loop.
ForEach ($File in $ProtectedFileList) {
ForEach ($PrFile in $FileList) {
$PrFile = $PrFile.filename
$LastIndexOfBackslash = $PrFile.LastIndexOf("/")
$PrFile = $PrFile.Remove(0, $LastIndexOfBackslash + 1)
If ($PrFile -ceq $File) {
$ProtectedFileFound = $True
echo "- $PrFile" >> $env:GITHUB_STEP_SUMMARY
Write-Host "PROTECTED FILE: $PrFile"
}
}
}
# If a protected file is found, throw an exception to cause the script to exit with an exit code of 1.
If ($ProtectedFileFound) {
Throw "A protected file was found. Click Summary in the left pane for more information."
} Else {
Write-Host "No protected files found"
# Clear the job summary because no protected files were found.
echo "" > $env:GITHUB_STEP_SUMMARY
}
} Else {
Write-Host "PR submitter $PrSubmitter is an approved protected file submitter."
}
# Set status to 'success' since the submitter is an admin.
} Else {
Write-Host "PR submitter $PrSubmitter is an admin."
}
} Else {
Write-Host "PR doesn't contain any files."
}
} Else {
Write-Host "PR base branch isn't $DefaultBranch or $PublishBranch."
}
# If an exception was encountered, or if the attempt to post the status check failed, send email notification with error and PR info.
If ($FatalError) {
$Body = "<p>An error occurred while processing the protected file check for a pull request.</p>"
$Body = $Body + "<h2>Error encountered</h2>"
$Body = $Body + "Fatal error: $FatalError<br>"
$Body = $Body + "Successful post: $SuccessfulPost<br>"
ForEach ($Err in $Error) {
$Body = $Body + "<p>$($Err.Exception.ToString())</p>"
$Body = $Body + "<p>$($Err.InvocationInfo.PositionMessage)</p>"
}
$Body = $Body + "<h2>Pull request info</h2>"
$Body = $Body + "<p>URL: $($GitHubData.event.pull_request.url)"
$Body = $Body + "<p>PR Submitter: $PrSubmitter</p>"
$Body = $Body + "<p>PR submitter permissions: $($PrSubmitterPerms.permission)</p>"
$Body = $Body + "<p>Protected file found: $ProtectedFileFound</p>"
$Body = $Body + "<p>File change list: $($FileList.filename)</p>"
Write-Host "Error posting status check. $Body"
}
}