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