Skip to content
1,501 linesCodeBlameRaw
1//! What starts a run: an event on the bus, a schedule, or someone running a
2//! workflow by hand. Each finds the workflows that want it, at the commit
3//! the event is about, and checks their filters.
4
5use g1t_actions::events::{RunInfo, github_events};
6use g1t_actions::workflow::{self, Trigger, Workflow};
7use g1t_contracts::access::{self, Capability};
8use g1t_contracts::actions::{DispatchArgs, RepositoryDispatchArgs, WorkflowRun};
9use g1t_contracts::events::{Event, caused_by_job};
10use g1t_contracts::identity::{AGENT_ID, AGENT_NAME, UsernamesArgs};
11use g1t_contracts::repos::{Commit, CompareArgs, Comparison, LogArgs, Repo, RepoPath};
12use g1t_contracts::work::{IssueDetail, PullDetail, ViewArgs};
13use g1t_contracts::{FailureCode, Outcome, User, new_id};
14use g1t_contracts::time::rfc3339;
15use g1t_kit::now_ms;
16use serde_json::{Map, Value, json};
17use worker::Result;
18
19use crate::plan::NewRun;
20use crate::sync::{Read, WorkflowRow};
21use crate::{API, Actions, SITE, check, fail, payload};
22
23/// What an event is about, worked out once for every workflow it starts.
24struct Subject {
25 /// Where the workflow files are read, and at which commit.
26 source: RepoPath,
27 source_ref: Option<String>,
28 git_ref: String,
29 sha: String,
30 head_ref: Option<String>,
31 base_ref: Option<String>,
32 pull: Option<u32>,
33 /// The branch or tag for `branches`/`tags` filters; for pull requests,
34 /// the branch they merge into.
35 filter_ref: String,
36 /// The files it changes, for `paths` filters; `None` until needed.
37 paths: Option<Vec<String>>,
38 /// For a push, what to compare to find the files.
39 compare: Option<(Option<String>, String)>,
40 payload: Value,
41 title: String,
42 trusted: bool,
43 /// Why its runs wait for approval first: a pull request from outside,
44 /// by the repository's approval policy (protection.rs).
45 approval: Option<String>,
46}
47
48/// Whether a deployment's `ref` is a commit's full hash rather than a
49/// branch or tag.
50fn is_commit(name: &str) -> bool {
51 name.len() == 40 && name.chars().all(|c| c.is_ascii_hexdigit())
52}
53
54/// What a ref made or deleted is, as `create` and `delete` name it:
55/// `branch` or `tag`, and its short name. `None` for any other ref, and
56/// for the merge queue's own branches, which come and go with every
57/// queued change.
58fn branch_or_tag(git_ref: &str) -> Option<(&'static str, &str)> {
59 if git_ref.starts_with("refs/heads/g1t-queue/") {
60 return None;
61 }
62 match (git_ref.strip_prefix("refs/heads/"), git_ref.strip_prefix("refs/tags/")) {
63 (Some(branch), _) => Some(("branch", branch)),
64 (_, Some(tag)) => Some(("tag", tag)),
65 _ => None,
66 }
67}
68
69/// Events GitHub takes no `branches`, `tags` or `paths` filters on.
70fn unfiltered(event_name: &str) -> bool {
71 matches!(event_name, "create" | "delete")
72}
73
74/// Whether an `*.assigned` event added nobody: g1t says so for a change
75/// that only took people off.
76fn nobody_added(data: &Value) -> bool {
77 data["added"].as_array().is_some_and(Vec::is_empty)
78}
79
80/// Whether whoever a pull request is for is trusted without asking
81/// identity: g1t's agent in work nobody asked it for, or someone whose
82/// role here is known to allow pushing.
83fn trusted_outright(owner: &User, repo: &Repo) -> bool {
84 owner.id == AGENT_ID || access::can(Some(owner), repo, Capability::Push)
85}
86
87impl Actions {
88 async fn username(&self, id: Option<&str>) -> Result<Option<String>> {
89 let Some(id) = id else { return Ok(None) };
90 if id == AGENT_ID {
91 return Ok(Some(AGENT_NAME.to_owned()));
92 }
93 let names: std::collections::HashMap<String, String> =
94 g1t_kit::call(&self.identity, "usernames", &UsernamesArgs { ids: vec![id.to_owned()] }).await?;
95 Ok(names.get(id).cloned())
96 }
97
98 /// Whether whoever a pull request is for (Pull::owner: whoever asked
99 /// g1t for it, or its author) could push to the repository, so its
100 /// runs get the secrets and a token. Anyone else's, a reader's included
101 /// (who may open one on a private repository too), runs without them.
102 /// A change g1t made for someone is trusted as they are.
103 async fn insider(&self, owner: &User, repo: &Repo, ws: &User) -> Result<bool> {
104 if trusted_outright(owner, repo) {
105 return Ok(true);
106 }
107 // Stored authors carry no memberships or grants: ask identity, as
108 // the workspace (which may see anyone's permission).
109 let permission: Outcome<access::PermissionInfo> = g1t_kit::call(
110 &self.identity,
111 "collaborator_permission",
112 &access::CollaboratorPermissionArgs {
113 viewer: Some(ws.clone()),
114 path: RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() },
115 username: owner.username.clone(),
116 },
117 )
118 .await?;
119 Ok(permission
120 .into_result()
121 .ok()
122 .and_then(|info| info.role)
123 .is_some_and(|role| access::allows(role, Capability::Push)))
124 }
125
126 async fn commits(&self, repo: &Repo, actor: &User, after: &str, before: Option<&str>) -> Result<Vec<Commit>> {
127 let log: Outcome<Vec<Commit>> = g1t_kit::call(
128 &self.repos,
129 "log",
130 &LogArgs {
131 path: RepoPath {
132 namespace: repo.namespace.clone(),
133 name: repo.name.clone(),
134 },
135 viewer: Some(actor.clone()),
136 git_ref: Some(after.to_owned()),
137 limit: 20,
138 },
139 )
140 .await?;
141 let mut commits: Vec<Commit> = log.into_result().unwrap_or_default();
142 if let Some(before) = before
143 && let Some(at) = commits.iter().position(|commit| commit.hash == before)
144 {
145 commits.truncate(at);
146 }
147 // GitHub lists them oldest first, with the head commit last.
148 commits.reverse();
149 Ok(commits)
150 }
151
152 /// The message of the commit `sha` in `path`, when it can be read.
153 async fn head_message(&self, path: &RepoPath, actor: &User, sha: &str) -> Result<Option<String>> {
154 let log: Outcome<Vec<Commit>> = g1t_kit::call(
155 &self.repos,
156 "log",
157 &LogArgs { path: path.clone(), viewer: Some(actor.clone()), git_ref: Some(sha.to_owned()), limit: 1 },
158 )
159 .await?;
160 Ok(log.into_result().ok().and_then(|commits| commits.into_iter().next()).map(|commit| commit.message))
161 }
162
163 async fn changed_paths(&self, repo: &Repo, actor: &User, base: Option<String>, head: String) -> Result<Vec<String>> {
164 let compared: Outcome<Comparison> = g1t_kit::call(
165 &self.repos,
166 "compare",
167 &CompareArgs {
168 repo_id: repo.id.clone(),
169 viewer: Some(actor.clone()),
170 base,
171 head: Some(head),
172 base_branch: None,
173 },
174 )
175 .await?;
176 Ok(compared.into_result().map(|c| c.files.into_iter().map(|f| f.path).collect()).unwrap_or_default())
177 }
178
179 async fn default_head(&self, repo: &Repo) -> Result<Option<String>> {
180 g1t_kit::call(
181 &self.repos,
182 "head",
183 &g1t_contracts::repos::HeadArgs {
184 repo_id: repo.id.clone(),
185 branch: repo.default_branch.clone(),
186 },
187 )
188 .await
189 }
190
191 /// Whether `name` is one of the repository's branches.
192 async fn is_branch(&self, repo: &Repo, ws: &User, name: &str) -> Result<bool> {
193 let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call(
194 &self.repos,
195 "branches",
196 &g1t_contracts::repos::BranchesArgs {
197 path: Self::repo_path(repo),
198 viewer: Some(ws.clone()),
199 },
200 )
201 .await?;
202 Ok(branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == name))
203 }
204
205 fn repo_path(repo: &Repo) -> RepoPath {
206 RepoPath {
207 namespace: repo.namespace.clone(),
208 name: repo.name.clone(),
209 }
210 }
211
212 /// The subject of an event of `kind`, as GitHub's `event_name`.
213 async fn subject(&self, event: &Event, event_name: &str, action: Option<&str>, repo: &Repo, ws: &User, sender: &str) -> Result<Option<Subject>> {
214 let path = Self::repo_path(repo);
215 let data = &event.data;
216 let on_default = |sha: String, payload: Value, title: String, pull: Option<u32>| Subject {
217 source: path.clone(),
218 source_ref: None,
219 git_ref: format!("refs/heads/{}", repo.default_branch),
220 sha,
221 head_ref: None,
222 base_ref: None,
223 pull,
224 filter_ref: format!("refs/heads/{}", repo.default_branch),
225 paths: None,
226 compare: None,
227 payload,
228 title,
229 trusted: true,
230 approval: None,
231 };
232 let view = |number: u32| ViewArgs {
233 repo: path.clone(),
234 number,
235 viewer: Some(ws.clone()),
236 after_seq: 0,
237 };
238 Ok(match event_name {
239 "push" => {
240 let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else {
241 return Ok(None);
242 };
243 // The merge queue's states run merge_group workflows, not push ones.
244 if git_ref.starts_with("refs/heads/g1t-queue/") {
245 return Ok(None);
246 }
247 let before = data["before"].as_str();
248 let commits = self.commits(repo, ws, after, before).await?;
249 let title = commits.last().map(|c| c.message.lines().next().unwrap_or_default().to_owned()).unwrap_or_default();
250 let mut payload = payload::push(repo, git_ref, before, after, &commits, sender);
251 if let Some(head) = commits.last() {
252 payload["head_commit"] = payload::commit(repo, head);
253 }
254 Some(Subject {
255 source: path.clone(),
256 source_ref: Some(after.to_owned()),
257 git_ref: git_ref.to_owned(),
258 sha: after.to_owned(),
259 head_ref: None,
260 base_ref: None,
261 pull: None,
262 filter_ref: git_ref.to_owned(),
263 paths: None,
264 compare: Some((before.map(str::to_owned), after.to_owned())),
265 payload,
266 title,
267 trusted: true,
268 approval: None,
269 })
270 }
271 // A branch or tag was made: its own commit, as on GitHub.
272 "create" => {
273 let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else {
274 return Ok(None);
275 };
276 if git_ref.starts_with("refs/heads/g1t-queue/") || !data["before"].is_null() {
277 return Ok(None);
278 }
279 let Some((ref_type, name)) = branch_or_tag(git_ref) else { return Ok(None) };
280 let payload = json!({
281 "ref": name,
282 "ref_type": ref_type,
283 "master_branch": repo.default_branch,
284 "description": repo.description,
285 "pusher_type": "user",
286 "repository": payload::repository(repo),
287 "sender": payload::user(sender),
288 });
289 Some(Subject {
290 source: path.clone(),
291 source_ref: Some(after.to_owned()),
292 git_ref: git_ref.to_owned(),
293 sha: after.to_owned(),
294 head_ref: None,
295 base_ref: None,
296 pull: None,
297 filter_ref: git_ref.to_owned(),
298 paths: None,
299 compare: None,
300 payload,
301 title: format!("Created {ref_type} {name}"),
302 trusted: true,
303 approval: None,
304 })
305 }
306 // A branch or tag was deleted: on the default branch's latest
307 // commit, as on GitHub, since what was deleted has no commit to
308 // run on now.
309 "delete" => {
310 let Some(git_ref) = data["ref"].as_str() else { return Ok(None) };
311 let Some((ref_type, name)) = branch_or_tag(git_ref) else { return Ok(None) };
312 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
313 let payload = json!({
314 "ref": name,
315 "ref_type": ref_type,
316 "pusher_type": "user",
317 "repository": payload::repository(repo),
318 "sender": payload::user(sender),
319 });
320 Some(on_default(sha, payload, format!("Deleted {ref_type} {name}"), None))
321 }
322 "pull_request" | "pull_request_target" | "pull_request_review" => {
323 let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) };
324 // Assignees changed but nobody was added: someone was only
325 // taken off, which is not `assigned`.
326 if action == Some("assigned") && nobody_added(data) {
327 return Ok(None);
328 }
329 let detail: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?;
330 let Outcome::Ok(detail) = detail else { return Ok(None) };
331 let pull = &detail.pull;
332 let base_ref = pull.base_branch(&repo.default_branch).to_owned();
333 let mut payload = json!({
334 "action": action,
335 "number": pull.number,
336 "pull_request": payload::pull(repo, pull),
337 "repository": payload::repository(repo),
338 "sender": payload::user(sender),
339 });
340 payload::changed(&mut payload, data);
341 if event_name == "pull_request_review" {
342 let review = detail.comments.iter().rev().find(|c| c.verdict.is_some() && !c.advisory);
343 payload["review"] = json!({
344 "state": review.and_then(|r| r.verdict).map(payload::review_state),
345 "body": review.map(|r| r.body.clone()),
346 "user": review.map(|r| payload::user(&r.author.username)),
347 });
348 }
349 let trusted = self.insider(pull.owner(), repo, ws).await?;
350 // A pull request from outside may wait for approval before
351 // its head's code runs. `pull_request_target` runs the
352 // base's code, and a merged one's run the commit it landed
353 // as, so neither waits.
354 let approval = if event_name != "pull_request_target" && action != Some("closed") {
355 self.approval_needed(repo, pull.owner(), ws).await?
356 } else {
357 None
358 };
359 let head_ref = payload::head_ref(pull);
360 if event_name == "pull_request_target" {
361 // In the base's context: its workflows, its head.
362 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
363 let mut subject = on_default(sha, payload, pull.title.clone(), Some(pull.number));
364 subject.head_ref = Some(head_ref);
365 subject.base_ref = Some(base_ref.clone());
366 subject.filter_ref = format!("refs/heads/{base_ref}");
367 subject.paths = Some(pull.files.iter().map(|f| f.path.clone()).collect());
368 return Ok(Some(subject));
369 }
370 // A merged pull request's run is on the commit it landed as,
371 // in the repository; otherwise on its head, where that is.
372 let landed = match (action, data["commit"].as_str()) {
373 (Some("closed"), Some(commit)) => Some(commit.to_owned()),
374 _ => None,
375 };
376 let sha = match (&landed, data["commit"].as_str(), &pull.head_commit) {
377 (Some(commit), _, _) => commit.clone(),
378 (None, Some(commit), _) => commit.to_owned(),
379 (None, None, Some(head)) => head.clone(),
380 (None, None, None) => return Ok(None),
381 };
382 let source = match landed {
383 Some(_) => path.clone(),
384 None => pull.fork.clone().unwrap_or_else(|| path.clone()),
385 };
386 Some(Subject {
387 source,
388 source_ref: Some(sha.clone()),
389 git_ref: format!("refs/pull/{}/merge", pull.number),
390 sha,
391 head_ref: Some(head_ref),
392 base_ref: Some(base_ref.clone()),
393 pull: Some(pull.number),
394 // `branches` filters on pull requests name the base.
395 filter_ref: format!("refs/heads/{base_ref}"),
396 paths: Some(pull.files.iter().map(|f| f.path.clone()).collect()),
397 compare: None,
398 payload,
399 title: pull.title.clone(),
400 trusted,
401 approval,
402 })
403 }
404 "workflow_run" => {
405 // A run of a workflow_run workflow does not start another,
406 // so two such workflows cannot set each other off.
407 if data["event"].as_str() == Some("workflow_run") {
408 return Ok(None);
409 }
410 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
411 let head_branch = data["ref"].as_str().unwrap_or_default().trim_start_matches("refs/heads/").to_owned();
412 let name = data["workflow"].as_str().unwrap_or_default();
413 let payload = json!({
414 "action": "completed",
415 "workflow_run": {
416 "id": data["runId"],
417 "name": name,
418 "path": data["path"],
419 "event": data["event"],
420 "status": "completed",
421 "conclusion": data["conclusion"],
422 "head_sha": data["sha"],
423 "head_branch": head_branch,
424 "run_number": data["number"],
425 "html_url": format!("{SITE}/{}/{}/actions/runs/{}", repo.namespace, repo.name, data["runId"].as_str().unwrap_or_default()),
426 "pull_requests": data["pull"].as_u64().map(|n| vec![json!({ "number": n })]).unwrap_or_default(),
427 },
428 "workflow": { "name": name, "path": data["path"] },
429 "repository": payload::repository(repo),
430 "sender": payload::user(sender),
431 });
432 let mut subject = on_default(sha, payload, format!("After {name}"), None);
433 // Branch filters apply to the branch the followed run was on.
434 subject.filter_ref = format!("refs/heads/{head_branch}");
435 Some(subject)
436 }
437 "issues" | "issue_comment" => {
438 let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) };
439 if action == Some("assigned") && nobody_added(data) {
440 return Ok(None);
441 }
442 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
443 let issue: Outcome<IssueDetail> = g1t_kit::call(&self.work, "get_issue", &view(number)).await?;
444 let (issue_json, comments, title, on_pull) = match issue {
445 Outcome::Ok(detail) => (payload::issue(repo, &detail.issue), detail.comments, detail.issue.title.clone(), false),
446 Outcome::Fail(_) => {
447 let pull: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?;
448 let Outcome::Ok(detail) = pull else { return Ok(None) };
449 (payload::pull_as_issue(repo, &detail.pull), detail.comments, detail.pull.title.clone(), true)
450 }
451 };
452 let mut payload = json!({
453 "action": action,
454 "issue": issue_json,
455 "repository": payload::repository(repo),
456 "sender": payload::user(sender),
457 });
458 payload::changed(&mut payload, data);
459 if event_name == "issue_comment" {
460 let comment_id = data["commentId"].as_str();
461 if action == Some("deleted") {
462 // Gone by now: as the event kept it.
463 match data.get("comment").filter(|kept| kept.is_object()) {
464 Some(kept) => payload["comment"] = payload::deleted_comment(repo, number, kept, on_pull),
465 None => return Ok(None),
466 }
467 } else {
468 let comment = comments.iter().find(|c| Some(c.id.as_str()) == comment_id);
469 // A new comment is the newest; an edited one must be found.
470 let comment = if action == Some("created") { comment.or(comments.last()) } else { comment };
471 match comment {
472 Some(comment) => payload["comment"] = payload::comment(repo, number, comment, on_pull),
473 None => return Ok(None),
474 }
475 }
476 // `edited`: what the body was before.
477 if let Some(changes) = data.get("changes").filter(|changes| changes.is_object()) {
478 payload["changes"] = changes.clone();
479 }
480 }
481 Some(on_default(sha, payload, title, on_pull.then_some(number)))
482 }
483 // A release: on its tag, at the commit the tag named.
484 "release" => {
485 let release = &data["release"];
486 let Some(tag) = data["tagName"].as_str().or_else(|| release["tagName"].as_str()) else { return Ok(None) };
487 let sha = match release["target"].as_str().filter(|target| !target.is_empty()) {
488 Some(target) => target.to_owned(),
489 None => match self.default_head(repo).await? {
490 Some(head) => head,
491 None => return Ok(None),
492 },
493 };
494 let git_ref = format!("refs/tags/{tag}");
495 let mut payload = json!({
496 "action": action,
497 "release": payload::release(repo, release),
498 "repository": payload::repository(repo),
499 "sender": payload::user(sender),
500 });
501 if let Some(changes) = data.get("changes").filter(|changes| changes.is_object()) {
502 payload["changes"] = changes.clone();
503 }
504 let name = release["name"].as_str().filter(|name| !name.is_empty()).unwrap_or(tag);
505 Some(Subject {
506 source: path.clone(),
507 source_ref: Some(sha.clone()),
508 git_ref: git_ref.clone(),
509 sha,
510 head_ref: None,
511 base_ref: None,
512 pull: None,
513 filter_ref: git_ref,
514 paths: None,
515 compare: None,
516 payload,
517 title: format!("Release {name} {}", action.unwrap_or("changed")),
518 trusted: true,
519 approval: None,
520 })
521 }
522 // A deployment, or a new status of one: at the commit deployed,
523 // on the branch or tag it names (none for a bare commit).
524 "deployment" | "deployment_status" => {
525 let deployment = &data["deployment"];
526 let Some(sha) = deployment["sha"].as_str().filter(|sha| !sha.is_empty()).map(str::to_owned) else { return Ok(None) };
527 let named = deployment["ref"].as_str().unwrap_or_default();
528 let git_ref = if named.is_empty() || named == sha || is_commit(named) {
529 String::new()
530 } else if named.starts_with("refs/") {
531 named.to_owned()
532 } else if self.is_branch(repo, ws, named).await? {
533 format!("refs/heads/{named}")
534 } else {
535 format!("refs/tags/{named}")
536 };
537 let environment = deployment["environment"].as_str().unwrap_or_default();
538 let mut payload = json!({
539 "action": "created",
540 "deployment": payload::deployment(repo, deployment),
541 "repository": payload::repository(repo),
542 "sender": payload::user(sender),
543 });
544 let title = if event_name == "deployment_status" {
545 let status = &data["deploymentStatus"];
546 payload["deployment_status"] = payload::deployment_status(repo, status, deployment);
547 format!("Deployment to {environment}: {}", status["state"].as_str().unwrap_or("changed"))
548 } else {
549 format!("Deployment to {environment}")
550 };
551 Some(Subject {
552 source: path.clone(),
553 source_ref: Some(sha.clone()),
554 filter_ref: git_ref.clone(),
555 git_ref,
556 sha,
557 head_ref: None,
558 base_ref: None,
559 pull: None,
560 paths: None,
561 compare: None,
562 payload,
563 title,
564 trusted: true,
565 approval: None,
566 })
567 }
568 _ => None,
569 })
570 }
571
572 /// A push keeps the repository's schedules going (`run_schedules`).
573 /// Written at most once a day, and only on scheduled workflows.
574 async fn note_push(&self, repo_id: &str) -> Result<()> {
575 let at = now_ms();
576 self.db
577 .prepare("UPDATE workflows SET pushed_at = ? WHERE repo_id = ? AND crons != '[]' AND (pushed_at IS NULL OR pushed_at < ?)")
578 .bind(&[rfc3339(at).into(), repo_id.into(), rfc3339(at.saturating_sub(24 * 60 * 60 * 1000)).into()])?
579 .run()
580 .await?;
581 Ok(())
582 }
583
584 pub async fn on_event(&self, event: &Event) -> Result<()> {
585 let Some(repo_id) = event.repo_id.as_deref() else { return Ok(()) };
586 let mut mapped = github_events(&event.kind);
587 // A new branch or tag is also `create`.
588 if event.kind == "git.push" && event.data["before"].is_null() {
589 mapped.push(("create", None));
590 }
591 let pushed_default = event.kind == "git.push" && event.data["defaultBranch"].as_bool() == Some(true);
592 if event.kind == "git.push" {
593 self.note_push(repo_id).await?;
594 }
595 if mapped.is_empty() && !pushed_default {
596 return Ok(());
597 }
598 let Some((repo, ws)) = self.repo_by_id(repo_id).await? else { return Ok(()) };
599 if pushed_default {
600 self.sync(&repo, &ws).await?;
601 }
602 // A mirror runs only what its state says (mirrored.rs).
603 let copied_in = event.kind == "git.push" && event.data["mirrored"].as_bool() == Some(true);
604 let policy = crate::mirrored::policy(repo.mirror.as_ref(), copied_in);
605 if !policy.runs {
606 return Ok(());
607 }
608 // What a workflow job's own token did starts no workflows, as on
609 // GitHub, so a workflow cannot set itself off; only
610 // `workflow_dispatch` and `repository_dispatch` do.
611 if let Some(run) = caused_by_job(&event.data) {
612 worker::console_log!("actions: {} {} came from run {run}'s token; no workflows start for it", event.kind, event.id);
613 return Ok(());
614 }
615 let sender = self.username(event.actor.as_deref()).await?.unwrap_or_else(|| repo.namespace.clone());
616 for (event_name, action) in mapped {
617 // Issues and comments start the default branch's workflows,
618 // which the synced table lists: when none listens, nothing is
619 // read from git. Agents make many of these events.
620 // Deployments' statuses are as frequent (every g1t.page build
621 // reports several), so they look there first too.
622 if matches!(event_name, "issues" | "issue_comment" | "deployment" | "deployment_status" | "delete")
623 && self.listens(repo_id, event_name).await? == Some(false)
624 {
625 continue;
626 }
627 let Some(mut subject) = self.subject(event, event_name, action, &repo, &ws, &sender).await? else {
628 continue;
629 };
630 // `[skip ci]` in the head commit's message, as on GitHub.
631 if matches!(event_name, "push" | "pull_request") {
632 let message = match subject.payload["head_commit"]["message"].as_str() {
633 Some(message) => Some(message.to_owned()),
634 None => self.head_message(&subject.source, &ws, &subject.sha).await?,
635 };
636 if message.as_deref().is_some_and(g1t_actions::events::skips_ci) {
637 worker::console_log!("actions: {} {} at {} asks to skip its runs", event.kind, event.id, subject.sha);
638 continue;
639 }
640 }
641 // A change to workflows made on the remote, by someone g1t
642 // knows nothing of, waits before it may use this repository's
643 // secrets.
644 if copied_in && matches!(event_name, "push" | "create") {
645 if subject.paths.is_none() {
646 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
647 subject.paths = Some(self.changed_paths(&repo, &ws, base, head).await?);
648 }
649 if crate::mirrored::touches_workflows(subject.paths.as_deref().unwrap_or_default())
650 && let Some(mirror) = &repo.mirror
651 {
652 subject.approval = subject.approval.take().or_else(|| Some(crate::mirrored::copied_workflows(&mirror.remote)));
653 }
654 }
655 // A pull request from a fork reads the fork's files.
656 let read = if subject.source == Self::repo_path(&repo) {
657 self.read_for(&repo, &ws, subject.source_ref.as_deref(), policy.github).await?
658 } else {
659 self.read_workflows(&subject.source, &ws, subject.source_ref.as_deref()).await?
660 };
661 // A pull request's head runs each workflow once, however many
662 // events say it is there (marked ready, and pushed).
663 let key = match subject.pull {
664 Some(number) if event_name.starts_with("pull_request") && event_name != "pull_request_review" => {
665 // Reopened or made a draft again runs anew, at a head
666 // that may have run before.
667 let phase = match action {
668 Some("closed") => "closed".to_owned(),
669 Some(again @ ("reopened" | "converted_to_draft")) => format!("{again}:{}", event.id),
670 _ => "open".to_owned(),
671 };
672 format!("{event_name}:{number}:{}:{phase}", subject.sha)
673 }
674 _ if event_name == "create" => format!("{}:create", event.id),
675 _ => event.id.clone(),
676 };
677 self.start_matching(&repo, &ws, read, &mut subject, event_name, action, &key, event.actor.as_deref(), &sender)
678 .await?;
679 }
680 Ok(())
681 }
682
683 #[allow(clippy::too_many_arguments)]
684 async fn start_matching(
685 &self,
686 repo: &Repo,
687 ws: &User,
688 read: Read,
689 subject: &mut Subject,
690 event_name: &str,
691 action: Option<&str>,
692 event_key: &str,
693 actor_id: Option<&str>,
694 sender: &str,
695 ) -> Result<()> {
696 for file in read.files {
697 let parsed = workflow::parse(&file.source);
698 let workflow = match parsed {
699 Ok(workflow) => workflow,
700 Err(problem) => {
701 // A push shows a broken workflow as a failed run, as GitHub does.
702 if event_name == "push" && file.source.contains("on") {
703 self.record_invalid(repo, &file.path, &file.source, subject, event_key, actor_id, sender, &problem)
704 .await?;
705 }
706 continue;
707 }
708 };
709 let Some(trigger) = workflow.trigger(event_name) else { continue };
710 // workflow_run follows the workflows it names.
711 if event_name == "workflow_run" {
712 let followed = subject.payload["workflow_run"]["name"].as_str().unwrap_or_default();
713 if !trigger.workflows.iter().any(|name| name == followed) {
714 continue;
715 }
716 }
717 if !trigger.wants_type(action) || !self.passes(repo, ws, trigger, subject, event_name).await? {
718 continue;
719 }
720 if self.disabled(&repo.id, &file.path).await? {
721 continue;
722 }
723 // On a mirror the remote may deploy too: a workflow that deploys
724 // waits for approval (mirrored.rs).
725 let held = crate::mirrored::policy(repo.mirror.as_ref(), false)
726 .hold
727 .zip(crate::mirrored::deploys_to(&workflow))
728 .map(|(remote, environment)| crate::mirrored::held(&remote, &environment));
729 self.create_run(NewRun {
730 repo: repo.clone(),
731 path: file.path,
732 source: file.source,
733 info: self.run_info(repo, &workflow, event_name, subject, sender, actor_id),
734 workflow,
735 action: action.map(str::to_owned),
736 pull: subject.pull,
737 title: subject.title.clone(),
738 inputs: Map::new(),
739 event_key: event_key.to_owned(),
740 actor_id: actor_id.map(str::to_owned),
741 actor: Some(sender.to_owned()),
742 trusted: subject.trusted,
743 approval: subject.approval.clone().or(held),
744 })
745 .await?;
746 }
747 Ok(())
748 }
749
750 /// Whether the branch, tag and path filters let the event through.
751 async fn passes(&self, repo: &Repo, ws: &User, trigger: &Trigger, subject: &mut Subject, event_name: &str) -> Result<bool> {
752 // GitHub takes no filters on these: a workflow with `branches` on
753 // `create` or `delete` still runs for every branch and tag.
754 if unfiltered(event_name) {
755 return Ok(true);
756 }
757 let git_ref = subject.filter_ref.as_str();
758 if let Some(tag) = git_ref.strip_prefix("refs/tags/") {
759 // A tag push runs a workflow that filters tags, or filters nothing.
760 if trigger.tags.is_set() {
761 if !trigger.tags.allows(tag) {
762 return Ok(false);
763 }
764 } else if trigger.branches.is_set() {
765 return Ok(false);
766 }
767 // Paths are not checked for tags, as on GitHub.
768 return Ok(true);
769 }
770 let branch = git_ref.strip_prefix("refs/heads/").unwrap_or(git_ref);
771 if trigger.branches.is_set() {
772 if !trigger.branches.allows(branch) {
773 return Ok(false);
774 }
775 } else if event_name == "push" && trigger.tags.is_set() {
776 return Ok(false);
777 }
778 if trigger.paths.is_set() {
779 if subject.paths.is_none() {
780 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
781 subject.paths = Some(self.changed_paths(repo, ws, base, head).await?);
782 }
783 if !trigger.paths.allows_paths(subject.paths.as_deref().unwrap_or_default()) {
784 return Ok(false);
785 }
786 }
787 Ok(true)
788 }
789
790 async fn disabled(&self, repo_id: &str, path: &str) -> Result<bool> {
791 let row = self
792 .db
793 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND path = ?")
794 .bind(&[repo_id.into(), path.into()])?
795 .first::<WorkflowRow>(None)
796 .await?;
797 Ok(row.is_some_and(|row| row.state == "disabled"))
798 }
799
800 fn run_info(&self, repo: &Repo, workflow: &Workflow, event_name: &str, subject: &Subject, sender: &str, actor_id: Option<&str>) -> RunInfo {
801 RunInfo {
802 repository: format!("{}/{}", repo.namespace, repo.name),
803 repository_id: repo.id.clone(),
804 default_branch: repo.default_branch.clone(),
805 event_name: event_name.to_owned(),
806 event: subject.payload.clone(),
807 git_ref: subject.git_ref.clone(),
808 sha: subject.sha.clone(),
809 head_ref: subject.head_ref.clone(),
810 base_ref: subject.base_ref.clone(),
811 actor: sender.to_owned(),
812 actor_id: actor_id.unwrap_or_default().to_owned(),
813 triggering_actor: sender.to_owned(),
814 run_id: String::new(),
815 run_number: 0,
816 run_attempt: 1,
817 workflow: workflow.name.clone().unwrap_or_default(),
818 workflow_path: String::new(),
819 server_url: SITE.to_owned(),
820 api_url: API.to_owned(),
821 }
822 }
823
824 #[allow(clippy::too_many_arguments)]
825 async fn record_invalid(
826 &self,
827 repo: &Repo,
828 path: &str,
829 source: &str,
830 subject: &Subject,
831 event_key: &str,
832 actor_id: Option<&str>,
833 sender: &str,
834 problem: &str,
835 ) -> Result<()> {
836 let row = self.workflow_row(repo, path, path, source).await?;
837 self.record_failed_run(&row, subject.git_ref.as_str(), &subject.sha, event_key, actor_id, sender, problem).await
838 }
839
840 /// Scheduled workflows that run this minute, on the default branch: at
841 /// most every five minutes (`cron::Schedule::runs_at`). Not in a
842 /// repository with no push for [`crate::SCHEDULE_IDLE_MS`], nor for an
843 /// hour after billing refused one of the workflow's scheduled jobs
844 /// ([`crate::SCHEDULE_REFUSED_MS`]): no run is made only to be refused.
845 pub async fn run_schedules(&self, minute: u64) -> Result<()> {
846 let rows = self
847 .db
848 .prepare(
849 "SELECT * FROM workflows WHERE state = 'active' AND crons != '[]' AND error IS NULL
850 AND COALESCE(pushed_at, updated_at) >= ? AND (schedule_refused_until IS NULL OR schedule_refused_until <= ?)",
851 )
852 .bind(&[rfc3339(minute.saturating_sub(crate::SCHEDULE_IDLE_MS)).into(), rfc3339(minute).into()])?
853 .all()
854 .await?
855 .results::<WorkflowRow>()?;
856 for row in rows {
857 let crons: Vec<String> = serde_json::from_str(&row.crons).unwrap_or_default();
858 let Some(cron) = crons.iter().find(|cron| g1t_actions::cron::Schedule::parse(cron).is_ok_and(|s| s.runs_at(minute))) else {
859 continue;
860 };
861 let Ok(workflow) = workflow::parse(&row.source) else { continue };
862 // Schedules wait while a repository is archived, or a mirror runs
863 // nothing; a deleted one is not found.
864 let Some((repo, _ws)) = self
865 .repo_by_id(&row.repo_id)
866 .await?
867 .filter(|(repo, _)| !repo.archived() && crate::mirrored::policy(repo.mirror.as_ref(), false).runs)
868 else {
869 continue;
870 };
871 let Some(sha) = self.default_head(&repo).await? else { continue };
872 let payload = json!({ "schedule": cron, "repository": payload::repository(&repo), "workflow": row.path });
873 let mut subject = Subject {
874 source: Self::repo_path(&repo),
875 source_ref: None,
876 git_ref: format!("refs/heads/{}", repo.default_branch),
877 sha,
878 head_ref: None,
879 base_ref: None,
880 pull: None,
881 filter_ref: String::new(),
882 paths: None,
883 compare: None,
884 payload,
885 title: format!("Scheduled: {cron}"),
886 trusted: true,
887 approval: None,
888 };
889 subject.filter_ref = subject.git_ref.clone();
890 let info = self.run_info(&repo, &workflow, "schedule", &subject, &repo.namespace, None);
891 self.create_run(NewRun {
892 repo: repo.clone(),
893 path: row.path.clone(),
894 source: row.source.clone(),
895 workflow,
896 info,
897 action: None,
898 pull: None,
899 title: subject.title.clone(),
900 inputs: Map::new(),
901 event_key: format!("schedule:{minute}"),
902 actor_id: None,
903 actor: None,
904 trusted: true,
905 approval: None,
906 })
907 .await?;
908 }
909 Ok(())
910 }
911
912 /// `dispatch`: someone with the Write role runs a workflow that has
913 /// `workflow_dispatch`.
914 pub async fn dispatch(&self, a: DispatchArgs) -> Result<Outcome<WorkflowRun>> {
915 let repo = check!(self.may(&a.actor, &a.repo, Capability::Run).await?);
916 if repo.archived() {
917 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
918 }
919 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
920 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
921 };
922 let git_ref = a.git_ref.clone().unwrap_or_else(|| repo.default_branch.clone());
923 let full_ref = if git_ref.starts_with("refs/") {
924 git_ref.clone()
925 } else {
926 // A branch if there is one by that name, otherwise a tag.
927 let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call(
928 &self.repos,
929 "branches",
930 &g1t_contracts::repos::BranchesArgs {
931 path: Self::repo_path(&repo),
932 viewer: Some(ws.clone()),
933 },
934 )
935 .await?;
936 let is_branch = branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == git_ref);
937 format!("refs/{}/{git_ref}", if is_branch { "heads" } else { "tags" })
938 };
939 let short = full_ref.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/").to_owned();
940 let policy = crate::mirrored::policy(repo.mirror.as_ref(), false);
941 if let Some(mirror) = repo.mirror.as_ref().filter(|_| !policy.runs) {
942 return Ok(fail(FailureCode::Forbidden, crate::mirrored::refused(&repo.namespace, &repo.name, mirror)));
943 }
944 let read = self.read_for(&repo, &ws, Some(&short), policy.github).await?;
945 let Some(sha) = read.head.clone() else {
946 return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}.")));
947 };
948 // A workflow is named by its file (`build.yml`), its path, or its id
949 // (`wfl_…`), which stands for the path it was read from.
950 let by_id = if a.workflow.starts_with("wfl_") {
951 self.db
952 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND id = ?")
953 .bind(&[repo.id.as_str().into(), a.workflow.as_str().into()])?
954 .first::<WorkflowRow>(None)
955 .await?
956 .map(|row| row.path)
957 } else {
958 None
959 };
960 let named = by_id.as_deref().unwrap_or(&a.workflow);
961 let wanted = named.trim_start_matches(".g1t/workflows/");
962 let Some(file) = read.files.iter().find(|file| {
963 file.path.rsplit('/').next() == Some(wanted) || file.path == named
964 }) else {
965 return Ok(fail(FailureCode::NotFound, format!("There is no workflow {wanted} on {short}.")));
966 };
967 let workflow = match workflow::parse(&file.source) {
968 Ok(workflow) => workflow,
969 Err(problem) => return Ok(fail(FailureCode::Invalid, format!("The workflow does not read: {problem}"))),
970 };
971 let Some(trigger) = workflow.trigger("workflow_dispatch") else {
972 return Ok(fail(FailureCode::Invalid, "That workflow cannot be run by hand: it has no `workflow_dispatch` trigger."));
973 };
974 // `type: environment` names one of the repository's environments.
975 let environments = if trigger.inputs.values().any(|spec| spec.get("type").and_then(Value::as_str) == Some("environment")) {
976 self.environment_list(&repo.id).await?.into_iter().map(|env| env.name).collect()
977 } else {
978 Vec::new()
979 };
980 let inputs = check!(dispatch_inputs(trigger, &a.inputs, &environments));
981 let payload = json!({
982 // As GitHub gives them here: text, `true` and `false` included.
983 // The `inputs` context keeps booleans and numbers.
984 "inputs": event_inputs(&inputs),
985 "ref": full_ref,
986 "repository": payload::repository(&repo),
987 "sender": payload::user(&a.actor.username),
988 "workflow": file.path,
989 });
990 let subject = Subject {
991 source: Self::repo_path(&repo),
992 source_ref: Some(sha.clone()),
993 git_ref: full_ref.clone(),
994 sha,
995 head_ref: None,
996 base_ref: None,
997 pull: None,
998 filter_ref: full_ref,
999 paths: None,
1000 compare: None,
1001 payload,
1002 title: format!("{} run by {}", workflow.display_name(&file.path), a.actor.username),
1003 trusted: true,
1004 approval: None,
1005 };
1006 let info = self.run_info(&repo, &workflow, "workflow_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
1007 let created = self
1008 .create_run(NewRun {
1009 repo: repo.clone(),
1010 path: file.path.clone(),
1011 source: file.source.clone(),
1012 workflow,
1013 info,
1014 action: None,
1015 pull: None,
1016 title: subject.title.clone(),
1017 inputs,
1018 event_key: format!("dispatch:{}", new_id("dsp", now_ms())),
1019 actor_id: Some(a.actor.id.clone()),
1020 actor: Some(a.actor.username.clone()),
1021 trusted: true,
1022 approval: None,
1023 })
1024 .await?;
1025 match created {
1026 Some(id) => self.run_summary(&id).await,
1027 None => Ok(fail(FailureCode::Conflict, "It did not start.")),
1028 }
1029 }
1030
1031 /// `repository_dispatch`: an outside event, by name, starts the default
1032 /// branch's workflows that run `on: repository_dispatch` with that type
1033 /// (or with no `types`). A workflow job's token may send one: this,
1034 /// with `workflow_dispatch`, is how a workflow starts another.
1035 pub async fn repository_dispatch(&self, a: RepositoryDispatchArgs) -> Result<Outcome<u32>> {
1036 let repo = check!(self.may(&a.actor, &a.repo, Capability::Push).await?);
1037 if repo.archived() {
1038 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
1039 }
1040 let event_type = a.event_type.trim().to_owned();
1041 if event_type.is_empty() || event_type.chars().count() > 100 {
1042 return Ok(fail(FailureCode::Invalid, "event_type is 1 to 100 characters."));
1043 }
1044 let client_payload = match a.client_payload {
1045 Value::Null => json!({}),
1046 Value::Object(map) if map.len() <= 10 => Value::Object(map),
1047 Value::Object(_) => return Ok(fail(FailureCode::Invalid, "client_payload has at most 10 top-level properties.")),
1048 _ => return Ok(fail(FailureCode::Invalid, "client_payload is a JSON object.")),
1049 };
1050 if serde_json::to_string(&client_payload).map_or(0, |text| text.len()) > 64 * 1024 {
1051 return Ok(fail(FailureCode::Invalid, "client_payload is at most 64 KB."));
1052 }
1053 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
1054 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
1055 };
1056 let policy = crate::mirrored::policy(repo.mirror.as_ref(), false);
1057 if let Some(mirror) = repo.mirror.as_ref().filter(|_| !policy.runs) {
1058 return Ok(fail(FailureCode::Forbidden, crate::mirrored::refused(&repo.namespace, &repo.name, mirror)));
1059 }
1060 let read = self.read_for(&repo, &ws, Some(&repo.default_branch), policy.github).await?;
1061 let Some(sha) = read.head.clone() else {
1062 return Ok(fail(FailureCode::NotFound, "The repository has no default branch to run on yet."));
1063 };
1064 let git_ref = format!("refs/heads/{}", repo.default_branch);
1065 let payload = json!({
1066 "action": event_type,
1067 "branch": repo.default_branch,
1068 "client_payload": client_payload,
1069 "repository": payload::repository(&repo),
1070 "sender": payload::user(&a.actor.username),
1071 });
1072 let key = format!("repository_dispatch:{}", new_id("dsp", now_ms()));
1073 let mut started = 0u32;
1074 for file in read.files {
1075 let Ok(workflow) = workflow::parse(&file.source) else { continue };
1076 let Some(trigger) = workflow.trigger("repository_dispatch") else { continue };
1077 if !trigger.wants_type(Some(&event_type)) || self.disabled(&repo.id, &file.path).await? {
1078 continue;
1079 }
1080 let subject = Subject {
1081 source: Self::repo_path(&repo),
1082 source_ref: Some(sha.clone()),
1083 git_ref: git_ref.clone(),
1084 sha: sha.clone(),
1085 head_ref: None,
1086 base_ref: None,
1087 pull: None,
1088 filter_ref: git_ref.clone(),
1089 paths: None,
1090 compare: None,
1091 payload: payload.clone(),
1092 title: event_type.clone(),
1093 trusted: true,
1094 approval: None,
1095 };
1096 let info = self.run_info(&repo, &workflow, "repository_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
1097 let created = self
1098 .create_run(NewRun {
1099 repo: repo.clone(),
1100 path: file.path.clone(),
1101 source: file.source.clone(),
1102 workflow,
1103 info,
1104 action: Some(event_type.clone()),
1105 pull: None,
1106 title: subject.title.clone(),
1107 inputs: Map::new(),
1108 event_key: key.clone(),
1109 actor_id: Some(a.actor.id.clone()),
1110 actor: Some(a.actor.username.clone()),
1111 trusted: true,
1112 approval: None,
1113 })
1114 .await?;
1115 if created.is_some() {
1116 started += 1;
1117 }
1118 }
1119 Ok(Outcome::Ok(started))
1120 }
1121}
1122
1123#[derive(serde::Deserialize)]
1124#[serde(rename_all = "camelCase")]
1125pub struct MergeGroupArgs {
1126 pub repo_id: String,
1127 pub entry: String,
1128 pub sha: String,
1129 pub head_ref: String,
1130 #[serde(default)]
1131 pub base_sha: Option<String>,
1132 pub number: u32,
1133 #[serde(default)]
1134 pub ahead: Vec<u32>,
1135}
1136
1137impl Actions {
1138 /// `merge_group`: the merge queue built a state and its checks passed.
1139 /// Starts the workflows that run `on: merge_group` on it, as GitHub's
1140 /// queue does, and says how many started; the queue waits for their
1141 /// statuses on that commit.
1142 pub async fn merge_group(&self, a: MergeGroupArgs) -> Result<Outcome<Value>> {
1143 let Some((repo, ws)) = self.repo_by_id(&a.repo_id).await? else {
1144 return Ok(Outcome::Ok(json!({ "runs": 0 })));
1145 };
1146 let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&a.sha)).await?;
1147 let head_commit = self.commits(&repo, &ws, &a.sha, None).await?.pop();
1148 let payload = json!({
1149 "action": "checks_requested",
1150 "merge_group": {
1151 "head_sha": a.sha,
1152 "head_ref": a.head_ref,
1153 "base_sha": a.base_sha,
1154 "base_ref": format!("refs/heads/{}", repo.default_branch),
1155 "head_commit": head_commit.as_ref().map(|c| payload::commit(&repo, c)),
1156 },
1157 "repository": payload::repository(&repo),
1158 "sender": payload::user(&repo.namespace),
1159 });
1160 let mut started = 0u32;
1161 for file in read.files {
1162 let Ok(workflow) = workflow::parse(&file.source) else { continue };
1163 let Some(trigger) = workflow.trigger("merge_group") else { continue };
1164 if !trigger.wants_type(Some("checks_requested")) || self.disabled(&repo.id, &file.path).await? {
1165 continue;
1166 }
1167 // Branch filters on merge_group name the branch it merges into.
1168 if trigger.branches.is_set() && !trigger.branches.allows(&repo.default_branch) {
1169 continue;
1170 }
1171 let ahead = if a.ahead.is_empty() {
1172 String::new()
1173 } else {
1174 format!(" after {}", a.ahead.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", "))
1175 };
1176 let subject = Subject {
1177 source: Self::repo_path(&repo),
1178 source_ref: Some(a.sha.clone()),
1179 git_ref: a.head_ref.clone(),
1180 sha: a.sha.clone(),
1181 head_ref: None,
1182 base_ref: Some(repo.default_branch.clone()),
1183 pull: Some(a.number),
1184 filter_ref: format!("refs/heads/{}", repo.default_branch),
1185 paths: None,
1186 compare: None,
1187 payload: payload.clone(),
1188 title: format!("Merge queue: #{}{ahead}", a.number),
1189 trusted: true,
1190 approval: None,
1191 };
1192 let info = self.run_info(&repo, &workflow, "merge_group", &subject, &repo.namespace, None);
1193 let created = self
1194 .create_run(NewRun {
1195 repo: repo.clone(),
1196 path: file.path.clone(),
1197 source: file.source.clone(),
1198 workflow,
1199 info,
1200 action: Some("checks_requested".to_owned()),
1201 pull: Some(a.number),
1202 title: subject.title.clone(),
1203 inputs: Map::new(),
1204 event_key: format!("merge_group:{}:{}", a.entry, a.sha),
1205 actor_id: None,
1206 actor: None,
1207 trusted: true,
1208 approval: None,
1209 })
1210 .await?;
1211 if created.is_some() {
1212 started += 1;
1213 }
1214 }
1215 Ok(Outcome::Ok(json!({ "runs": started })))
1216 }
1217}
1218
1219/// The inputs of a manual run: what was given, checked against the
1220/// workflow's declared inputs, with their defaults filled in. An input the
1221/// workflow does not declare is refused, as GitHub refuses it.
1222/// `environments` are the repository's, for `type: environment`.
1223fn dispatch_inputs(trigger: &Trigger, given: &Map<String, Value>, environments: &[String]) -> Outcome<Map<String, Value>> {
1224 let unexpected: Vec<&String> = given.keys().filter(|name| !trigger.inputs.contains_key(*name)).collect();
1225 if !unexpected.is_empty() {
1226 let names = serde_json::to_string(&unexpected).unwrap_or_default();
1227 let declared = if trigger.inputs.is_empty() {
1228 "The workflow declares no inputs.".to_owned()
1229 } else {
1230 format!("The workflow declares {}.", trigger.inputs.keys().map(|name| format!("`{name}`")).collect::<Vec<_>>().join(", "))
1231 };
1232 return fail(FailureCode::Invalid, format!("Unexpected inputs provided: {names}. {declared}"));
1233 }
1234 let mut inputs = Map::new();
1235 for (name, spec) in &trigger.inputs {
1236 let kind = spec.get("type").and_then(Value::as_str).unwrap_or("string");
1237 let value = given.get(name).cloned().or_else(|| spec.get("default").cloned());
1238 let required = spec.get("required").and_then(Value::as_bool).unwrap_or(false);
1239 let value = match value {
1240 Some(Value::Null) | None if required => return fail(FailureCode::Invalid, format!("The input `{name}` is required.")),
1241 Some(Value::Null) | None => match kind {
1242 "boolean" => Value::Bool(false),
1243 _ => Value::String(String::new()),
1244 },
1245 Some(value) => match kind {
1246 "boolean" => Value::Bool(match &value {
1247 Value::Bool(flag) => *flag,
1248 Value::String(text) if text.trim().eq_ignore_ascii_case("true") => true,
1249 Value::String(text) if text.trim().eq_ignore_ascii_case("false") || text.trim().is_empty() => false,
1250 _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a boolean: true or false.")),
1251 }),
1252 "number" => match &value {
1253 Value::Number(_) => value,
1254 Value::String(text) => match number(text) {
1255 Some(number) => Value::Number(number),
1256 None => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
1257 },
1258 _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
1259 },
1260 "choice" => {
1261 let text = g1t_actions::expr::to_text(&value);
1262 let options: Vec<String> =
1263 spec.get("options").and_then(Value::as_array).map(|o| o.iter().map(g1t_actions::expr::to_text).collect()).unwrap_or_default();
1264 if !options.is_empty() && !options.contains(&text) {
1265 return fail(FailureCode::Invalid, format!("The input `{name}` is one of {}.", options.join(", ")));
1266 }
1267 Value::String(text)
1268 }
1269 "environment" => {
1270 let text = g1t_actions::expr::to_text(&value);
1271 let wanted = text.trim().to_ascii_lowercase();
1272 if !wanted.is_empty() && !environments.iter().any(|env| env.eq_ignore_ascii_case(&wanted)) {
1273 return fail(
1274 FailureCode::Invalid,
1275 format!("The input `{name}` names an environment, and this repository has none called `{}`.", text.trim()),
1276 );
1277 }
1278 Value::String(text)
1279 }
1280 _ => Value::String(g1t_actions::expr::to_text(&value)),
1281 },
1282 };
1283 inputs.insert(name.clone(), value);
1284 }
1285 Outcome::Ok(inputs)
1286}
1287
1288/// A number input given as text: a whole number stays one.
1289fn number(text: &str) -> Option<serde_json::Number> {
1290 let text = text.trim();
1291 match text.parse::<i64>() {
1292 Ok(whole) => Some(whole.into()),
1293 Err(_) => text.parse::<f64>().ok().filter(|n| n.is_finite()).and_then(serde_json::Number::from_f64),
1294 }
1295}
1296
1297/// A manual run's inputs as `github.event.inputs` gives them: every one as
1298/// text, as GitHub's `workflow_dispatch` payload has them.
1299fn event_inputs(inputs: &Map<String, Value>) -> Map<String, Value> {
1300 inputs.iter().map(|(name, value)| (name.clone(), Value::String(g1t_actions::expr::to_text(value)))).collect()
1301}
1302
1303#[cfg(test)]
1304mod tests {
1305 use super::*;
1306 use g1t_contracts::work::{Pull, g1t_author};
1307
1308 #[test]
1309 fn every_event_a_workflow_runs_on_is_sent_to_this_queue() {
1310 for kind in g1t_contracts::webhooks::EVENT_TYPES {
1311 if !github_events(kind).is_empty() {
1312 assert!(
1313 g1t_contracts::subscribers::routed("SUBSCRIBER_ACTIONS", kind),
1314 "{kind} starts workflows but is not routed to actions (g1t_contracts::subscribers)"
1315 );
1316 }
1317 }
1318 }
1319 use g1t_contracts::{Membership, PrincipalKind};
1320
1321 fn repo() -> Repo {
1322 serde_json::from_value(json!({
1323 "id": "rep_1", "namespace": "acme", "name": "web", "description": null, "isPrivate": true,
1324 "ownerId": "ws_1", "defaultBranch": "main", "forkOf": null, "createdAt": ""
1325 }))
1326 .unwrap()
1327 }
1328
1329 fn person(id: &str, username: &str) -> User {
1330 User { id: id.into(), username: username.into(), kind: PrincipalKind::User, ..User::default() }
1331 }
1332
1333 fn made_for(asker: User) -> Pull {
1334 serde_json::from_value(json!({
1335 "id": "pr_1", "repoId": "rep_1", "number": 14, "issue": 12, "title": "Fix it", "body": null,
1336 "agent": "g1t", "runtime": "hosted", "status": "open",
1337 "fork": { "namespace": "pulls", "name": "pr_1" }, "forkRepoId": "rep_f",
1338 "branch": null, "headCommit": "abc", "mergeBase": null, "mergedBy": null, "mergedAt": null,
1339 "supersededBy": null, "checkStatus": null,
1340 "author": g1t_author(), "requestedBy": asker,
1341 "createdAt": "", "updatedAt": ""
1342 }))
1343 .unwrap()
1344 }
1345
1346 #[test]
1347 fn g1t_s_change_for_someone_is_trusted_as_they_are() {
1348 // Stored people carry no memberships, so identity is asked about
1349 // them; being g1t's change gives it nothing more.
1350 let pull = made_for(person("usr_2", "ana"));
1351 assert!(!trusted_outright(pull.owner(), &repo()));
1352 // Someone known to be able to push is trusted at once.
1353 let mut member = person("usr_1", "syntaqx");
1354 member.workspaces.push(Membership::member("acme"));
1355 let pull = made_for(member);
1356 assert!(trusted_outright(pull.owner(), &repo()));
1357 }
1358
1359 #[test]
1360 fn the_payload_names_g1t_as_its_user_and_who_asked_for_it() {
1361 let pull = made_for(person("usr_1", "syntaqx"));
1362 let event = payload::pull(&repo(), &pull);
1363 assert_eq!(event["user"]["login"], "g1t");
1364 assert_eq!(event["user"]["type"], "Bot");
1365 assert_eq!(event["requested_by"]["login"], "syntaqx");
1366 assert_eq!(event["requested_by"]["type"], "User");
1367 let as_issue = payload::pull_as_issue(&repo(), &pull);
1368 assert_eq!(as_issue["user"]["login"], "g1t");
1369 assert_eq!(as_issue["requested_by"]["login"], "syntaqx");
1370 }
1371
1372 #[test]
1373 fn releases_deployments_and_deleted_comments_read_as_githubs() {
1374 let release = payload::release(
1375 &repo(),
1376 &json!({ "id": "rel_1", "tagName": "v1.2.0", "target": "abc", "name": null, "body": "Notes", "draft": false,
1377 "prerelease": true, "author": "ana", "createdAt": "2026-10-08T00:00:00Z", "publishedAt": "2026-10-08T00:00:00Z" }),
1378 );
1379 assert_eq!(release["tag_name"], "v1.2.0");
1380 assert_eq!(release["name"], "v1.2.0");
1381 assert_eq!(release["prerelease"], true);
1382 assert_eq!(release["author"]["login"], "ana");
1383 assert_eq!(release["html_url"], "https://g1t.sh/acme/web/releases/tag/v1.2.0");
1384 let deployment = json!({ "id": "dep_1", "sha": "abc", "ref": "main", "environment": "staging", "creator": "ana",
1385 "production_environment": false, "created_at": "t", "updated_at": "t" });
1386 let status = payload::deployment_status(&repo(), &json!({ "id": "dst_1", "state": "success", "environment_url": "https://s.example", "log_url": null, "creator": "g1t", "created_at": "t" }), &deployment);
1387 assert_eq!(status["state"], "success");
1388 assert_eq!(status["environment"], "staging");
1389 assert_eq!(status["environment_url"], "https://s.example");
1390 assert_eq!(payload::deployment(&repo(), &deployment)["payload"], json!({}));
1391 let gone = payload::deleted_comment(&repo(), 7, &json!({ "id": "cmt_1", "body": "hi", "author": { "id": "usr_1", "username": "bo" }, "createdAt": "t" }), true);
1392 assert_eq!(gone["user"]["login"], "bo");
1393 assert_eq!(gone["html_url"], "https://g1t.sh/acme/web/pull/7#cmt_1");
1394 assert!(is_commit("0123456789abcdef0123456789abcdef01234567"));
1395 assert!(!is_commit("main"));
1396 }
1397
1398 #[test]
1399 fn a_pull_request_names_its_own_base_labels_and_milestone() {
1400 let mut pull = made_for(person("usr_1", "syntaqx"));
1401 let event = payload::pull(&repo(), &pull);
1402 assert_eq!(event["base"]["ref"], repo().default_branch);
1403 pull.base = Some("release/1.x".into());
1404 pull.labels = vec!["bug".into()];
1405 pull.milestone = Some(g1t_contracts::work::MilestoneRef { number: 2, title: "1.1".into() });
1406 let event = payload::pull(&repo(), &pull);
1407 assert_eq!(event["base"]["ref"], "release/1.x");
1408 assert_eq!(event["labels"], serde_json::json!([{ "name": "bug" }]));
1409 assert_eq!(event["milestone"]["title"], "1.1");
1410 let mut labeled = serde_json::json!({ "action": "labeled" });
1411 payload::changed(&mut labeled, &serde_json::json!({ "label": { "name": "bug", "color": "d73a4a" } }));
1412 assert_eq!(labeled["label"]["color"], "d73a4a");
1413 let mut assigned = serde_json::json!({ "action": "assigned" });
1414 payload::changed(&mut assigned, &serde_json::json!({ "assignees": ["ana", "bo"], "added": ["bo"] }));
1415 assert_eq!(assigned["assignee"]["login"], "bo");
1416 assert!(nobody_added(&serde_json::json!({ "assignees": ["ana"], "added": [] })));
1417 assert!(!nobody_added(&serde_json::json!({ "assignees": ["ana"], "added": ["ana"] })));
1418 }
1419
1420 fn dispatchable(yaml: &str) -> Trigger {
1421 workflow::parse(yaml).unwrap().trigger("workflow_dispatch").unwrap().clone()
1422 }
1423
1424 fn given(value: Value) -> Map<String, Value> {
1425 value.as_object().unwrap().clone()
1426 }
1427
1428 const DISPATCH: &str = "on:
1429 workflow_dispatch:
1430 inputs:
1431 dry-run: { type: boolean, default: false }
1432 count: { type: number, default: 2 }
1433 target: { type: environment }
1434 level: { type: choice, options: [low, high], default: low }
1435 note: { required: false }
1436jobs:
1437 a:
1438 runs-on: x
1439 steps: [{ run: 'true' }]";
1440
1441 #[test]
1442 fn an_input_the_workflow_does_not_declare_is_refused() {
1443 let trigger = dispatchable(DISPATCH);
1444 let Outcome::Fail(failure) = dispatch_inputs(&trigger, &given(json!({ "dry-run": true, "colour": "red" })), &[]) else {
1445 panic!("an undeclared input was taken");
1446 };
1447 assert_eq!(failure.code, FailureCode::Invalid);
1448 assert!(failure.message.starts_with(r#"Unexpected inputs provided: ["colour"]."#), "{}", failure.message);
1449 assert!(failure.message.contains("`dry-run`"));
1450 let bare = dispatchable("on: workflow_dispatch\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]");
1451 let Outcome::Fail(failure) = dispatch_inputs(&bare, &given(json!({ "x": "1" })), &[]) else { panic!() };
1452 assert!(failure.message.contains("declares no inputs"));
1453 assert!(matches!(dispatch_inputs(&bare, &Map::new(), &[]), Outcome::Ok(inputs) if inputs.is_empty()));
1454 }
1455
1456 #[test]
1457 fn inputs_are_typed_and_the_event_has_them_as_text() {
1458 let trigger = dispatchable(DISPATCH);
1459 let environments = vec!["staging".to_owned(), "production".to_owned()];
1460 let Outcome::Ok(inputs) = dispatch_inputs(&trigger, &given(json!({ "dry-run": "true", "count": "3", "target": "Staging" })), &environments)
1461 else {
1462 panic!("refused");
1463 };
1464 assert_eq!(inputs["dry-run"], json!(true));
1465 assert_eq!(inputs["count"], json!(3));
1466 assert_eq!(inputs["level"], json!("low"));
1467 assert_eq!(inputs["note"], json!(""));
1468 let event = event_inputs(&inputs);
1469 assert_eq!(event["dry-run"], json!("true"));
1470 assert_eq!(event["count"], json!("3"));
1471 assert_eq!(event["target"], json!("Staging"));
1472 let Outcome::Ok(defaults) = dispatch_inputs(&trigger, &Map::new(), &environments) else { panic!() };
1473 assert_eq!(event_inputs(&defaults)["dry-run"], json!("false"));
1474 assert_eq!(defaults["count"], json!(2));
1475 let refused = |value: Value| match dispatch_inputs(&trigger, &given(value), &environments) {
1476 Outcome::Fail(failure) => failure.message,
1477 Outcome::Ok(_) => panic!("taken"),
1478 };
1479 assert!(refused(json!({ "target": "qa" })).contains("none called `qa`"));
1480 assert!(refused(json!({ "dry-run": "yes" })).contains("true or false"));
1481 assert!(refused(json!({ "count": "many" })).contains("is a number"));
1482 assert!(refused(json!({ "level": "mid" })).contains("low, high"));
1483 }
1484
1485 #[test]
1486 fn create_and_delete_take_no_filters_and_name_their_ref() {
1487 assert!(unfiltered("create") && unfiltered("delete"));
1488 assert!(!unfiltered("push") && !unfiltered("pull_request"));
1489 assert_eq!(branch_or_tag("refs/heads/feature/x"), Some(("branch", "feature/x")));
1490 assert_eq!(branch_or_tag("refs/tags/v1.0"), Some(("tag", "v1.0")));
1491 assert_eq!(branch_or_tag("refs/heads/g1t-queue/main/3"), None);
1492 assert_eq!(branch_or_tag("refs/notes/commits"), None);
1493 // A workflow can name `delete`. It takes no filters, as GitHub's
1494 // schema says, so writing one is refused when the workflow is read.
1495 assert!(workflow::parse("on:\n delete:\n branches: [release/*]\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").is_err());
1496 let workflow = workflow::parse("on:\n delete:\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap();
1497 let trigger = workflow.trigger("delete").unwrap();
1498 assert!(trigger.wants_type(None));
1499 assert!(!workflow.notes.iter().any(|note| note.severity == workflow::Severity::Unsupported));
1500 }
1501}