From c3c44bbf95fe87870dd035a3af3e213d7948ae0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Dec 2026 21:03:24 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20leftover=20cro?= =?UTF-8?q?ss-crate=20simplification=20(signed-token=20helper,=20NewPull,?= =?UTF-8?q?=20settings=20table,=20row=20helpers,=20strings!=20i18n=20macro?= =?UTF-8?q?,=20csrf=20form,=20RepoCtx=20helpers,=20shared=20page=20and=20e?= =?UTF-8?q?2e=20helpers,=20ci=20config=20split,=20one=20time=20helper=20se?= =?UTF-8?q?t);=20fixes:=20runner=20reported=20labels=20survive=20override?= =?UTF-8?q?=20clears,=20milestone=20titles=20repaired=20from=20the=20swapp?= =?UTF-8?q?ed=20update=20bug,=20runner=20helper=20lines=20can=20no=20longe?= =?UTF-8?q?r=20be=20spoofed=20by=20job=20output,=20rootfs=20GC=20no=20long?= =?UTF-8?q?er=20touches=20other=20id=20ranges,=20restart=20only=20labels?= =?UTF-8?q?=20jobs=20it=20cancelled,=20artifact=20quota=20re-checked=20in?= =?UTF-8?q?=20the=20store=20write,=20LFS=20gc=20and=20upload=20share=20a?= =?UTF-8?q?=20lock,=20OCI=20orphan=20blobs=20swept,=20mirror=20worker=20no?= =?UTF-8?q?=20longer=20spins=20on=20syncing=20mirrors,=20merge=20queue=20f?= =?UTF-8?q?ails=20missing=20checks=20after=20the=20job=20timeout=20and=20r?= =?UTF-8?q?esumes=20after=20restart,=20post=5Fupdate=20walks=20every=20pus?= =?UTF-8?q?hed=20commit,=20close-with-comment=20is=20one=20transaction,=20?= =?UTF-8?q?pull=20create=20is=20retry-safe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 1 + crates/forge-ci/build_identity.rs | 3 - crates/forge-ci/src/build.rs | 31 +- crates/forge-ci/src/config.rs | 1345 +---------------- crates/forge-ci/src/config/artifact.rs | 43 + crates/forge-ci/src/config/cache.rs | 147 ++ crates/forge-ci/src/config/job.rs | 228 +++ crates/forge-ci/src/config/matrix.rs | 355 +++++ crates/forge-ci/src/config/memory.rs | 69 + crates/forge-ci/src/config/release.rs | 369 +++++ crates/forge-ci/src/config/schedule.rs | 55 + crates/forge-ci/src/config/trigger.rs | 97 ++ crates/forge-ci/src/config/workflow.rs | 72 + .../0075_runner_registered_labels.sql | 2 + .../0076_milestone_title_repair.sql | 1 + crates/forge-core/src/alerts.rs | 56 + crates/forge-core/src/audit.rs | 21 +- crates/forge-core/src/ci.rs | 84 +- crates/forge-core/src/config.rs | 96 +- crates/forge-core/src/discussions.rs | 43 +- crates/forge-core/src/issues.rs | 75 +- crates/forge-core/src/lfs_token.rs | 75 +- crates/forge-core/src/lib.rs | 27 + crates/forge-core/src/mail.rs | 83 +- crates/forge-core/src/merge_queue.rs | 38 +- crates/forge-core/src/mirrors.rs | 26 +- crates/forge-core/src/model.rs | 61 +- crates/forge-core/src/notifications.rs | 81 +- crates/forge-core/src/oci.rs | 21 +- crates/forge-core/src/pulls.rs | 77 +- crates/forge-core/src/raw_token.rs | 33 +- crates/forge-core/src/reactions.rs | 44 +- crates/forge-core/src/reviews.rs | 58 +- crates/forge-core/src/secret.rs | 3 +- crates/forge-core/src/server_settings.rs | 634 ++++---- crates/forge-core/src/signed_token.rs | 25 + crates/forge-core/src/store/admin_alerts.rs | 41 +- crates/forge-core/src/store/advisories.rs | 28 +- crates/forge-core/src/store/audit.rs | 8 +- crates/forge-core/src/store/backup_runs.rs | 52 +- crates/forge-core/src/store/ci.rs | 63 +- crates/forge-core/src/store/commit_status.rs | 34 +- crates/forge-core/src/store/contributions.rs | 23 +- crates/forge-core/src/store/discussions.rs | 10 +- .../forge-core/src/store/edit_history_read.rs | 14 +- crates/forge-core/src/store/exports.rs | 26 +- crates/forge-core/src/store/imports.rs | 31 +- crates/forge-core/src/store/issues.rs | 193 ++- crates/forge-core/src/store/labels.rs | 4 +- crates/forge-core/src/store/mail.rs | 14 +- crates/forge-core/src/store/merge_queue.rs | 14 +- crates/forge-core/src/store/migrate.rs | 59 + crates/forge-core/src/store/mirrors.rs | 26 +- crates/forge-core/src/store/mod.rs | 46 +- crates/forge-core/src/store/notifications.rs | 12 +- crates/forge-core/src/store/orgs.rs | 64 +- crates/forge-core/src/store/pulls.rs | 100 +- crates/forge-core/src/store/reactions.rs | 6 +- crates/forge-core/src/store/replication.rs | 77 +- crates/forge-core/src/store/reviews.rs | 25 +- crates/forge-core/src/store/shell_activity.rs | 5 +- crates/forge-core/src/store/signatures.rs | 65 +- crates/forge-core/src/store/snippets.rs | 48 +- crates/forge-core/src/store/webhooks.rs | 19 +- crates/forge-core/src/time.rs | 42 +- crates/forge-core/src/totp.rs | 4 +- crates/forge-core/src/webhooks.rs | 56 +- .../forge-e2e/tests/e2e/account_mail_e2e.rs | 6 +- crates/forge-e2e/tests/e2e/advisories_e2e.rs | 101 +- .../tests/e2e/branch_protection_e2e.rs | 124 +- crates/forge-e2e/tests/e2e/browse_e2e.rs | 127 +- crates/forge-e2e/tests/e2e/ci_e2e.rs | 201 +-- crates/forge-e2e/tests/e2e/common/http.rs | 42 +- crates/forge-e2e/tests/e2e/common/mod.rs | 195 ++- .../forge-e2e/tests/e2e/community_i18n_e2e.rs | 26 +- crates/forge-e2e/tests/e2e/discussions_e2e.rs | 70 +- crates/forge-e2e/tests/e2e/git_e2e.rs | 132 +- crates/forge-e2e/tests/e2e/i18n_e2e.rs | 29 +- crates/forge-e2e/tests/e2e/issue_close_e2e.rs | 165 +- crates/forge-e2e/tests/e2e/lfs_e2e.rs | 110 +- crates/forge-e2e/tests/e2e/merge_queue_e2e.rs | 189 +-- crates/forge-e2e/tests/e2e/mirrors_e2e.rs | 125 +- crates/forge-e2e/tests/e2e/oci_e2e.rs | 34 +- crates/forge-e2e/tests/e2e/orgs_core_e2e.rs | 33 +- crates/forge-e2e/tests/e2e/orgs_live_e2e.rs | 102 +- crates/forge-e2e/tests/e2e/orgs_ui_e2e.rs | 228 +-- crates/forge-e2e/tests/e2e/packages_e2e.rs | 34 +- crates/forge-e2e/tests/e2e/pulls_e2e.rs | 234 +-- .../tests/e2e/repo_collaborators_e2e.rs | 70 +- crates/forge-e2e/tests/e2e/repo_rename_e2e.rs | 152 +- .../forge-e2e/tests/e2e/repo_settings_e2e.rs | 149 +- .../forge-e2e/tests/e2e/repo_transfer_e2e.rs | 74 +- crates/forge-e2e/tests/e2e/section_nav_e2e.rs | 27 +- crates/forge-e2e/tests/e2e/snippets_e2e.rs | 66 +- crates/forge-e2e/tests/e2e/stars_e2e.rs | 22 +- crates/forge-e2e/tests/e2e/ui_prefs_e2e.rs | 88 +- crates/forge-e2e/tests/e2e/user_delete_e2e.rs | 50 +- crates/forge-e2e/tests/e2e/wiki_e2e.rs | 206 +-- crates/forge-git/src/history.rs | 5 +- crates/forge-git/src/pulls.rs | 2 +- crates/forge-git/src/repo.rs | 6 +- crates/forge-runner/Cargo.toml | 1 + crates/forge-runner/src/check.rs | 21 +- crates/forge-runner/src/cli.rs | 2 +- crates/forge-runner/src/executor.rs | 35 +- crates/forge-runner/src/main.rs | 6 +- crates/forge-runner/src/oci/helper.rs | 2 +- crates/forge-runner/src/oci/store.rs | 39 +- crates/forge-runner/src/oom.rs | 18 +- crates/forge-runner/src/runner.rs | 5 +- crates/forge-runner/src/sandbox/helper.rs | 9 +- crates/forge-runner/src/sandbox/idmap.rs | 4 +- crates/forge-runner/src/sandbox/mod.rs | 24 + crates/forge-runner/src/sandbox/net.rs | 2 +- crates/forge-runner/src/sandbox/spec.rs | 1 + .../forge-runner/tests/integration/sandbox.rs | 5 +- crates/forge-ssh/src/parse.rs | 21 +- crates/forge-ssh/src/server.rs | 40 +- crates/forge-web-account/src/lib.rs | 2 +- .../src/pages/account_tools_tests.rs | 8 +- .../src/pages/admin_backups.rs | 2 +- .../src/pages/admin_health.rs | 58 +- .../src/pages/admin_live_tests.rs | 29 +- .../forge-web-account/src/pages/admin_mail.rs | 19 +- .../src/pages/admin_replication.rs | 171 +-- crates/forge-web-account/src/pages/assets.rs | 8 +- .../forge-web-account/src/pages/audit_log.rs | 44 +- crates/forge-web-account/src/pages/banner.rs | 14 +- crates/forge-web-account/src/pages/explore.rs | 58 +- crates/forge-web-account/src/pages/import.rs | 15 +- crates/forge-web-account/src/pages/login.rs | 14 +- .../forge-web-account/src/pages/needs_you.rs | 17 +- crates/forge-web-account/src/pages/org_ctx.rs | 14 +- .../src/pages/org_members.rs | 4 +- .../src/pages/org_settings.rs | 11 +- .../forge-web-account/src/pages/org_teams.rs | 7 +- .../forge-web-account/src/pages/passkeys.rs | 26 +- crates/forge-web-account/src/pages/profile.rs | 36 +- .../src/pages/profile_pins.rs | 34 +- .../src/pages/settings_appearance.rs | 8 +- .../src/pages/settings_export.rs | 9 +- .../src/pages/settings_gpg_tests.rs | 42 +- .../src/pages/settings_profile.rs | 8 +- .../src/pages/settings_security.rs | 105 +- .../src/pages/settings_sessions.rs | 8 +- .../forge-web-account/src/pages/snippets.rs | 12 +- crates/forge-web-app/src/alerts.rs | 235 ++- crates/forge-web-app/src/api/gitea.rs | 10 +- crates/forge-web-app/src/api/statuses.rs | 2 +- crates/forge-web-app/src/auth.rs | 19 +- crates/forge-web-app/src/backup/scheduler.rs | 38 +- crates/forge-web-app/src/ci/api.rs | 21 +- crates/forge-web-app/src/ci/api_tests.rs | 24 +- crates/forge-web-app/src/ci/schedule.rs | 23 +- crates/forge-web-app/src/lfs/gc.rs | 3 +- crates/forge-web-app/src/lfs/mod.rs | 7 + crates/forge-web-app/src/lfs/routes.rs | 32 +- crates/forge-web-app/src/lib.rs | 1 - crates/forge-web-app/src/merge_queue.rs | 73 +- crates/forge-web-app/src/mirrors/worker.rs | 7 +- crates/forge-web-app/src/oci/auth.rs | 4 +- crates/forge-web-app/src/oci/gc.rs | 23 +- crates/forge-web-app/src/post_update.rs | 47 +- crates/forge-web-app/src/prune.rs | 3 + crates/forge-web-app/src/pulls_sync.rs | 156 +- .../forge-web-app/src/test_support/fixture.rs | 83 + crates/forge-web-app/src/views/diff.rs | 2 +- crates/forge-web-app/src/views/mod.rs | 66 +- crates/forge-web-app/src/views/paging.rs | 18 + crates/forge-web-app/src/views/repo_list.rs | 7 + crates/forge-web-app/src/views/timeline.rs | 4 +- crates/forge-web-app/src/webhooks/emit.rs | 18 +- crates/forge-web-base/src/accent.rs | 13 +- crates/forge-web-base/src/blobs.rs | 15 +- crates/forge-web-base/src/custom_colour.rs | 13 +- crates/forge-web-base/src/i18n/accounts.rs | 203 +-- crates/forge-web-base/src/i18n/admin.rs | 669 ++------ crates/forge-web-base/src/i18n/alerts.rs | 214 +-- crates/forge-web-base/src/i18n/authoring.rs | 51 +- crates/forge-web-base/src/i18n/browse.rs | 19 +- crates/forge-web-base/src/i18n/code.rs | 571 ++----- crates/forge-web-base/src/i18n/community.rs | 456 ++---- .../forge-web-base/src/i18n/integrations.rs | 464 ++---- crates/forge-web-base/src/i18n/issues.rs | 710 ++------- crates/forge-web-base/src/i18n/link.rs | 42 +- crates/forge-web-base/src/i18n/merge_queue.rs | 175 +-- crates/forge-web-base/src/i18n/migrate.rs | 343 +---- crates/forge-web-base/src/i18n/misc.rs | 615 ++------ crates/forge-web-base/src/i18n/mod.rs | 971 +++--------- crates/forge-web-base/src/i18n/needs.rs | 95 +- crates/forge-web-base/src/i18n/orgs.rs | 542 ++----- crates/forge-web-base/src/i18n/packages.rs | 126 +- crates/forge-web-base/src/i18n/pulls.rs | 351 +---- .../forge-web-base/src/i18n/pulls_review.rs | 411 +---- crates/forge-web-base/src/i18n/push.rs | 94 +- crates/forge-web-base/src/i18n/releases_ci.rs | 626 ++------ crates/forge-web-base/src/i18n/repo_admin.rs | 567 ++----- crates/forge-web-base/src/i18n/timeline.rs | 18 +- .../src/pages/admin_runners.rs | 91 +- .../forge-web-pages/src/pages/admin_users.rs | 16 +- crates/forge-web-pages/src/pages/ci_job.rs | 19 +- crates/forge-web-pages/src/pages/ci_runs.rs | 142 +- .../src/pages/discussion_settings.rs | 2 +- .../forge-web-pages/src/pages/issue_meta.rs | 4 +- .../forge-web-pages/src/pages/issue_parts.rs | 90 +- .../forge-web-pages/src/pages/issues_list.rs | 30 +- crates/forge-web-pages/src/pages/mod.rs | 26 + .../src/pages/notifications.rs | 14 +- crates/forge-web-pages/src/pages/pull_live.rs | 6 +- .../forge-web-pages/src/pages/pull_reviews.rs | 60 +- crates/forge-web-pages/src/pages/refs.rs | 4 +- crates/forge-web-pages/src/pages/releases.rs | 197 +-- .../src/pages/releases_live.rs | 5 +- crates/forge-web-pages/src/pages/repo.rs | 4 +- crates/forge-web-pages/src/pages/repo_ctx.rs | 46 +- .../forge-web-pages/src/pages/repo_mirrors.rs | 93 +- .../forge-web-pages/src/pages/repo_rename.rs | 2 +- .../src/pages/repo_security.rs | 26 +- .../src/pages/repo_settings.rs | 43 +- crates/forge-web-pages/src/pages/tree.rs | 4 +- crates/forge-web-pages/src/pages/wiki.rs | 12 +- .../src/pages/authoring_tests.rs | 46 +- crates/forge-web-repo/src/pages/blame.rs | 2 +- crates/forge-web-repo/src/pages/blob.rs | 2 +- crates/forge-web-repo/src/pages/branches.rs | 24 +- crates/forge-web-repo/src/pages/ci_tests.rs | 32 +- .../forge-web-repo/src/pages/code_search.rs | 2 +- crates/forge-web-repo/src/pages/commit.rs | 2 +- crates/forge-web-repo/src/pages/commits.rs | 10 +- crates/forge-web-repo/src/pages/compare.rs | 63 +- .../src/pages/discussion_actions.rs | 2 +- .../src/pages/discussion_live_tests.rs | 22 +- .../src/pages/discussion_view.rs | 4 +- .../forge-web-repo/src/pages/discussions.rs | 23 +- crates/forge-web-repo/src/pages/fork.rs | 38 +- .../src/pages/issue_meta_tests.rs | 39 +- .../src/pages/issue_pin_tests.rs | 102 +- crates/forge-web-repo/src/pages/issue_view.rs | 47 +- .../forge-web-repo/src/pages/labels_page.rs | 29 +- .../forge-web-repo/src/pages/merge_queue.rs | 15 +- .../src/pages/milestones_page.rs | 32 +- .../forge-web-repo/src/pages/pull_branch.rs | 98 +- crates/forge-web-repo/src/pages/pull_files.rs | 64 +- crates/forge-web-repo/src/pages/pull_flow.rs | 20 +- crates/forge-web-repo/src/pages/pull_view.rs | 108 +- crates/forge-web-repo/src/pages/pulls_list.rs | 119 +- .../forge-web-repo/src/pages/pulls_merge.rs | 66 +- crates/forge-web-repo/src/pages/push.rs | 8 +- crates/forge-web-repo/src/pages/reactions.rs | 2 +- .../src/pages/reactions_tests.rs | 30 +- .../src/pages/repo_collaborators.rs | 14 +- crates/forge-web-repo/src/pages/repo_scrub.rs | 2 +- .../forge-web-repo/src/pages/repo_secrets.rs | 69 +- .../forge-web-repo/src/pages/repo_webhooks.rs | 105 +- .../src/pages/review_requests.rs | 30 +- crates/forge-web/src/admin_cli.rs | 19 +- crates/forge-web/src/boot.rs | 93 +- .../forge-web/src/compression_route_tests.rs | 4 +- crates/forge-web/src/forgejo_tests.rs | 15 +- crates/forge-web/src/gitea_route_tests.rs | 28 +- crates/forge-web/src/importer_route_tests.rs | 14 +- crates/forge-web/src/main.rs | 10 +- .../src/page_route_tests/edit_history.rs | 31 +- .../src/page_route_tests/notifications.rs | 46 +- .../src/page_route_tests/pull_reviews.rs | 31 +- crates/forge-web/src/page_route_tests/repo.rs | 34 +- crates/forge-web/src/shell_route_tests.rs | 22 +- crates/forge-web/src/templates_route_tests.rs | 4 +- docs/merge-queue.md | 2 +- 269 files changed, 7316 insertions(+), 14474 deletions(-) create mode 100644 crates/forge-ci/src/config/artifact.rs create mode 100644 crates/forge-ci/src/config/cache.rs create mode 100644 crates/forge-ci/src/config/job.rs create mode 100644 crates/forge-ci/src/config/matrix.rs create mode 100644 crates/forge-ci/src/config/memory.rs create mode 100644 crates/forge-ci/src/config/release.rs create mode 100644 crates/forge-ci/src/config/schedule.rs create mode 100644 crates/forge-ci/src/config/trigger.rs create mode 100644 crates/forge-ci/src/config/workflow.rs create mode 100644 crates/forge-core/migrations/0075_runner_registered_labels.sql create mode 100644 crates/forge-core/migrations/0076_milestone_title_repair.sql create mode 100644 crates/forge-core/src/signed_token.rs create mode 100644 crates/forge-web-app/src/views/paging.rs diff --git a/Cargo.lock b/Cargo.lock index a7d8beb..d50ff56 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2070,6 +2070,7 @@ dependencies = [ "nix 0.31.4", "oci-client", "oci-spec", + "rand 0.10.4", "reqwest", "seccompiler", "serde", diff --git a/crates/forge-ci/build_identity.rs b/crates/forge-ci/build_identity.rs index 44edceb..d6e0d07 100644 --- a/crates/forge-ci/build_identity.rs +++ b/crates/forge-ci/build_identity.rs @@ -14,7 +14,6 @@ pub fn emit_identity() { if env::var("PROFILE").as_deref() != Ok("release") { println!("cargo:rustc-env=FORGE_GIT_SHA=unknown"); println!("cargo:rustc-env=FORGE_GIT_DATE=unknown"); - println!("cargo:rustc-env=FORGE_GIT_DIRTY=0"); return; } @@ -39,8 +38,6 @@ pub fn emit_identity() { let date = git(&["show", "-s", "--format=%cs", "HEAD"]) .or_else(|| env::var("FORGE_BUILD_DATE").ok().filter(|s| !s.is_empty())) .unwrap_or_else(|| "unknown".into()); - let dirty = git(&["status", "--porcelain", "--untracked-files=no"]).is_some(); println!("cargo:rustc-env=FORGE_GIT_SHA={sha}"); println!("cargo:rustc-env=FORGE_GIT_DATE={date}"); - println!("cargo:rustc-env=FORGE_GIT_DIRTY={}", u8::from(dirty)); } diff --git a/crates/forge-ci/src/build.rs b/crates/forge-ci/src/build.rs index 2250ba4..f537b96 100644 --- a/crates/forge-ci/src/build.rs +++ b/crates/forge-ci/src/build.rs @@ -5,17 +5,12 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION"); struct Identity { commit: &'static str, date: &'static str, - dirty: bool, } static IDENTITY: OnceLock = OnceLock::new(); -pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) { - let _ = IDENTITY.set(Identity { - commit, - date, - dirty, - }); +pub fn set_identity(commit: &'static str, date: &'static str) { + let _ = IDENTITY.set(Identity { commit, date }); } pub fn commit() -> &'static str { @@ -26,23 +21,17 @@ pub fn date() -> &'static str { IDENTITY.get().map_or("unknown", |i| i.date) } -pub fn dirty() -> bool { - IDENTITY.get().is_some_and(|i| i.dirty) -} - pub fn display() -> String { - format_build(VERSION, commit(), date(), dirty()) + format_build(VERSION, commit(), date()) } -pub fn format_build(version: &str, commit: &str, date: &str, dirty: bool) -> String { - let dirty = if dirty { "-dirty" } else { "" }; - format!("{version} ({commit}{dirty}, {date})") +pub fn format_build(version: &str, commit: &str, date: &str) -> String { + format!("{version} ({commit}, {date})") } pub fn commit_of(build: &str) -> Option<&str> { let inner = build.split_once('(')?.1; let commit = inner.split([',', ')']).next()?.trim(); - let commit = commit.strip_suffix("-dirty").unwrap_or(commit); (!commit.is_empty() && commit != "unknown").then_some(commit) } @@ -67,15 +56,13 @@ mod tests { #[test] fn up_to_date_compares_the_commit_only() { - let server = format_build("0.1.0", "cf8e648", "2026-10-20", false); + let server = format_build("0.1.0", "cf8e648", "2026-10-20"); assert_eq!(server, "0.1.0 (cf8e648, 2026-10-20)"); - let same = format_build("0.1.0", "cf8e648", "2026-10-20", true); - assert_eq!(compare(Some(&same), &server), Freshness::UpToDate); - let older = format_build("0.1.0", "4d21658", "2026-10-19", false); + let older = format_build("0.1.0", "4d21658", "2026-10-19"); assert_eq!(compare(Some(&older), &server), Freshness::Outdated); assert_eq!(compare(None, &server), Freshness::Unknown); assert_eq!(compare(Some("0.1.0"), &server), Freshness::Unknown); - let unknown = format_build("0.1.0", "unknown", "unknown", false); - assert_eq!(compare(Some(&same), &unknown), Freshness::Unknown); + let unknown = format_build("0.1.0", "unknown", "unknown"); + assert_eq!(compare(Some(&server), &unknown), Freshness::Unknown); } } diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index fe0255f..7cb22db 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -1,22 +1,34 @@ use std::collections::{BTreeMap, BTreeSet}; -use globset::{Glob, GlobBuilder}; use serde::{Deserialize, Serialize}; use crate::error::ConfigError; -const MAX_CONFIG_BYTES: usize = 64 * 1024; +mod artifact; +mod cache; +mod job; +mod matrix; +mod memory; +mod release; +mod schedule; +mod trigger; +mod workflow; + +pub use job::JobSpec; +pub use matrix::{MatrixSpec, MatrixValue}; +pub use release::{Prerelease, ReleaseNotes, ReleaseSpec}; +pub use trigger::Triggers; + +use job::{is_job_name, validate_job}; +use matrix::{combinations, interpolate}; +use release::validate_release; +use schedule::validate_schedules; +use trigger::{matches_any, validate_trigger_glob}; +use workflow::validate_workflow_name; + +pub const MAX_CONFIG_BYTES: usize = 64 * 1024; const MAX_JOBS: usize = 20; -const DEFAULT_TIMEOUT_MINUTES: u32 = 60; -const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive = 1..=360; -const MAX_WORKFLOW_NAME_CHARS: usize = 40; -const MAX_CACHE_ENTRIES: usize = 8; -const MAX_CACHE_PATH_CHARS: usize = 200; -const MAX_RELEASE_ASSETS: usize = 32; -const MAX_RELEASE_TITLE_CHARS: usize = 200; - -const MAX_SCHEDULES: usize = 8; -const MAX_MATRIX_VALUE_CHARS: usize = 64; +pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CiConfig { @@ -32,192 +44,6 @@ pub struct CiConfig { pub warnings: Vec, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct ReleaseSpec { - pub assets: Vec, - pub prerelease: Prerelease, - pub draft: bool, - pub notes: ReleaseNotes, - pub title: String, -} - -impl Default for ReleaseSpec { - fn default() -> Self { - Self { - assets: Vec::new(), - prerelease: Prerelease::Auto, - draft: false, - notes: ReleaseNotes::Commits, - title: "{tag}".to_string(), - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Prerelease { - Auto, - Always, - Never, -} - -impl Serialize for Prerelease { - fn serialize(&self, serializer: S) -> Result { - match self { - Prerelease::Auto => serializer.serialize_str("auto"), - Prerelease::Always => serializer.serialize_bool(true), - Prerelease::Never => serializer.serialize_bool(false), - } - } -} - -impl<'de> Deserialize<'de> for Prerelease { - fn deserialize>(deserializer: D) -> Result { - #[derive(Deserialize)] - #[serde(untagged)] - enum Raw { - Flag(bool), - Text(String), - } - match Raw::deserialize(deserializer)? { - Raw::Flag(true) => Ok(Prerelease::Always), - Raw::Flag(false) => Ok(Prerelease::Never), - Raw::Text(text) if text == "auto" => Ok(Prerelease::Auto), - Raw::Text(text) => Err(serde::de::Error::custom(format!( - "prerelease must be \"auto\", true or false, got {text:?}" - ))), - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum ReleaseNotes { - Commits, - #[serde(rename = "none")] - Off, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct Triggers { - pub push: Vec, - pub tags: Vec, - pub pull_request: bool, - pub manual: bool, - pub cancel_superseded: bool, - pub merge_queue: bool, - pub schedule: Vec, -} - -impl Default for Triggers { - fn default() -> Self { - Self { - push: Vec::new(), - tags: Vec::new(), - pull_request: false, - manual: true, - cancel_superseded: true, - merge_queue: false, - schedule: Vec::new(), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct JobSpec { - pub image: String, - pub run: String, - #[serde(default)] - pub needs: Vec, - #[serde(default)] - pub secrets: Vec, - #[serde(default)] - pub env: BTreeMap, - #[serde(default)] - pub artifacts: Vec, - #[serde(default)] - pub runs_on: Vec, - #[serde(default)] - pub cache: Vec, - #[serde(default = "default_timeout_minutes")] - pub timeout_minutes: u32, - #[serde(default = "default_network")] - pub network: bool, - #[serde( - default, - deserialize_with = "deserialize_memory", - skip_serializing_if = "Option::is_none" - )] - pub memory: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub matrix: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] -pub struct MatrixValue(pub String); - -impl Serialize for MatrixValue { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_str(&self.0) - } -} - -impl<'de> Deserialize<'de> for MatrixValue { - fn deserialize>(deserializer: D) -> Result { - #[derive(Deserialize)] - #[serde(untagged)] - enum Raw { - Text(String), - Int(i64), - Flag(bool), - } - Ok(MatrixValue(match Raw::deserialize(deserializer)? { - Raw::Text(text) => text, - Raw::Int(n) => n.to_string(), - Raw::Flag(b) => b.to_string(), - })) - } -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct MatrixSpec { - #[serde(default)] - pub exclude: Vec>, - #[serde(default)] - pub include: Vec>, - #[serde(flatten)] - pub axes: BTreeMap>, -} - -const MEMORY_RANGE_BYTES: std::ops::RangeInclusive = (64 << 20)..=(1024 << 30); - -fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { - #[derive(Deserialize)] - #[serde(untagged)] - enum Raw { - Bytes(u64), - Text(String), - } - match Option::::deserialize(d)? { - None => Ok(None), - Some(Raw::Bytes(n)) => Ok(Some(n)), - Some(Raw::Text(text)) => crate::size::parse_size(&text).map(Some).ok_or_else(|| { - serde::de::Error::custom(format!( - "memory must be a size such as 4g or 512m, got {text:?}" - )) - }), - } -} - -fn default_timeout_minutes() -> u32 { - DEFAULT_TIMEOUT_MINUTES -} - -fn default_network() -> bool { - true -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Event<'a> { Push { branch: &'a str }, @@ -360,18 +186,7 @@ impl CiConfig { for pattern in &self.on.tags { validate_trigger_glob("tag", pattern)?; } - if self.on.schedule.len() > MAX_SCHEDULES { - return Err(ConfigError::TooManySchedules { - count: self.on.schedule.len(), - max: MAX_SCHEDULES, - }); - } - for expr in &self.on.schedule { - crate::cron::parse(expr).map_err(|reason| ConfigError::InvalidSchedule { - expr: expr.clone(), - reason, - })?; - } + validate_schedules(&self.on.schedule)?; for (name, job) in &self.jobs { validate_job(name, job, &self.jobs)?; } @@ -392,251 +207,6 @@ impl CiConfig { } } -impl ReleaseSpec { - pub fn is_prerelease(&self, tag: &str) -> bool { - match self.prerelease { - Prerelease::Auto => tag.contains('-'), - Prerelease::Always => true, - Prerelease::Never => false, - } - } - - pub fn title_for(&self, tag: &str) -> String { - self.title.trim().replace("{tag}", tag) - } - - pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { - self.assets.iter().any(|asset| { - asset_selector(asset).is_some_and(|(selected_job, glob)| { - names_job(selected_job, job) && matches_any(&[glob.to_string()], artifact_name) - }) - }) - } -} - -fn asset_selector(asset: &str) -> Option<(&str, &str)> { - asset.split_once(':') -} - -fn matches_any(globs: &[String], value: &str) -> bool { - globs - .iter() - .any(|pattern| build_glob(pattern).is_ok_and(|g| g.compile_matcher().is_match(value))) -} - -fn build_glob(pattern: &str) -> Result { - GlobBuilder::new(pattern).literal_separator(true).build() -} - -fn validate_trigger_glob(kind: &'static str, pattern: &str) -> Result<(), ConfigError> { - let invalid = |reason: String| ConfigError::InvalidTriggerGlob { - kind, - pattern: pattern.to_string(), - reason, - }; - if pattern.is_empty() { - return Err(invalid("pattern is empty".into())); - } - build_glob(pattern) - .map(|_| ()) - .map_err(|e| invalid(e.to_string())) -} - -fn validate_workflow_name(name: &str) -> Result<(), ConfigError> { - let invalid = |reason: &str| ConfigError::InvalidWorkflowName { - name: name.to_string(), - reason: reason.to_string(), - }; - let trimmed = name.trim(); - if trimmed.is_empty() { - return Err(invalid("must not be empty")); - } - if trimmed.chars().count() > MAX_WORKFLOW_NAME_CHARS { - return Err(invalid(&format!( - "must be at most {MAX_WORKFLOW_NAME_CHARS} characters" - ))); - } - if trimmed.chars().any(char::is_control) { - return Err(invalid("must not contain control characters")); - } - Ok(()) -} - -fn is_job_name(name: &str) -> bool { - let Some((first, rest)) = name.as_bytes().split_first() else { - return false; - }; - rest.len() <= 39 - && (first.is_ascii_lowercase() || first.is_ascii_digit()) - && rest - .iter() - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-') -} - -fn is_env_name(name: &str) -> bool { - let Some((first, rest)) = name.as_bytes().split_first() else { - return false; - }; - rest.len() <= 63 - && (first.is_ascii_uppercase() || *first == b'_') - && rest - .iter() - .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || *b == b'_') -} - -fn is_runner_label(label: &str) -> bool { - (1..=64).contains(&label.len()) - && label - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') -} - -fn validate_artifact(job: &str, pattern: &str) -> Result<(), ConfigError> { - let invalid = |reason: &str| ConfigError::InvalidArtifactGlob { - job: job.to_string(), - pattern: pattern.to_string(), - reason: reason.to_string(), - }; - if pattern.is_empty() { - return Err(invalid("pattern is empty")); - } - if pattern.starts_with('/') || pattern.starts_with('\\') { - return Err(invalid("must be relative")); - } - if pattern.split(['/', '\\']).any(|part| part == "..") { - return Err(invalid("must not contain \"..\"")); - } - build_glob(pattern) - .map(|_| ()) - .map_err(|e| invalid(&e.to_string())) -} - -fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> { - if entries.len() > MAX_CACHE_ENTRIES { - return Err(ConfigError::TooManyCacheEntries { - job: job.to_string(), - count: entries.len(), - max: MAX_CACHE_ENTRIES, - }); - } - let mut seen = BTreeSet::new(); - for path in entries { - validate_cache_path(job, path)?; - if !seen.insert(path.as_str()) { - return Err(ConfigError::DuplicateCachePath { - job: job.to_string(), - path: path.clone(), - }); - } - } - Ok(()) -} - -fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { - let invalid = |reason: &str| ConfigError::InvalidCachePath { - job: job.to_string(), - path: path.to_string(), - reason: reason.to_string(), - }; - if path.is_empty() { - return Err(invalid("must not be empty")); - } - if path.chars().count() > MAX_CACHE_PATH_CHARS { - return Err(invalid(&format!( - "must be at most {MAX_CACHE_PATH_CHARS} characters" - ))); - } - if path.starts_with('/') { - return Err(invalid("must be relative")); - } - if path.contains('\\') { - return Err(invalid("must not contain a backslash")); - } - if path.chars().any(|c| "*?[]{}".contains(c)) { - return Err(invalid("must not contain glob characters")); - } - if path.chars().any(char::is_control) { - return Err(invalid("must not contain control characters")); - } - for part in path.split('/') { - match part { - "" => return Err(invalid("must not contain empty components")), - "." | ".." => return Err(invalid("must not contain \".\" or \"..\" components")), - _ if part.eq_ignore_ascii_case(".git") => { - return Err(invalid("must not be inside .git")); - } - _ => {} - } - } - Ok(()) -} - -fn validate_release( - release: &ReleaseSpec, - on: &Triggers, - jobs: &BTreeMap, -) -> Result<(), ConfigError> { - if on.tags.is_empty() { - return Err(ConfigError::ReleaseWithoutTags); - } - if release.assets.len() > MAX_RELEASE_ASSETS { - return Err(ConfigError::TooManyReleaseAssets { - count: release.assets.len(), - max: MAX_RELEASE_ASSETS, - }); - } - for asset in &release.assets { - validate_release_asset(asset, jobs)?; - } - validate_release_title(&release.title) -} - -fn validate_release_asset( - asset: &str, - jobs: &BTreeMap, -) -> Result<(), ConfigError> { - let invalid = |reason: String| ConfigError::InvalidReleaseAsset { - asset: asset.to_string(), - reason, - }; - let Some((job, glob)) = asset_selector(asset) else { - return Err(invalid("must be \"job:glob\"".into())); - }; - let Some((_, spec)) = jobs.iter().find(|(name, _)| names_job(job, name)) else { - return Err(invalid(format!("job {job:?} is not defined"))); - }; - if spec.artifacts.is_empty() { - return Err(invalid(format!("job {job:?} declares no artifacts"))); - } - if glob.is_empty() { - return Err(invalid("glob must not be empty".into())); - } - if glob.contains('/') { - return Err(invalid( - "glob must not contain \"/\", artifact names are flattened".into(), - )); - } - build_glob(glob) - .map(|_| ()) - .map_err(|e| invalid(e.to_string())) -} - -fn validate_release_title(title: &str) -> Result<(), ConfigError> { - let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason); - if title.trim().is_empty() { - return Err(invalid("must not be empty".into())); - } - if title.trim().chars().count() > MAX_RELEASE_TITLE_CHARS { - return Err(invalid(format!( - "must be at most {MAX_RELEASE_TITLE_CHARS} characters" - ))); - } - if title.chars().any(char::is_control) { - return Err(invalid("must not contain control characters".into())); - } - Ok(()) -} - fn names_job(selected: &str, job: &str) -> bool { selected == job || job @@ -644,245 +214,6 @@ fn names_job(selected: &str, job: &str) -> bool { .is_some_and(|rest| rest.starts_with(" (")) } -fn is_matrix_key(key: &str) -> bool { - let Some((first, rest)) = key.as_bytes().split_first() else { - return false; - }; - rest.len() <= 31 - && first.is_ascii_lowercase() - && rest - .iter() - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_') -} - -type Combination = (String, BTreeMap); - -fn combinations(job: &str, matrix: &MatrixSpec) -> Result, ConfigError> { - let bad = |reason: String| ConfigError::InvalidMatrix { - job: job.to_string(), - reason, - }; - if matrix.axes.is_empty() { - return Err(bad( - "needs at least one axis, e.g. rust = [\"stable\"]".into() - )); - } - let mut total: usize = 1; - for (key, values) in &matrix.axes { - if !is_matrix_key(key) { - return Err(bad(format!( - "axis name {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" - ))); - } - if values.is_empty() { - return Err(bad(format!("axis {key:?} has no values"))); - } - for (i, value) in values.iter().enumerate() { - validate_matrix_value(&value.0).map_err(|r| bad(format!("axis {key:?}: {r}")))?; - if values[..i].contains(value) { - return Err(bad(format!("axis {key:?} lists {:?} twice", value.0))); - } - } - total = total.saturating_mul(values.len()); - if total > MAX_JOBS { - return Err(ConfigError::MatrixTooLarge { - job: job.to_string(), - count: total, - max: MAX_JOBS, - }); - } - } - let mut combos: Vec> = vec![BTreeMap::new()]; - for (key, values) in &matrix.axes { - combos = combos - .into_iter() - .flat_map(|base| { - values.iter().map(move |value| { - let mut next = base.clone(); - next.insert(key.clone(), value.0.clone()); - next - }) - }) - .collect(); - } - for entry in &matrix.exclude { - for key in entry.keys() { - if !matrix.axes.contains_key(key) { - return Err(bad(format!("exclude names {key:?}, which is not an axis"))); - } - } - combos.retain(|combo| !entry.iter().all(|(k, v)| combo.get(k) == Some(&v.0))); - } - for entry in &matrix.include { - let mut combo = BTreeMap::new(); - for (key, value) in entry { - if !is_matrix_key(key) { - return Err(bad(format!( - "include key {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" - ))); - } - validate_matrix_value(&value.0).map_err(|r| bad(format!("include {key:?}: {r}")))?; - combo.insert(key.clone(), value.0.clone()); - } - if let Some(missing) = matrix.axes.keys().find(|k| !combo.contains_key(*k)) { - return Err(bad(format!("an include entry must set axis {missing:?}"))); - } - let same_axes = |other: &BTreeMap| { - matrix.axes.keys().all(|k| other.get(k) == combo.get(k)) - }; - if !combos.iter().any(same_axes) { - combos.push(combo); - } - } - if combos.is_empty() { - return Err(bad("exclude removes every combination".into())); - } - if combos.len() > MAX_JOBS { - return Err(ConfigError::MatrixTooLarge { - job: job.to_string(), - count: combos.len(), - max: MAX_JOBS, - }); - } - Ok(combos - .into_iter() - .map(|combo| { - let suffix = matrix - .axes - .keys() - .filter_map(|k| combo.get(k).map(String::as_str)) - .collect::>() - .join(", "); - (suffix, combo) - }) - .collect()) -} - -fn validate_matrix_value(value: &str) -> Result<(), String> { - if value.is_empty() { - return Err("values must not be empty".into()); - } - if value.chars().count() > MAX_MATRIX_VALUE_CHARS { - return Err(format!( - "values must be at most {MAX_MATRIX_VALUE_CHARS} characters" - )); - } - if value - .chars() - .any(|c| c.is_control() || matches!(c, ',' | '(' | ')')) - { - return Err(format!( - "{value:?} must not contain control characters, commas or parentheses" - )); - } - Ok(()) -} - -fn interpolate( - job: &str, - text: &str, - vars: &BTreeMap, -) -> Result { - let mut out = String::with_capacity(text.len()); - let mut rest = text; - while let Some(at) = rest.find("${") { - out.push_str(&rest[..at]); - let after = &rest[at + 2..]; - let found = if let Some(body) = after.strip_prefix('{') { - body.find("}}") - .map(|end| (body[..end].trim(), &body[end + 2..])) - } else { - after - .find('}') - .map(|end| (after[..end].trim(), &after[end + 1..])) - }; - match found.and_then(|(inner, tail)| Some((inner.strip_prefix("matrix.")?, tail))) { - Some((key, tail)) => { - let value = vars.get(key).ok_or_else(|| ConfigError::InvalidMatrix { - job: job.to_string(), - reason: format!("`matrix.{key}` is not an axis or include key"), - })?; - out.push_str(value); - rest = tail; - } - None => { - out.push_str("${"); - rest = after; - } - } - } - out.push_str(rest); - Ok(out) -} - -fn validate_job( - name: &str, - job: &JobSpec, - all: &BTreeMap, -) -> Result<(), ConfigError> { - if job.image.is_empty() || job.image.chars().any(char::is_whitespace) { - return Err(ConfigError::InvalidImage { - job: name.to_string(), - }); - } - if job.run.trim().is_empty() { - return Err(ConfigError::EmptyRun { - job: name.to_string(), - }); - } - for need in &job.needs { - if !all.contains_key(need) { - return Err(ConfigError::UnknownNeed { - job: name.to_string(), - need: need.clone(), - }); - } - } - for secret in &job.secrets { - if !is_env_name(secret) { - return Err(ConfigError::InvalidSecretName { - job: name.to_string(), - name: secret.clone(), - }); - } - } - for key in job.env.keys() { - if !is_env_name(key) { - return Err(ConfigError::InvalidEnvName { - job: name.to_string(), - name: key.clone(), - }); - } - } - for pattern in &job.artifacts { - validate_artifact(name, pattern)?; - } - for label in &job.runs_on { - if !is_runner_label(label) { - return Err(ConfigError::InvalidRunsOn { - job: name.to_string(), - label: label.clone(), - }); - } - } - validate_cache(name, &job.cache)?; - if !TIMEOUT_RANGE_MINUTES.contains(&job.timeout_minutes) { - return Err(ConfigError::InvalidTimeout { - job: name.to_string(), - value: job.timeout_minutes, - }); - } - if let Some(memory) = job.memory - && !MEMORY_RANGE_BYTES.contains(&memory) - { - return Err(ConfigError::InvalidMemory { - job: name.to_string(), - value: crate::size::format_size(memory), - }); - } - Ok(()) -} - #[cfg(test)] mod tests { use super::*; @@ -907,11 +238,11 @@ cargo fmt --check artifacts = ["target/release/forge"] "#; - fn job_toml(body: &str) -> String { + pub(super) fn job_toml(body: &str) -> String { format!("[jobs.build]\nimage = \"docker.io/rust:1\"\nrun = \"cargo build\"\n{body}\n") } - fn err_of(text: &str) -> ConfigError { + pub(super) fn err_of(text: &str) -> ConfigError { match parse_config(text) { Ok(_) => panic!("expected an error for:\n{text}"), Err(e) => e, @@ -953,13 +284,6 @@ artifacts = ["target/release/forge"] !parse_config(&job_toml("network = false")).unwrap().jobs["build"].network, "network = false is honoured" ); - let release = release_of(&release_toml("")); - assert!(release.assets.is_empty()); - assert_eq!(release.prerelease, Prerelease::Auto); - assert!(!release.draft); - assert_eq!(release.notes, ReleaseNotes::Commits); - assert_eq!(release.title, "{tag}"); - assert_eq!(release, ReleaseSpec::default()); } #[test] @@ -1022,47 +346,6 @@ artifacts = ["target/release/forge"] )); } - #[test] - fn memory_is_parsed_to_bytes() { - let cfg = parse_config(&job_toml("memory = \"4g\"")).unwrap(); - assert_eq!(cfg.jobs["build"].memory, Some(4 << 30)); - let cfg = parse_config(&job_toml("memory = \"512M\"")).unwrap(); - assert_eq!(cfg.jobs["build"].memory, Some(512 << 20)); - assert_eq!( - parse_config(&job_toml("")).unwrap().jobs["build"].memory, - None - ); - let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"]; - let json = serde_json::to_string(job).unwrap(); - assert!(json.contains("\"memory\":4294967296"), "{json}"); - let back: JobSpec = serde_json::from_str(&json).unwrap(); - assert_eq!(back.memory, Some(4 << 30)); - let old = json.replace(",\"memory\":4294967296", ""); - assert_eq!(serde_json::from_str::(&old).unwrap().memory, None); - } - - #[test] - fn bad_memory_is_an_error() { - for bad in ["\"lots\"", "\"0\"", "\"-1g\"", "true"] { - assert!( - matches!( - err_of(&job_toml(&format!("memory = {bad}"))), - ConfigError::Toml(_) - ), - "{bad}" - ); - } - for bad in ["\"1m\"", "\"2t\""] { - assert!( - matches!( - err_of(&job_toml(&format!("memory = {bad}"))), - ConfigError::InvalidMemory { .. } - ), - "{bad}" - ); - } - } - #[test] fn no_jobs_is_an_error() { assert_eq!(err_of("[on]\nmanual = true\n"), ConfigError::NoJobs); @@ -1154,201 +437,6 @@ artifacts = ["target/release/forge"] ); } - #[test] - fn image_and_run_validation() { - let cases = [ - ("image", "[jobs.b]\nimage = \"\"\nrun = \"r\"\n"), - ("image", "[jobs.b]\nimage = \"a b\"\nrun = \"r\"\n"), - ("run", "[jobs.b]\nimage = \"i\"\nrun = \" \\n \"\n"), - ]; - for (want, text) in cases { - let got = match err_of(text) { - ConfigError::InvalidImage { .. } => "image", - ConfigError::EmptyRun { .. } => "run", - other => panic!("case {text:?}: unexpected error {other:?}"), - }; - assert_eq!(got, want, "case {text:?}"); - } - } - - #[test] - fn secret_and_env_names() { - let long = "A".repeat(65); - for bad in ["deploy", "1KEY", "A-B", "", long.as_str()] { - let text = job_toml(&format!("secrets = [{bad:?}]")); - assert!( - matches!(err_of(&text), ConfigError::InvalidSecretName { .. }), - "secret {bad:?} should be rejected" - ); - } - let text = job_toml("secrets = [\"_OK_1\"]"); - assert!(parse_config(&text).is_ok()); - let text = job_toml("[jobs.build.env]\n\"lower\" = \"x\""); - assert!(matches!(err_of(&text), ConfigError::InvalidEnvName { .. })); - let text = job_toml("[jobs.build.env]\nRUST_LOG = \"info\""); - assert!(parse_config(&text).is_ok()); - } - - #[test] - fn artifact_validation() { - for bad in ["/etc/passwd", "..", "a/../b", "\\\\x", "", "a/[b"] { - let text = job_toml(&format!("artifacts = [{bad:?}]")); - assert!( - matches!(err_of(&text), ConfigError::InvalidArtifactGlob { .. }), - "artifact {bad:?} should be rejected" - ); - } - let text = job_toml("artifacts = [\"target/release/*\", \"dist/**/*.tar\"]"); - assert!(parse_config(&text).is_ok()); - } - - #[test] - fn runs_on_validation() { - let text = job_toml("runs_on = [\"linux\", \"x86_64\"]"); - assert_eq!( - parse_config(&text).unwrap().jobs["build"].runs_on, - vec!["linux".to_string(), "x86_64".to_string()] - ); - let text = job_toml("runs_on = [\"has space\"]"); - assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); - let text = job_toml("runs_on = [\"\"]"); - assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); - } - - #[test] - fn cache_accepts_relative_directories() { - let text = job_toml("cache = [\"target\", \".cargo-home\", \"a/b/c\"]"); - assert_eq!( - parse_config(&text).unwrap().jobs["build"].cache, - vec![ - "target".to_string(), - ".cargo-home".to_string(), - "a/b/c".to_string() - ] - ); - let at_limit = "x".repeat(MAX_CACHE_PATH_CHARS); - let text = job_toml(&format!("cache = [{at_limit:?}]")); - assert!(parse_config(&text).is_ok()); - } - - #[test] - fn cache_rejects_bad_paths() { - let long = "x".repeat(MAX_CACHE_PATH_CHARS + 1); - let bad = [ - "".to_string(), - "/abs".to_string(), - "a\\b".to_string(), - "..".to_string(), - "a/../b".to_string(), - "./target".to_string(), - ".".to_string(), - "a//b".to_string(), - "target/".to_string(), - ".git".to_string(), - ".git/objects".to_string(), - "sub/.GIT/x".to_string(), - "target/*".to_string(), - "t?rget".to_string(), - "[t]".to_string(), - "{a,b}".to_string(), - long, - ]; - let text = job_toml(r#"cache = ["a\u0007b"]"#); - assert!(matches!( - err_of(&text), - ConfigError::InvalidCachePath { .. } - )); - for path in bad { - let text = job_toml(&format!("cache = [{path:?}]")); - assert!( - matches!(err_of(&text), ConfigError::InvalidCachePath { .. }), - "cache path {path:?} should be rejected" - ); - } - } - - #[test] - fn cache_rejects_duplicates_and_too_many_entries() { - let text = job_toml("cache = [\"target\", \"target\"]"); - assert!(matches!( - err_of(&text), - ConfigError::DuplicateCachePath { .. } - )); - let entries: Vec = (0..=MAX_CACHE_ENTRIES).map(|i| format!("d{i}")).collect(); - let text = job_toml(&format!("cache = {entries:?}")); - assert_eq!( - err_of(&text), - ConfigError::TooManyCacheEntries { - job: "build".into(), - count: MAX_CACHE_ENTRIES + 1, - max: MAX_CACHE_ENTRIES - } - ); - let text = job_toml(&format!("cache = {:?}", &entries[..MAX_CACHE_ENTRIES])); - assert!(parse_config(&text).is_ok()); - } - - #[test] - fn timeout_validation() { - assert_eq!( - parse_config(&job_toml("timeout_minutes = 1")).unwrap().jobs["build"].timeout_minutes, - 1 - ); - assert_eq!( - parse_config(&job_toml("timeout_minutes = 360")) - .unwrap() - .jobs["build"] - .timeout_minutes, - 360 - ); - for bad in [0, 361] { - let text = job_toml(&format!("timeout_minutes = {bad}")); - assert_eq!( - err_of(&text), - ConfigError::InvalidTimeout { - job: "build".into(), - value: bad - } - ); - } - } - - #[test] - fn branch_and_tag_globs_match_only_their_event_kind() { - let text = format!("[on]\npush = [\"main\", \"release/*\"]\n{}", job_toml("")); - let cfg = parse_config(&text).unwrap(); - assert!(cfg.triggered_by(&Event::Push { branch: "main" })); - assert!(cfg.triggered_by(&Event::Push { - branch: "release/1.0" - })); - assert!(!cfg.triggered_by(&Event::Push { - branch: "release/1.0/x" - })); - assert!(!cfg.triggered_by(&Event::Push { branch: "mainx" })); - assert!(!cfg.triggered_by(&Event::Push { branch: "feature" })); - assert!(!cfg.triggered_by(&Event::Tag { tag: "v1" })); - - let text = format!("[on]\ntags = [\"v*\"]\n{}", job_toml("")); - let cfg = parse_config(&text).unwrap(); - assert!(cfg.triggered_by(&Event::Tag { tag: "v1.2.3" })); - assert!(!cfg.triggered_by(&Event::Tag { tag: "release-1" })); - assert!(!cfg.triggered_by(&Event::Push { branch: "v1" })); - } - - #[test] - fn invalid_trigger_globs_are_rejected() { - let text = format!("[on]\npush = [\"[\"]\n{}", job_toml("")); - assert!(matches!( - err_of(&text), - ConfigError::InvalidTriggerGlob { kind: "branch", .. } - )); - let text = format!("[on]\ntags = [\"\"]\n{}", job_toml("")); - assert!(matches!( - err_of(&text), - ConfigError::InvalidTriggerGlob { kind: "tag", .. } - )); - } - #[test] fn job_order_is_topological_and_stable() { let text = "[jobs.lint]\nimage = \"i\"\nrun = \"r\"\nneeds = [\"test\"]\n\ @@ -1369,383 +457,4 @@ artifacts = ["target/release/forge"] let cfg = parse_config(EXAMPLE).unwrap(); assert_eq!(cfg.job_order(), vec!["test", "lint"]); } - - #[test] - fn workflow_name_is_optional_and_kept() { - assert_eq!(parse_config(&job_toml("")).unwrap().name, None); - let cfg = parse_config(&format!("name = \"build\"\n{}", job_toml(""))).unwrap(); - assert_eq!(cfg.name.as_deref(), Some("build")); - } - - #[test] - fn workflow_name_must_be_one_non_blank_line() { - for text in [ - "name = \"\"", - "name = \" \"", - "name = \"a\\u0007b\"", - "name = \"a\\nb\"", - ] { - let err = err_of(&format!("{text}\n{}", job_toml(""))); - assert!( - matches!(err, ConfigError::InvalidWorkflowName { .. }), - "{text}: {err:?}" - ); - } - } - - #[test] - fn workflow_name_length_is_capped_after_trimming() { - let at_limit = "n".repeat(MAX_WORKFLOW_NAME_CHARS); - let ok = format!("name = \" {at_limit} \"\n{}", job_toml("")); - assert!(parse_config(&ok).is_ok()); - let over = "n".repeat(MAX_WORKFLOW_NAME_CHARS + 1); - let err = err_of(&format!("name = \"{over}\"\n{}", job_toml(""))); - assert!(matches!(err, ConfigError::InvalidWorkflowName { .. })); - } - - #[test] - fn workflow_name_must_be_a_string() { - assert!(matches!( - err_of(&format!("name = 3\n{}", job_toml(""))), - ConfigError::Toml(_) - )); - } - - fn release_toml(release: &str) -> String { - format!( - "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n", - job_toml("artifacts = [\"dist/*\"]") - ) - } - - fn release_of(text: &str) -> ReleaseSpec { - parse_config(text).unwrap().release.expect("release set") - } - - #[test] - fn release_full_table_parses() { - let text = release_toml( - "assets = [\"build:dist_*\", \"build:SHA256SUMS\"]\n\ - prerelease = true\ndraft = true\nnotes = \"none\"\ntitle = \"Release {tag}\"", - ); - let release = release_of(&text); - assert_eq!( - release.assets, - vec!["build:dist_*".to_string(), "build:SHA256SUMS".to_string()] - ); - assert_eq!(release.prerelease, Prerelease::Always); - assert!(release.draft); - assert_eq!(release.notes, ReleaseNotes::Off); - assert_eq!(release.title, "Release {tag}"); - } - - #[test] - fn release_prerelease_and_notes_values() { - assert_eq!( - release_of(&release_toml("prerelease = \"auto\"")).prerelease, - Prerelease::Auto - ); - assert_eq!( - release_of(&release_toml("prerelease = false")).prerelease, - Prerelease::Never - ); - assert_eq!( - release_of(&release_toml("notes = \"commits\"")).notes, - ReleaseNotes::Commits - ); - for bad in ["prerelease = \"yes\"", "notes = \"all\""] { - assert!( - matches!(err_of(&release_toml(bad)), ConfigError::Toml(_)), - "{bad}" - ); - } - } - - #[test] - fn release_unknown_keys_are_ignored_with_a_warning() { - let cfg = parse_config(&release_toml("bogus = 1")).unwrap(); - assert_eq!(cfg.warnings.len(), 1); - assert!( - cfg.warnings[0].contains("`release.bogus`"), - "{:?}", - cfg.warnings - ); - assert!(cfg.release.is_some()); - } - - #[test] - fn release_requires_tags() { - let text = format!("[release]\n{}", job_toml("artifacts = [\"dist/*\"]")); - assert_eq!(err_of(&text), ConfigError::ReleaseWithoutTags); - } - - #[test] - fn release_asset_must_be_job_and_glob() { - for bad in ["build", ":dist_*", "build:", "ghost:dist_*", "build:a/b"] { - let text = release_toml(&format!("assets = [{bad:?}]")); - assert!( - matches!(err_of(&text), ConfigError::InvalidReleaseAsset { .. }), - "asset {bad:?} should be rejected: {:?}", - err_of(&text) - ); - } - let text = release_toml("assets = [\"build:[\"]"); - assert!(matches!( - err_of(&text), - ConfigError::InvalidReleaseAsset { .. } - )); - } - - #[test] - fn release_asset_job_must_declare_artifacts() { - let text = format!( - "[on]\ntags = [\"v*\"]\n{}\n[release]\nassets = [\"build:x\"]\n", - job_toml("") - ); - match err_of(&text) { - ConfigError::InvalidReleaseAsset { asset, reason } => { - assert_eq!(asset, "build:x"); - assert!(reason.contains("no artifacts"), "{reason}"); - } - other => panic!("unexpected error {other:?}"), - } - } - - #[test] - fn release_assets_are_capped() { - let entries: Vec = (0..=MAX_RELEASE_ASSETS) - .map(|_| "build:dist_*".to_string()) - .collect(); - let text = release_toml(&format!("assets = {entries:?}")); - assert_eq!( - err_of(&text), - ConfigError::TooManyReleaseAssets { - count: MAX_RELEASE_ASSETS + 1, - max: MAX_RELEASE_ASSETS - } - ); - let text = release_toml(&format!("assets = {:?}", &entries[..MAX_RELEASE_ASSETS])); - assert!(parse_config(&text).is_ok()); - } - - #[test] - fn release_title_validation() { - for bad in ["", " ", "a\\u0007b"] { - let text = release_toml(&format!("title = \"{bad}\"")); - assert!( - matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_)), - "title {bad:?} should be rejected" - ); - } - let over = "t".repeat(MAX_RELEASE_TITLE_CHARS + 1); - let text = release_toml(&format!("title = \"{over}\"")); - assert!(matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_))); - let at_limit = "t".repeat(MAX_RELEASE_TITLE_CHARS); - assert!(parse_config(&release_toml(&format!("title = \"{at_limit}\""))).is_ok()); - } - - #[test] - fn release_title_for_fills_tag() { - assert_eq!(ReleaseSpec::default().title_for("v1.2.0"), "v1.2.0"); - let release = release_of(&release_toml("title = \"Release {tag}\"")); - assert_eq!(release.title_for("v1.2.0"), "Release v1.2.0"); - let fixed = release_of(&release_toml("title = \"Stable\"")); - assert_eq!(fixed.title_for("v1.2.0"), "Stable"); - } - - #[test] - fn release_prerelease_auto_logic() { - let auto = ReleaseSpec::default(); - assert!(auto.is_prerelease("v1.2.0-rc1")); - assert!(auto.is_prerelease("v2.0.0-beta.3")); - assert!(!auto.is_prerelease("v1.2.0")); - let always = release_of(&release_toml("prerelease = true")); - assert!(always.is_prerelease("v1.2.0")); - let never = release_of(&release_toml("prerelease = false")); - assert!(!never.is_prerelease("v1.2.0-rc1")); - } - - #[test] - fn release_asset_matching() { - let release = release_of(&release_toml( - "assets = [\"build:forge-*-linux-*\", \"build:SHA256SUMS\"]", - )); - assert!(release.asset_matches("build", "forge-1.2.0-linux-x86_64")); - assert!(release.asset_matches("build", "SHA256SUMS")); - assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64")); - assert!(!release.asset_matches("build", "SHA256SUMS.sig")); - assert!(!release.asset_matches("lint", "SHA256SUMS")); - assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS")); - } - - #[test] - fn wants_release_only_for_matching_tags() { - let text = release_toml(""); - let cfg = parse_config(&text).unwrap(); - assert!(cfg.wants_release(&Event::Tag { tag: "v1.2.0" })); - assert!(!cfg.wants_release(&Event::Tag { tag: "release-1" })); - assert!(!cfg.wants_release(&Event::Push { branch: "main" })); - assert!(!cfg.wants_release(&Event::Manual)); - assert!(!cfg.wants_release(&Event::PullRequest)); - - let without = parse_config(&format!("[on]\ntags = [\"v*\"]\n{}", job_toml(""))).unwrap(); - assert!(without.release.is_none()); - assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); - } - - fn matrix_toml(matrix: &str, extra: &str) -> String { - format!( - "[jobs.test]\nimage = \"rust:${{{{ matrix.rust }}}}\"\nrun = \"cargo +${{matrix.rust}} test --target $MATRIX_TARGET\"\nruns_on = [\"${{{{ matrix.target }}}}\"]\nmatrix = {matrix}\n{extra}\n" - ) - } - - const GRID: &str = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"] }"#; - - #[test] - fn schedule_is_parsed_and_validated() { - let cfg = parse_config(&format!( - "[on]\nschedule = [\"0 3 * * *\", \"*/15 * * * 1\"]\n{}", - job_toml("") - )) - .unwrap(); - assert_eq!(cfg.on.schedule.len(), 2); - assert!(cfg.warnings.is_empty()); - assert!(cfg.triggered_by(&Event::Schedule)); - let none = parse_config(&job_toml("")).unwrap(); - assert!(!none.triggered_by(&Event::Schedule)); - for bad in ["0 0 3 * * *", "nope", "70 3 * * *", ""] { - let text = format!("[on]\nschedule = [\"{bad}\"]\n{}", job_toml("")); - assert!( - matches!(err_of(&text), ConfigError::InvalidSchedule { .. }), - "{bad}" - ); - } - let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", "); - let text = format!("[on]\nschedule = [{many}]\n{}", job_toml("")); - assert!(matches!( - err_of(&text), - ConfigError::TooManySchedules { .. } - )); - } - - #[test] - fn a_matrix_expands_into_named_jobs() { - let cfg = parse_config(&matrix_toml(GRID, "")).unwrap(); - let names: Vec<&str> = cfg.jobs.keys().map(String::as_str).collect(); - assert_eq!( - names, - [ - "test (1.85, aarch64)", - "test (1.85, x86_64)", - "test (stable, aarch64)", - "test (stable, x86_64)" - ] - ); - let job = &cfg.jobs["test (stable, x86_64)"]; - assert_eq!(job.image, "rust:stable"); - assert_eq!(job.run, "cargo +stable test --target $MATRIX_TARGET"); - assert_eq!(job.runs_on, vec!["x86_64".to_string()]); - assert_eq!(job.env["MATRIX_RUST"], "stable"); - assert_eq!(job.env["MATRIX_TARGET"], "x86_64"); - assert!(job.matrix.is_none()); - } - - #[test] - fn matrix_exclude_and_include() { - let m = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"], exclude = [{ rust = "1.85", target = "aarch64" }], include = [{ rust = "nightly", target = "x86_64", flag = "-Z" }] }"#; - let cfg = parse_config(&matrix_toml(m, "")).unwrap(); - assert_eq!(cfg.jobs.len(), 4); - assert!(!cfg.jobs.contains_key("test (1.85, aarch64)")); - let extra = &cfg.jobs["test (nightly, x86_64)"]; - assert_eq!(extra.env["MATRIX_FLAG"], "-Z"); - let m = - r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#; - let cfg = parse_config(&matrix_toml(m, "")).unwrap(); - assert_eq!( - cfg.jobs.keys().collect::>(), - ["test (stable, x86_64)"] - ); - let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#; - assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1); - } - - #[test] - fn needs_on_a_matrix_job_waits_for_every_combination() { - let text = format!( - "{}\n[jobs.ship]\nimage = \"img\"\nrun = \"true\"\nneeds = [\"test\"]\n", - matrix_toml(GRID, "") - ); - let cfg = parse_config(&text).unwrap(); - assert_eq!(cfg.jobs["ship"].needs.len(), 4); - let order = cfg.job_order(); - assert_eq!(order.last(), Some(&"ship")); - let text = format!( - "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}", - matrix_toml(GRID, "needs = [\"setup\"]") - ); - let cfg = parse_config(&text).unwrap(); - assert_eq!(cfg.jobs["test (stable, x86_64)"].needs, ["setup"]); - } - - #[test] - fn matrix_errors_are_clear() { - let big = r#"{ a = [1,2,3,4,5], b = [1,2,3,4,5] }"#; - let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {big}\n"); - let e = err_of(&text); - assert_eq!( - e, - ConfigError::MatrixTooLarge { - job: "t".into(), - count: 25, - max: MAX_JOBS - } - ); - assert!(e.to_string().contains("limit is 20")); - let mut text = String::new(); - for i in 0..MAX_JOBS - 1 { - text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n")); - } - text.push_str("[jobs.m]\nimage = \"i\"\nrun = \"x\"\nmatrix = { a = [1, 2] }\n"); - assert!(matches!(err_of(&text), ConfigError::TooManyJobs { .. })); - for bad in [ - "{}", - "{ a = [] }", - "{ a = [\"x\", \"x\"] }", - "{ A = [\"x\"] }", - "{ a = [\"x,y\"] }", - "{ a = [\"x\"], exclude = [{ b = \"1\" }] }", - "{ a = [\"x\"], exclude = [{ a = \"x\" }] }", - "{ a = [\"x\"], include = [{ b = \"1\" }] }", - ] { - let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {bad}\n"); - assert!( - matches!(err_of(&text), ConfigError::InvalidMatrix { .. }), - "{bad}" - ); - } - let text = - "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n"; - assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. })); - let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n"; - assert!(matches!(err_of(text), ConfigError::InvalidJobName(_))); - } - - #[test] - fn shell_variables_are_left_alone() { - let text = "[jobs.t]\nimage = \"i\"\nrun = \"echo ${HOME} ${{ secrets.X }} ${matrix.a}\"\nmatrix = { a = [\"x\"] }\n"; - let cfg = parse_config(text).unwrap(); - assert_eq!(cfg.jobs["t (x)"].run, "echo ${HOME} ${{ secrets.X }} x"); - } - - #[test] - fn release_assets_can_name_a_matrix_job() { - let text = format!( - "[on]\ntags = [\"v*\"]\n[release]\nassets = [\"test:*.tar\"]\n{}", - matrix_toml(GRID, "artifacts = [\"out/a.tar\"]") - ); - let cfg = parse_config(&text).unwrap(); - let release = cfg.release.unwrap(); - assert!(release.asset_matches("test (stable, x86_64)", "a.tar")); - assert!(!release.asset_matches("testing", "a.tar")); - } } diff --git a/crates/forge-ci/src/config/artifact.rs b/crates/forge-ci/src/config/artifact.rs new file mode 100644 index 0000000..131b498 --- /dev/null +++ b/crates/forge-ci/src/config/artifact.rs @@ -0,0 +1,43 @@ +use crate::error::ConfigError; + +use super::trigger::build_glob; + +pub(super) fn validate_artifact(job: &str, pattern: &str) -> Result<(), ConfigError> { + let invalid = |reason: &str| ConfigError::InvalidArtifactGlob { + job: job.to_string(), + pattern: pattern.to_string(), + reason: reason.to_string(), + }; + if pattern.is_empty() { + return Err(invalid("pattern is empty")); + } + if pattern.starts_with('/') || pattern.starts_with('\\') { + return Err(invalid("must be relative")); + } + if pattern.split(['/', '\\']).any(|part| part == "..") { + return Err(invalid("must not contain \"..\"")); + } + build_glob(pattern) + .map(|_| ()) + .map_err(|e| invalid(&e.to_string())) +} + +#[cfg(test)] +mod tests { + use crate::config::parse_config; + use crate::config::tests::{err_of, job_toml}; + use crate::error::ConfigError; + + #[test] + fn artifact_validation() { + for bad in ["/etc/passwd", "..", "a/../b", "\\\\x", "", "a/[b"] { + let text = job_toml(&format!("artifacts = [{bad:?}]")); + assert!( + matches!(err_of(&text), ConfigError::InvalidArtifactGlob { .. }), + "artifact {bad:?} should be rejected" + ); + } + let text = job_toml("artifacts = [\"target/release/*\", \"dist/**/*.tar\"]"); + assert!(parse_config(&text).is_ok()); + } +} diff --git a/crates/forge-ci/src/config/cache.rs b/crates/forge-ci/src/config/cache.rs new file mode 100644 index 0000000..5ae5250 --- /dev/null +++ b/crates/forge-ci/src/config/cache.rs @@ -0,0 +1,147 @@ +use std::collections::BTreeSet; + +use crate::error::ConfigError; + +const MAX_CACHE_ENTRIES: usize = 8; +const MAX_CACHE_PATH_CHARS: usize = 200; + +pub(super) fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> { + if entries.len() > MAX_CACHE_ENTRIES { + return Err(ConfigError::TooManyCacheEntries { + job: job.to_string(), + count: entries.len(), + max: MAX_CACHE_ENTRIES, + }); + } + let mut seen = BTreeSet::new(); + for path in entries { + validate_cache_path(job, path)?; + if !seen.insert(path.as_str()) { + return Err(ConfigError::DuplicateCachePath { + job: job.to_string(), + path: path.clone(), + }); + } + } + Ok(()) +} + +fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { + let invalid = |reason: &str| ConfigError::InvalidCachePath { + job: job.to_string(), + path: path.to_string(), + reason: reason.to_string(), + }; + if path.is_empty() { + return Err(invalid("must not be empty")); + } + if path.chars().count() > MAX_CACHE_PATH_CHARS { + return Err(invalid(&format!( + "must be at most {MAX_CACHE_PATH_CHARS} characters" + ))); + } + if path.starts_with('/') { + return Err(invalid("must be relative")); + } + if path.contains('\\') { + return Err(invalid("must not contain a backslash")); + } + if path.chars().any(|c| "*?[]{}".contains(c)) { + return Err(invalid("must not contain glob characters")); + } + if path.chars().any(char::is_control) { + return Err(invalid("must not contain control characters")); + } + for part in path.split('/') { + match part { + "" => return Err(invalid("must not contain empty components")), + "." | ".." => return Err(invalid("must not contain \".\" or \"..\" components")), + _ if part.eq_ignore_ascii_case(".git") => { + return Err(invalid("must not be inside .git")); + } + _ => {} + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{MAX_CACHE_ENTRIES, MAX_CACHE_PATH_CHARS}; + use crate::config::parse_config; + use crate::config::tests::{err_of, job_toml}; + use crate::error::ConfigError; + + #[test] + fn cache_accepts_relative_directories() { + let text = job_toml("cache = [\"target\", \".cargo-home\", \"a/b/c\"]"); + assert_eq!( + parse_config(&text).unwrap().jobs["build"].cache, + vec![ + "target".to_string(), + ".cargo-home".to_string(), + "a/b/c".to_string() + ] + ); + let at_limit = "x".repeat(MAX_CACHE_PATH_CHARS); + let text = job_toml(&format!("cache = [{at_limit:?}]")); + assert!(parse_config(&text).is_ok()); + } + + #[test] + fn cache_rejects_bad_paths() { + let long = "x".repeat(MAX_CACHE_PATH_CHARS + 1); + let bad = [ + "".to_string(), + "/abs".to_string(), + "a\\b".to_string(), + "..".to_string(), + "a/../b".to_string(), + "./target".to_string(), + ".".to_string(), + "a//b".to_string(), + "target/".to_string(), + ".git".to_string(), + ".git/objects".to_string(), + "sub/.GIT/x".to_string(), + "target/*".to_string(), + "t?rget".to_string(), + "[t]".to_string(), + "{a,b}".to_string(), + long, + ]; + let text = job_toml(r#"cache = ["a\u0007b"]"#); + assert!(matches!( + err_of(&text), + ConfigError::InvalidCachePath { .. } + )); + for path in bad { + let text = job_toml(&format!("cache = [{path:?}]")); + assert!( + matches!(err_of(&text), ConfigError::InvalidCachePath { .. }), + "cache path {path:?} should be rejected" + ); + } + } + + #[test] + fn cache_rejects_duplicates_and_too_many_entries() { + let text = job_toml("cache = [\"target\", \"target\"]"); + assert!(matches!( + err_of(&text), + ConfigError::DuplicateCachePath { .. } + )); + let entries: Vec = (0..=MAX_CACHE_ENTRIES).map(|i| format!("d{i}")).collect(); + let text = job_toml(&format!("cache = {entries:?}")); + assert_eq!( + err_of(&text), + ConfigError::TooManyCacheEntries { + job: "build".into(), + count: MAX_CACHE_ENTRIES + 1, + max: MAX_CACHE_ENTRIES + } + ); + let text = job_toml(&format!("cache = {:?}", &entries[..MAX_CACHE_ENTRIES])); + assert!(parse_config(&text).is_ok()); + } +} diff --git a/crates/forge-ci/src/config/job.rs b/crates/forge-ci/src/config/job.rs new file mode 100644 index 0000000..3e9d1a6 --- /dev/null +++ b/crates/forge-ci/src/config/job.rs @@ -0,0 +1,228 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::error::ConfigError; + +use super::DEFAULT_TIMEOUT_MINUTES; +use super::artifact::validate_artifact; +use super::cache::validate_cache; +use super::matrix::MatrixSpec; +use super::memory::{MEMORY_RANGE_BYTES, deserialize_memory}; + +const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive = 1..=360; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct JobSpec { + pub image: String, + pub run: String, + #[serde(default)] + pub needs: Vec, + #[serde(default)] + pub secrets: Vec, + #[serde(default)] + pub env: BTreeMap, + #[serde(default)] + pub artifacts: Vec, + #[serde(default)] + pub runs_on: Vec, + #[serde(default)] + pub cache: Vec, + #[serde(default = "default_timeout_minutes")] + pub timeout_minutes: u32, + #[serde(default = "default_network")] + pub network: bool, + #[serde( + default, + deserialize_with = "deserialize_memory", + skip_serializing_if = "Option::is_none" + )] + pub memory: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub matrix: Option, +} + +fn default_timeout_minutes() -> u32 { + DEFAULT_TIMEOUT_MINUTES +} + +fn default_network() -> bool { + true +} + +pub(super) fn is_job_name(name: &str) -> bool { + let Some((first, rest)) = name.as_bytes().split_first() else { + return false; + }; + rest.len() <= 39 + && (first.is_ascii_lowercase() || first.is_ascii_digit()) + && rest + .iter() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-') +} + +fn is_env_name(name: &str) -> bool { + let Some((first, rest)) = name.as_bytes().split_first() else { + return false; + }; + rest.len() <= 63 + && (first.is_ascii_uppercase() || *first == b'_') + && rest + .iter() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || *b == b'_') +} + +fn is_runner_label(label: &str) -> bool { + (1..=64).contains(&label.len()) + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') +} + +pub(super) fn validate_job( + name: &str, + job: &JobSpec, + all: &BTreeMap, +) -> Result<(), ConfigError> { + if job.image.is_empty() || job.image.chars().any(char::is_whitespace) { + return Err(ConfigError::InvalidImage { + job: name.to_string(), + }); + } + if job.run.trim().is_empty() { + return Err(ConfigError::EmptyRun { + job: name.to_string(), + }); + } + for need in &job.needs { + if !all.contains_key(need) { + return Err(ConfigError::UnknownNeed { + job: name.to_string(), + need: need.clone(), + }); + } + } + for secret in &job.secrets { + if !is_env_name(secret) { + return Err(ConfigError::InvalidSecretName { + job: name.to_string(), + name: secret.clone(), + }); + } + } + for key in job.env.keys() { + if !is_env_name(key) { + return Err(ConfigError::InvalidEnvName { + job: name.to_string(), + name: key.clone(), + }); + } + } + for pattern in &job.artifacts { + validate_artifact(name, pattern)?; + } + for label in &job.runs_on { + if !is_runner_label(label) { + return Err(ConfigError::InvalidRunsOn { + job: name.to_string(), + label: label.clone(), + }); + } + } + validate_cache(name, &job.cache)?; + if !TIMEOUT_RANGE_MINUTES.contains(&job.timeout_minutes) { + return Err(ConfigError::InvalidTimeout { + job: name.to_string(), + value: job.timeout_minutes, + }); + } + if let Some(memory) = job.memory + && !MEMORY_RANGE_BYTES.contains(&memory) + { + return Err(ConfigError::InvalidMemory { + job: name.to_string(), + value: crate::size::format_size(memory), + }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use crate::config::parse_config; + use crate::config::tests::{err_of, job_toml}; + use crate::error::ConfigError; + + #[test] + fn image_and_run_validation() { + let cases = [ + ("image", "[jobs.b]\nimage = \"\"\nrun = \"r\"\n"), + ("image", "[jobs.b]\nimage = \"a b\"\nrun = \"r\"\n"), + ("run", "[jobs.b]\nimage = \"i\"\nrun = \" \\n \"\n"), + ]; + for (want, text) in cases { + let got = match err_of(text) { + ConfigError::InvalidImage { .. } => "image", + ConfigError::EmptyRun { .. } => "run", + other => panic!("case {text:?}: unexpected error {other:?}"), + }; + assert_eq!(got, want, "case {text:?}"); + } + } + + #[test] + fn secret_and_env_names() { + let long = "A".repeat(65); + for bad in ["deploy", "1KEY", "A-B", "", long.as_str()] { + let text = job_toml(&format!("secrets = [{bad:?}]")); + assert!( + matches!(err_of(&text), ConfigError::InvalidSecretName { .. }), + "secret {bad:?} should be rejected" + ); + } + let text = job_toml("secrets = [\"_OK_1\"]"); + assert!(parse_config(&text).is_ok()); + let text = job_toml("[jobs.build.env]\n\"lower\" = \"x\""); + assert!(matches!(err_of(&text), ConfigError::InvalidEnvName { .. })); + let text = job_toml("[jobs.build.env]\nRUST_LOG = \"info\""); + assert!(parse_config(&text).is_ok()); + } + + #[test] + fn runs_on_validation() { + let text = job_toml("runs_on = [\"linux\", \"x86_64\"]"); + assert_eq!( + parse_config(&text).unwrap().jobs["build"].runs_on, + vec!["linux".to_string(), "x86_64".to_string()] + ); + let text = job_toml("runs_on = [\"has space\"]"); + assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); + let text = job_toml("runs_on = [\"\"]"); + assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); + } + + #[test] + fn timeout_validation() { + assert_eq!( + parse_config(&job_toml("timeout_minutes = 1")).unwrap().jobs["build"].timeout_minutes, + 1 + ); + assert_eq!( + parse_config(&job_toml("timeout_minutes = 360")) + .unwrap() + .jobs["build"] + .timeout_minutes, + 360 + ); + for bad in [0, 361] { + let text = job_toml(&format!("timeout_minutes = {bad}")); + assert_eq!( + err_of(&text), + ConfigError::InvalidTimeout { + job: "build".into(), + value: bad + } + ); + } + } +} diff --git a/crates/forge-ci/src/config/matrix.rs b/crates/forge-ci/src/config/matrix.rs new file mode 100644 index 0000000..21774f3 --- /dev/null +++ b/crates/forge-ci/src/config/matrix.rs @@ -0,0 +1,355 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::error::ConfigError; + +use super::MAX_JOBS; + +const MAX_MATRIX_VALUE_CHARS: usize = 64; + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct MatrixValue(pub String); + +impl Serialize for MatrixValue { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.0) + } +} + +impl<'de> Deserialize<'de> for MatrixValue { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Text(String), + Int(i64), + Flag(bool), + } + Ok(MatrixValue(match Raw::deserialize(deserializer)? { + Raw::Text(text) => text, + Raw::Int(n) => n.to_string(), + Raw::Flag(b) => b.to_string(), + })) + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MatrixSpec { + #[serde(default)] + pub exclude: Vec>, + #[serde(default)] + pub include: Vec>, + #[serde(flatten)] + pub axes: BTreeMap>, +} + +fn is_matrix_key(key: &str) -> bool { + let Some((first, rest)) = key.as_bytes().split_first() else { + return false; + }; + rest.len() <= 31 + && first.is_ascii_lowercase() + && rest + .iter() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_') +} + +type Combination = (String, BTreeMap); + +pub(super) fn combinations( + job: &str, + matrix: &MatrixSpec, +) -> Result, ConfigError> { + let bad = |reason: String| ConfigError::InvalidMatrix { + job: job.to_string(), + reason, + }; + if matrix.axes.is_empty() { + return Err(bad( + "needs at least one axis, e.g. rust = [\"stable\"]".into() + )); + } + let mut total: usize = 1; + for (key, values) in &matrix.axes { + if !is_matrix_key(key) { + return Err(bad(format!( + "axis name {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" + ))); + } + if values.is_empty() { + return Err(bad(format!("axis {key:?} has no values"))); + } + for (i, value) in values.iter().enumerate() { + validate_matrix_value(&value.0).map_err(|r| bad(format!("axis {key:?}: {r}")))?; + if values[..i].contains(value) { + return Err(bad(format!("axis {key:?} lists {:?} twice", value.0))); + } + } + total = total.saturating_mul(values.len()); + if total > MAX_JOBS { + return Err(ConfigError::MatrixTooLarge { + job: job.to_string(), + count: total, + max: MAX_JOBS, + }); + } + } + let mut combos: Vec> = vec![BTreeMap::new()]; + for (key, values) in &matrix.axes { + combos = combos + .into_iter() + .flat_map(|base| { + values.iter().map(move |value| { + let mut next = base.clone(); + next.insert(key.clone(), value.0.clone()); + next + }) + }) + .collect(); + } + for entry in &matrix.exclude { + for key in entry.keys() { + if !matrix.axes.contains_key(key) { + return Err(bad(format!("exclude names {key:?}, which is not an axis"))); + } + } + combos.retain(|combo| !entry.iter().all(|(k, v)| combo.get(k) == Some(&v.0))); + } + for entry in &matrix.include { + let mut combo = BTreeMap::new(); + for (key, value) in entry { + if !is_matrix_key(key) { + return Err(bad(format!( + "include key {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" + ))); + } + validate_matrix_value(&value.0).map_err(|r| bad(format!("include {key:?}: {r}")))?; + combo.insert(key.clone(), value.0.clone()); + } + if let Some(missing) = matrix.axes.keys().find(|k| !combo.contains_key(*k)) { + return Err(bad(format!("an include entry must set axis {missing:?}"))); + } + let same_axes = |other: &BTreeMap| { + matrix.axes.keys().all(|k| other.get(k) == combo.get(k)) + }; + if !combos.iter().any(same_axes) { + combos.push(combo); + } + } + if combos.is_empty() { + return Err(bad("exclude removes every combination".into())); + } + if combos.len() > MAX_JOBS { + return Err(ConfigError::MatrixTooLarge { + job: job.to_string(), + count: combos.len(), + max: MAX_JOBS, + }); + } + Ok(combos + .into_iter() + .map(|combo| { + let suffix = matrix + .axes + .keys() + .filter_map(|k| combo.get(k).map(String::as_str)) + .collect::>() + .join(", "); + (suffix, combo) + }) + .collect()) +} + +fn validate_matrix_value(value: &str) -> Result<(), String> { + if value.is_empty() { + return Err("values must not be empty".into()); + } + if value.chars().count() > MAX_MATRIX_VALUE_CHARS { + return Err(format!( + "values must be at most {MAX_MATRIX_VALUE_CHARS} characters" + )); + } + if value + .chars() + .any(|c| c.is_control() || matches!(c, ',' | '(' | ')')) + { + return Err(format!( + "{value:?} must not contain control characters, commas or parentheses" + )); + } + Ok(()) +} + +pub(super) fn interpolate( + job: &str, + text: &str, + vars: &BTreeMap, +) -> Result { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(at) = rest.find("${") { + out.push_str(&rest[..at]); + let after = &rest[at + 2..]; + let found = if let Some(body) = after.strip_prefix('{') { + body.find("}}") + .map(|end| (body[..end].trim(), &body[end + 2..])) + } else { + after + .find('}') + .map(|end| (after[..end].trim(), &after[end + 1..])) + }; + match found.and_then(|(inner, tail)| Some((inner.strip_prefix("matrix.")?, tail))) { + Some((key, tail)) => { + let value = vars.get(key).ok_or_else(|| ConfigError::InvalidMatrix { + job: job.to_string(), + reason: format!("`matrix.{key}` is not an axis or include key"), + })?; + out.push_str(value); + rest = tail; + } + None => { + out.push_str("${"); + rest = after; + } + } + } + out.push_str(rest); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::parse_config; + use crate::config::tests::err_of; + + fn matrix_toml(matrix: &str, extra: &str) -> String { + format!( + "[jobs.test]\nimage = \"rust:${{{{ matrix.rust }}}}\"\nrun = \"cargo +${{matrix.rust}} test --target $MATRIX_TARGET\"\nruns_on = [\"${{{{ matrix.target }}}}\"]\nmatrix = {matrix}\n{extra}\n" + ) + } + + const GRID: &str = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"] }"#; + + #[test] + fn a_matrix_expands_into_named_jobs() { + let cfg = parse_config(&matrix_toml(GRID, "")).unwrap(); + let names: Vec<&str> = cfg.jobs.keys().map(String::as_str).collect(); + assert_eq!( + names, + [ + "test (1.85, aarch64)", + "test (1.85, x86_64)", + "test (stable, aarch64)", + "test (stable, x86_64)" + ] + ); + let job = &cfg.jobs["test (stable, x86_64)"]; + assert_eq!(job.image, "rust:stable"); + assert_eq!(job.run, "cargo +stable test --target $MATRIX_TARGET"); + assert_eq!(job.runs_on, vec!["x86_64".to_string()]); + assert_eq!(job.env["MATRIX_RUST"], "stable"); + assert_eq!(job.env["MATRIX_TARGET"], "x86_64"); + assert!(job.matrix.is_none()); + } + + #[test] + fn matrix_exclude_and_include() { + let m = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"], exclude = [{ rust = "1.85", target = "aarch64" }], include = [{ rust = "nightly", target = "x86_64", flag = "-Z" }] }"#; + let cfg = parse_config(&matrix_toml(m, "")).unwrap(); + assert_eq!(cfg.jobs.len(), 4); + assert!(!cfg.jobs.contains_key("test (1.85, aarch64)")); + let extra = &cfg.jobs["test (nightly, x86_64)"]; + assert_eq!(extra.env["MATRIX_FLAG"], "-Z"); + let m = + r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#; + let cfg = parse_config(&matrix_toml(m, "")).unwrap(); + assert_eq!( + cfg.jobs.keys().collect::>(), + ["test (stable, x86_64)"] + ); + let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#; + assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1); + } + + #[test] + fn needs_on_a_matrix_job_waits_for_every_combination() { + let text = format!( + "{}\n[jobs.ship]\nimage = \"img\"\nrun = \"true\"\nneeds = [\"test\"]\n", + matrix_toml(GRID, "") + ); + let cfg = parse_config(&text).unwrap(); + assert_eq!(cfg.jobs["ship"].needs.len(), 4); + let order = cfg.job_order(); + assert_eq!(order.last(), Some(&"ship")); + let text = format!( + "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}", + matrix_toml(GRID, "needs = [\"setup\"]") + ); + let cfg = parse_config(&text).unwrap(); + assert_eq!(cfg.jobs["test (stable, x86_64)"].needs, ["setup"]); + } + + #[test] + fn matrix_errors_are_clear() { + let big = r#"{ a = [1,2,3,4,5], b = [1,2,3,4,5] }"#; + let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {big}\n"); + let e = err_of(&text); + assert_eq!( + e, + ConfigError::MatrixTooLarge { + job: "t".into(), + count: 25, + max: MAX_JOBS + } + ); + assert!(e.to_string().contains("limit is 20")); + let mut text = String::new(); + for i in 0..MAX_JOBS - 1 { + text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n")); + } + text.push_str("[jobs.m]\nimage = \"i\"\nrun = \"x\"\nmatrix = { a = [1, 2] }\n"); + assert!(matches!(err_of(&text), ConfigError::TooManyJobs { .. })); + for bad in [ + "{}", + "{ a = [] }", + "{ a = [\"x\", \"x\"] }", + "{ A = [\"x\"] }", + "{ a = [\"x,y\"] }", + "{ a = [\"x\"], exclude = [{ b = \"1\" }] }", + "{ a = [\"x\"], exclude = [{ a = \"x\" }] }", + "{ a = [\"x\"], include = [{ b = \"1\" }] }", + ] { + let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {bad}\n"); + assert!( + matches!(err_of(&text), ConfigError::InvalidMatrix { .. }), + "{bad}" + ); + } + let text = + "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n"; + assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. })); + let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n"; + assert!(matches!(err_of(text), ConfigError::InvalidJobName(_))); + } + + #[test] + fn shell_variables_are_left_alone() { + let text = "[jobs.t]\nimage = \"i\"\nrun = \"echo ${HOME} ${{ secrets.X }} ${matrix.a}\"\nmatrix = { a = [\"x\"] }\n"; + let cfg = parse_config(text).unwrap(); + assert_eq!(cfg.jobs["t (x)"].run, "echo ${HOME} ${{ secrets.X }} x"); + } + + #[test] + fn release_assets_can_name_a_matrix_job() { + let text = format!( + "[on]\ntags = [\"v*\"]\n[release]\nassets = [\"test:*.tar\"]\n{}", + matrix_toml(GRID, "artifacts = [\"out/a.tar\"]") + ); + let cfg = parse_config(&text).unwrap(); + let release = cfg.release.unwrap(); + assert!(release.asset_matches("test (stable, x86_64)", "a.tar")); + assert!(!release.asset_matches("testing", "a.tar")); + } +} diff --git a/crates/forge-ci/src/config/memory.rs b/crates/forge-ci/src/config/memory.rs new file mode 100644 index 0000000..7d3dec8 --- /dev/null +++ b/crates/forge-ci/src/config/memory.rs @@ -0,0 +1,69 @@ +use serde::{Deserialize, Deserializer}; + +pub(super) const MEMORY_RANGE_BYTES: std::ops::RangeInclusive = (64 << 20)..=(1024 << 30); + +pub(super) fn deserialize_memory<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Bytes(u64), + Text(String), + } + match Option::::deserialize(d)? { + None => Ok(None), + Some(Raw::Bytes(n)) => Ok(Some(n)), + Some(Raw::Text(text)) => crate::size::parse_size(&text).map(Some).ok_or_else(|| { + serde::de::Error::custom(format!( + "memory must be a size such as 4g or 512m, got {text:?}" + )) + }), + } +} + +#[cfg(test)] +mod tests { + use crate::config::tests::{err_of, job_toml}; + use crate::config::{JobSpec, parse_config}; + use crate::error::ConfigError; + + #[test] + fn memory_is_parsed_to_bytes() { + let cfg = parse_config(&job_toml("memory = \"4g\"")).unwrap(); + assert_eq!(cfg.jobs["build"].memory, Some(4 << 30)); + let cfg = parse_config(&job_toml("memory = \"512M\"")).unwrap(); + assert_eq!(cfg.jobs["build"].memory, Some(512 << 20)); + assert_eq!( + parse_config(&job_toml("")).unwrap().jobs["build"].memory, + None + ); + let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"]; + let json = serde_json::to_string(job).unwrap(); + assert!(json.contains("\"memory\":4294967296"), "{json}"); + let back: JobSpec = serde_json::from_str(&json).unwrap(); + assert_eq!(back.memory, Some(4 << 30)); + let old = json.replace(",\"memory\":4294967296", ""); + assert_eq!(serde_json::from_str::(&old).unwrap().memory, None); + } + + #[test] + fn bad_memory_is_an_error() { + for bad in ["\"lots\"", "\"0\"", "\"-1g\"", "true"] { + assert!( + matches!( + err_of(&job_toml(&format!("memory = {bad}"))), + ConfigError::Toml(_) + ), + "{bad}" + ); + } + for bad in ["\"1m\"", "\"2t\""] { + assert!( + matches!( + err_of(&job_toml(&format!("memory = {bad}"))), + ConfigError::InvalidMemory { .. } + ), + "{bad}" + ); + } + } +} diff --git a/crates/forge-ci/src/config/release.rs b/crates/forge-ci/src/config/release.rs new file mode 100644 index 0000000..3dde62c --- /dev/null +++ b/crates/forge-ci/src/config/release.rs @@ -0,0 +1,369 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::error::ConfigError; + +use super::trigger::{build_glob, matches_any}; +use super::{JobSpec, Triggers, names_job}; + +const MAX_RELEASE_ASSETS: usize = 32; +const MAX_RELEASE_TITLE_CHARS: usize = 200; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ReleaseSpec { + pub assets: Vec, + pub prerelease: Prerelease, + pub draft: bool, + pub notes: ReleaseNotes, + pub title: String, +} + +impl Default for ReleaseSpec { + fn default() -> Self { + Self { + assets: Vec::new(), + prerelease: Prerelease::Auto, + draft: false, + notes: ReleaseNotes::Commits, + title: "{tag}".to_string(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Prerelease { + Auto, + Always, + Never, +} + +impl Serialize for Prerelease { + fn serialize(&self, serializer: S) -> Result { + match self { + Prerelease::Auto => serializer.serialize_str("auto"), + Prerelease::Always => serializer.serialize_bool(true), + Prerelease::Never => serializer.serialize_bool(false), + } + } +} + +impl<'de> Deserialize<'de> for Prerelease { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Flag(bool), + Text(String), + } + match Raw::deserialize(deserializer)? { + Raw::Flag(true) => Ok(Prerelease::Always), + Raw::Flag(false) => Ok(Prerelease::Never), + Raw::Text(text) if text == "auto" => Ok(Prerelease::Auto), + Raw::Text(text) => Err(serde::de::Error::custom(format!( + "prerelease must be \"auto\", true or false, got {text:?}" + ))), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ReleaseNotes { + Commits, + #[serde(rename = "none")] + Off, +} + +impl ReleaseSpec { + pub fn is_prerelease(&self, tag: &str) -> bool { + match self.prerelease { + Prerelease::Auto => tag.contains('-'), + Prerelease::Always => true, + Prerelease::Never => false, + } + } + + pub fn title_for(&self, tag: &str) -> String { + self.title.trim().replace("{tag}", tag) + } + + pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { + self.assets.iter().any(|asset| { + asset_selector(asset).is_some_and(|(selected_job, glob)| { + names_job(selected_job, job) && matches_any(&[glob.to_string()], artifact_name) + }) + }) + } +} + +fn asset_selector(asset: &str) -> Option<(&str, &str)> { + asset.split_once(':') +} + +pub(super) fn validate_release( + release: &ReleaseSpec, + on: &Triggers, + jobs: &BTreeMap, +) -> Result<(), ConfigError> { + if on.tags.is_empty() { + return Err(ConfigError::ReleaseWithoutTags); + } + if release.assets.len() > MAX_RELEASE_ASSETS { + return Err(ConfigError::TooManyReleaseAssets { + count: release.assets.len(), + max: MAX_RELEASE_ASSETS, + }); + } + for asset in &release.assets { + validate_release_asset(asset, jobs)?; + } + validate_release_title(&release.title) +} + +fn validate_release_asset( + asset: &str, + jobs: &BTreeMap, +) -> Result<(), ConfigError> { + let invalid = |reason: String| ConfigError::InvalidReleaseAsset { + asset: asset.to_string(), + reason, + }; + let Some((job, glob)) = asset_selector(asset) else { + return Err(invalid("must be \"job:glob\"".into())); + }; + let Some((_, spec)) = jobs.iter().find(|(name, _)| names_job(job, name)) else { + return Err(invalid(format!("job {job:?} is not defined"))); + }; + if spec.artifacts.is_empty() { + return Err(invalid(format!("job {job:?} declares no artifacts"))); + } + if glob.is_empty() { + return Err(invalid("glob must not be empty".into())); + } + if glob.contains('/') { + return Err(invalid( + "glob must not contain \"/\", artifact names are flattened".into(), + )); + } + build_glob(glob) + .map(|_| ()) + .map_err(|e| invalid(e.to_string())) +} + +fn validate_release_title(title: &str) -> Result<(), ConfigError> { + let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason); + if title.trim().is_empty() { + return Err(invalid("must not be empty".into())); + } + if title.trim().chars().count() > MAX_RELEASE_TITLE_CHARS { + return Err(invalid(format!( + "must be at most {MAX_RELEASE_TITLE_CHARS} characters" + ))); + } + if title.chars().any(char::is_control) { + return Err(invalid("must not contain control characters".into())); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::tests::{err_of, job_toml}; + use crate::config::{Event, parse_config}; + + fn release_toml(release: &str) -> String { + format!( + "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n", + job_toml("artifacts = [\"dist/*\"]") + ) + } + + fn release_of(text: &str) -> ReleaseSpec { + parse_config(text).unwrap().release.expect("release set") + } + + #[test] + fn release_defaults_apply() { + let release = release_of(&release_toml("")); + assert!(release.assets.is_empty()); + assert_eq!(release.prerelease, Prerelease::Auto); + assert!(!release.draft); + assert_eq!(release.notes, ReleaseNotes::Commits); + assert_eq!(release.title, "{tag}"); + assert_eq!(release, ReleaseSpec::default()); + } + + #[test] + fn release_full_table_parses() { + let text = release_toml( + "assets = [\"build:dist_*\", \"build:SHA256SUMS\"]\n\ + prerelease = true\ndraft = true\nnotes = \"none\"\ntitle = \"Release {tag}\"", + ); + let release = release_of(&text); + assert_eq!( + release.assets, + vec!["build:dist_*".to_string(), "build:SHA256SUMS".to_string()] + ); + assert_eq!(release.prerelease, Prerelease::Always); + assert!(release.draft); + assert_eq!(release.notes, ReleaseNotes::Off); + assert_eq!(release.title, "Release {tag}"); + } + + #[test] + fn release_prerelease_and_notes_values() { + assert_eq!( + release_of(&release_toml("prerelease = \"auto\"")).prerelease, + Prerelease::Auto + ); + assert_eq!( + release_of(&release_toml("prerelease = false")).prerelease, + Prerelease::Never + ); + assert_eq!( + release_of(&release_toml("notes = \"commits\"")).notes, + ReleaseNotes::Commits + ); + for bad in ["prerelease = \"yes\"", "notes = \"all\""] { + assert!( + matches!(err_of(&release_toml(bad)), ConfigError::Toml(_)), + "{bad}" + ); + } + } + + #[test] + fn release_unknown_keys_are_ignored_with_a_warning() { + let cfg = parse_config(&release_toml("bogus = 1")).unwrap(); + assert_eq!(cfg.warnings.len(), 1); + assert!( + cfg.warnings[0].contains("`release.bogus`"), + "{:?}", + cfg.warnings + ); + assert!(cfg.release.is_some()); + } + + #[test] + fn release_requires_tags() { + let text = format!("[release]\n{}", job_toml("artifacts = [\"dist/*\"]")); + assert_eq!(err_of(&text), ConfigError::ReleaseWithoutTags); + } + + #[test] + fn release_asset_must_be_job_and_glob() { + for bad in ["build", ":dist_*", "build:", "ghost:dist_*", "build:a/b"] { + let text = release_toml(&format!("assets = [{bad:?}]")); + assert!( + matches!(err_of(&text), ConfigError::InvalidReleaseAsset { .. }), + "asset {bad:?} should be rejected: {:?}", + err_of(&text) + ); + } + let text = release_toml("assets = [\"build:[\"]"); + assert!(matches!( + err_of(&text), + ConfigError::InvalidReleaseAsset { .. } + )); + } + + #[test] + fn release_asset_job_must_declare_artifacts() { + let text = format!( + "[on]\ntags = [\"v*\"]\n{}\n[release]\nassets = [\"build:x\"]\n", + job_toml("") + ); + match err_of(&text) { + ConfigError::InvalidReleaseAsset { asset, reason } => { + assert_eq!(asset, "build:x"); + assert!(reason.contains("no artifacts"), "{reason}"); + } + other => panic!("unexpected error {other:?}"), + } + } + + #[test] + fn release_assets_are_capped() { + let entries: Vec = (0..=MAX_RELEASE_ASSETS) + .map(|_| "build:dist_*".to_string()) + .collect(); + let text = release_toml(&format!("assets = {entries:?}")); + assert_eq!( + err_of(&text), + ConfigError::TooManyReleaseAssets { + count: MAX_RELEASE_ASSETS + 1, + max: MAX_RELEASE_ASSETS + } + ); + let text = release_toml(&format!("assets = {:?}", &entries[..MAX_RELEASE_ASSETS])); + assert!(parse_config(&text).is_ok()); + } + + #[test] + fn release_title_validation() { + for bad in ["", " ", "a\\u0007b"] { + let text = release_toml(&format!("title = \"{bad}\"")); + assert!( + matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_)), + "title {bad:?} should be rejected" + ); + } + let over = "t".repeat(MAX_RELEASE_TITLE_CHARS + 1); + let text = release_toml(&format!("title = \"{over}\"")); + assert!(matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_))); + let at_limit = "t".repeat(MAX_RELEASE_TITLE_CHARS); + assert!(parse_config(&release_toml(&format!("title = \"{at_limit}\""))).is_ok()); + } + + #[test] + fn release_title_for_fills_tag() { + assert_eq!(ReleaseSpec::default().title_for("v1.2.0"), "v1.2.0"); + let release = release_of(&release_toml("title = \"Release {tag}\"")); + assert_eq!(release.title_for("v1.2.0"), "Release v1.2.0"); + let fixed = release_of(&release_toml("title = \"Stable\"")); + assert_eq!(fixed.title_for("v1.2.0"), "Stable"); + } + + #[test] + fn release_prerelease_auto_logic() { + let auto = ReleaseSpec::default(); + assert!(auto.is_prerelease("v1.2.0-rc1")); + assert!(auto.is_prerelease("v2.0.0-beta.3")); + assert!(!auto.is_prerelease("v1.2.0")); + let always = release_of(&release_toml("prerelease = true")); + assert!(always.is_prerelease("v1.2.0")); + let never = release_of(&release_toml("prerelease = false")); + assert!(!never.is_prerelease("v1.2.0-rc1")); + } + + #[test] + fn release_asset_matching() { + let release = release_of(&release_toml( + "assets = [\"build:forge-*-linux-*\", \"build:SHA256SUMS\"]", + )); + assert!(release.asset_matches("build", "forge-1.2.0-linux-x86_64")); + assert!(release.asset_matches("build", "SHA256SUMS")); + assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64")); + assert!(!release.asset_matches("build", "SHA256SUMS.sig")); + assert!(!release.asset_matches("lint", "SHA256SUMS")); + assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS")); + } + + #[test] + fn wants_release_only_for_matching_tags() { + let text = release_toml(""); + let cfg = parse_config(&text).unwrap(); + assert!(cfg.wants_release(&Event::Tag { tag: "v1.2.0" })); + assert!(!cfg.wants_release(&Event::Tag { tag: "release-1" })); + assert!(!cfg.wants_release(&Event::Push { branch: "main" })); + assert!(!cfg.wants_release(&Event::Manual)); + assert!(!cfg.wants_release(&Event::PullRequest)); + + let without = parse_config(&format!("[on]\ntags = [\"v*\"]\n{}", job_toml(""))).unwrap(); + assert!(without.release.is_none()); + assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); + } +} diff --git a/crates/forge-ci/src/config/schedule.rs b/crates/forge-ci/src/config/schedule.rs new file mode 100644 index 0000000..ef3cfa0 --- /dev/null +++ b/crates/forge-ci/src/config/schedule.rs @@ -0,0 +1,55 @@ +use crate::error::ConfigError; + +const MAX_SCHEDULES: usize = 8; + +pub(super) fn validate_schedules(exprs: &[String]) -> Result<(), ConfigError> { + if exprs.len() > MAX_SCHEDULES { + return Err(ConfigError::TooManySchedules { + count: exprs.len(), + max: MAX_SCHEDULES, + }); + } + for expr in exprs { + crate::cron::parse(expr).map_err(|reason| ConfigError::InvalidSchedule { + expr: expr.clone(), + reason, + })?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::MAX_SCHEDULES; + use crate::config::Event; + use crate::config::parse_config; + use crate::config::tests::{err_of, job_toml}; + use crate::error::ConfigError; + + #[test] + fn schedule_is_parsed_and_validated() { + let cfg = parse_config(&format!( + "[on]\nschedule = [\"0 3 * * *\", \"*/15 * * * 1\"]\n{}", + job_toml("") + )) + .unwrap(); + assert_eq!(cfg.on.schedule.len(), 2); + assert!(cfg.warnings.is_empty()); + assert!(cfg.triggered_by(&Event::Schedule)); + let none = parse_config(&job_toml("")).unwrap(); + assert!(!none.triggered_by(&Event::Schedule)); + for bad in ["0 0 3 * * *", "nope", "70 3 * * *", ""] { + let text = format!("[on]\nschedule = [\"{bad}\"]\n{}", job_toml("")); + assert!( + matches!(err_of(&text), ConfigError::InvalidSchedule { .. }), + "{bad}" + ); + } + let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", "); + let text = format!("[on]\nschedule = [{many}]\n{}", job_toml("")); + assert!(matches!( + err_of(&text), + ConfigError::TooManySchedules { .. } + )); + } +} diff --git a/crates/forge-ci/src/config/trigger.rs b/crates/forge-ci/src/config/trigger.rs new file mode 100644 index 0000000..13008d0 --- /dev/null +++ b/crates/forge-ci/src/config/trigger.rs @@ -0,0 +1,97 @@ +use globset::{Glob, GlobBuilder}; +use serde::{Deserialize, Serialize}; + +use crate::error::ConfigError; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Triggers { + pub push: Vec, + pub tags: Vec, + pub pull_request: bool, + pub manual: bool, + pub cancel_superseded: bool, + pub merge_queue: bool, + pub schedule: Vec, +} + +impl Default for Triggers { + fn default() -> Self { + Self { + push: Vec::new(), + tags: Vec::new(), + pull_request: false, + manual: true, + cancel_superseded: true, + merge_queue: false, + schedule: Vec::new(), + } + } +} + +pub(super) fn matches_any(globs: &[String], value: &str) -> bool { + globs + .iter() + .any(|pattern| build_glob(pattern).is_ok_and(|g| g.compile_matcher().is_match(value))) +} + +pub(super) fn build_glob(pattern: &str) -> Result { + GlobBuilder::new(pattern).literal_separator(true).build() +} + +pub(super) fn validate_trigger_glob(kind: &'static str, pattern: &str) -> Result<(), ConfigError> { + let invalid = |reason: String| ConfigError::InvalidTriggerGlob { + kind, + pattern: pattern.to_string(), + reason, + }; + if pattern.is_empty() { + return Err(invalid("pattern is empty".into())); + } + build_glob(pattern) + .map(|_| ()) + .map_err(|e| invalid(e.to_string())) +} + +#[cfg(test)] +mod tests { + use crate::config::tests::{err_of, job_toml}; + use crate::config::{Event, parse_config}; + use crate::error::ConfigError; + + #[test] + fn branch_and_tag_globs_match_only_their_event_kind() { + let text = format!("[on]\npush = [\"main\", \"release/*\"]\n{}", job_toml("")); + let cfg = parse_config(&text).unwrap(); + assert!(cfg.triggered_by(&Event::Push { branch: "main" })); + assert!(cfg.triggered_by(&Event::Push { + branch: "release/1.0" + })); + assert!(!cfg.triggered_by(&Event::Push { + branch: "release/1.0/x" + })); + assert!(!cfg.triggered_by(&Event::Push { branch: "mainx" })); + assert!(!cfg.triggered_by(&Event::Push { branch: "feature" })); + assert!(!cfg.triggered_by(&Event::Tag { tag: "v1" })); + + let text = format!("[on]\ntags = [\"v*\"]\n{}", job_toml("")); + let cfg = parse_config(&text).unwrap(); + assert!(cfg.triggered_by(&Event::Tag { tag: "v1.2.3" })); + assert!(!cfg.triggered_by(&Event::Tag { tag: "release-1" })); + assert!(!cfg.triggered_by(&Event::Push { branch: "v1" })); + } + + #[test] + fn invalid_trigger_globs_are_rejected() { + let text = format!("[on]\npush = [\"[\"]\n{}", job_toml("")); + assert!(matches!( + err_of(&text), + ConfigError::InvalidTriggerGlob { kind: "branch", .. } + )); + let text = format!("[on]\ntags = [\"\"]\n{}", job_toml("")); + assert!(matches!( + err_of(&text), + ConfigError::InvalidTriggerGlob { kind: "tag", .. } + )); + } +} diff --git a/crates/forge-ci/src/config/workflow.rs b/crates/forge-ci/src/config/workflow.rs new file mode 100644 index 0000000..9b739ad --- /dev/null +++ b/crates/forge-ci/src/config/workflow.rs @@ -0,0 +1,72 @@ +use crate::error::ConfigError; + +const MAX_WORKFLOW_NAME_CHARS: usize = 40; + +pub(super) fn validate_workflow_name(name: &str) -> Result<(), ConfigError> { + let invalid = |reason: &str| ConfigError::InvalidWorkflowName { + name: name.to_string(), + reason: reason.to_string(), + }; + let trimmed = name.trim(); + if trimmed.is_empty() { + return Err(invalid("must not be empty")); + } + if trimmed.chars().count() > MAX_WORKFLOW_NAME_CHARS { + return Err(invalid(&format!( + "must be at most {MAX_WORKFLOW_NAME_CHARS} characters" + ))); + } + if trimmed.chars().any(char::is_control) { + return Err(invalid("must not contain control characters")); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::MAX_WORKFLOW_NAME_CHARS; + use crate::config::parse_config; + use crate::config::tests::{err_of, job_toml}; + use crate::error::ConfigError; + + #[test] + fn workflow_name_is_optional_and_kept() { + assert_eq!(parse_config(&job_toml("")).unwrap().name, None); + let cfg = parse_config(&format!("name = \"build\"\n{}", job_toml(""))).unwrap(); + assert_eq!(cfg.name.as_deref(), Some("build")); + } + + #[test] + fn workflow_name_must_be_one_non_blank_line() { + for text in [ + "name = \"\"", + "name = \" \"", + "name = \"a\\u0007b\"", + "name = \"a\\nb\"", + ] { + let err = err_of(&format!("{text}\n{}", job_toml(""))); + assert!( + matches!(err, ConfigError::InvalidWorkflowName { .. }), + "{text}: {err:?}" + ); + } + } + + #[test] + fn workflow_name_length_is_capped_after_trimming() { + let at_limit = "n".repeat(MAX_WORKFLOW_NAME_CHARS); + let ok = format!("name = \" {at_limit} \"\n{}", job_toml("")); + assert!(parse_config(&ok).is_ok()); + let over = "n".repeat(MAX_WORKFLOW_NAME_CHARS + 1); + let err = err_of(&format!("name = \"{over}\"\n{}", job_toml(""))); + assert!(matches!(err, ConfigError::InvalidWorkflowName { .. })); + } + + #[test] + fn workflow_name_must_be_a_string() { + assert!(matches!( + err_of(&format!("name = 3\n{}", job_toml(""))), + ConfigError::Toml(_) + )); + } +} diff --git a/crates/forge-core/migrations/0075_runner_registered_labels.sql b/crates/forge-core/migrations/0075_runner_registered_labels.sql new file mode 100644 index 0000000..c8468dd --- /dev/null +++ b/crates/forge-core/migrations/0075_runner_registered_labels.sql @@ -0,0 +1,2 @@ +ALTER TABLE ci_runners ADD COLUMN registered_labels TEXT NOT NULL DEFAULT '[]'; +UPDATE ci_runners SET registered_labels = COALESCE(json_extract(reported_config, '$.labels'), labels); diff --git a/crates/forge-core/migrations/0076_milestone_title_repair.sql b/crates/forge-core/migrations/0076_milestone_title_repair.sql new file mode 100644 index 0000000..8490bed --- /dev/null +++ b/crates/forge-core/migrations/0076_milestone_title_repair.sql @@ -0,0 +1 @@ +UPDATE milestones SET title = title WHERE 0; diff --git a/crates/forge-core/src/alerts.rs b/crates/forge-core/src/alerts.rs index 40c1b2c..42f5adf 100644 --- a/crates/forge-core/src/alerts.rs +++ b/crates/forge-core/src/alerts.rs @@ -8,6 +8,62 @@ pub enum AlertKind { Replication, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlertTopic { + RunnerOffline, + BackupFailed, + BackupVerifyFailed, + BackupOverdue, + FsckFailed, + DiskLow, + CiKilled, + SelfUpdateRestart, + SelfUpdateFailed, + Replication, +} + +impl AlertTopic { + pub const ALL: [Self; 10] = [ + Self::RunnerOffline, + Self::BackupFailed, + Self::BackupVerifyFailed, + Self::BackupOverdue, + Self::FsckFailed, + Self::DiskLow, + Self::CiKilled, + Self::SelfUpdateRestart, + Self::SelfUpdateFailed, + Self::Replication, + ]; + + pub fn kind(self) -> AlertKind { + match self { + Self::RunnerOffline => AlertKind::RunnerOffline, + Self::BackupFailed + | Self::BackupVerifyFailed + | Self::BackupOverdue + | Self::FsckFailed => AlertKind::Backup, + Self::DiskLow => AlertKind::Disk, + Self::CiKilled => AlertKind::CiKilled, + Self::SelfUpdateRestart | Self::SelfUpdateFailed => AlertKind::SelfUpdate, + Self::Replication => AlertKind::Replication, + } + } +} + +string_enum!(AlertTopic { + RunnerOffline = "runner_offline", + BackupFailed = "backup_failed", + BackupVerifyFailed = "backup_verify_failed", + BackupOverdue = "backup_overdue", + FsckFailed = "fsck_failed", + DiskLow = "disk_low", + CiKilled = "ci_killed", + SelfUpdateRestart = "self_update_restart", + SelfUpdateFailed = "self_update_failed", + Replication = "replication", +}); + pub fn is_kill_signature(exit_code: Option, message: Option<&str>) -> bool { if matches!(exit_code, Some(137) | Some(-9)) { return true; diff --git a/crates/forge-core/src/audit.rs b/crates/forge-core/src/audit.rs index 9653daf..0096b85 100644 --- a/crates/forge-core/src/audit.rs +++ b/crates/forge-core/src/audit.rs @@ -11,13 +11,9 @@ macro_rules! audit_actions { impl AuditAction { pub const ALL: &'static [AuditAction] = &[$(AuditAction::$variant,)*]; - - pub fn as_str(self) -> &'static str { - match self { - $(AuditAction::$variant => $name,)* - } - } } + + string_enum!(AuditAction { $($variant = $name),* }); }; } @@ -130,15 +126,6 @@ audit_actions! { PasskeyLogin => "passkey_login", } -impl AuditAction { - pub fn parse(name: &str) -> Option { - AuditAction::ALL - .iter() - .copied() - .find(|action| action.as_str() == name) - } -} - #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuditEntry { pub id: String, @@ -218,12 +205,12 @@ mod tests { fn names_are_unique_and_round_trip() { let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); for action in AuditAction::ALL { - assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); + assert_eq!(action.as_str().parse::().ok(), Some(*action)); } names.sort(); names.dedup(); assert_eq!(names.len(), AuditAction::ALL.len()); - assert_eq!(AuditAction::parse("nope"), None); + assert!("nope".parse::().is_err()); } #[test] diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 42d4fd8..90711ea 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -1,12 +1,9 @@ use std::collections::BTreeMap; -use std::str::FromStr; use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY}; pub use forge_ci::proto::RestartMode; -use crate::error::{Error, Result}; - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RunState { WaitingApproval, @@ -18,19 +15,17 @@ pub enum RunState { Error, } -impl RunState { - pub fn as_str(self) -> &'static str { - match self { - RunState::WaitingApproval => "waiting_approval", - RunState::Queued => "queued", - RunState::Running => "running", - RunState::Success => "success", - RunState::Failure => "failure", - RunState::Cancelled => "cancelled", - RunState::Error => "error", - } - } +string_enum!(RunState { + WaitingApproval = "waiting_approval", + Queued = "queued", + Running = "running", + Success = "success", + Failure = "failure", + Cancelled = "cancelled", + Error = "error", +}); +impl RunState { pub fn is_terminal(self) -> bool { matches!( self, @@ -39,23 +34,6 @@ impl RunState { } } -impl FromStr for RunState { - type Err = Error; - - fn from_str(s: &str) -> Result { - Ok(match s { - "waiting_approval" => RunState::WaitingApproval, - "queued" => RunState::Queued, - "running" => RunState::Running, - "success" => RunState::Success, - "failure" => RunState::Failure, - "cancelled" => RunState::Cancelled, - "error" => RunState::Error, - other => return Err(Error::Database(format!("unknown CI run state {other:?}"))), - }) - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum JobState { Blocked, @@ -68,20 +46,18 @@ pub enum JobState { Skipped, } -impl JobState { - pub fn as_str(self) -> &'static str { - match self { - JobState::Blocked => "blocked", - JobState::Queued => "queued", - JobState::Running => "running", - JobState::Success => "success", - JobState::Failure => "failure", - JobState::Cancelled => "cancelled", - JobState::Error => "error", - JobState::Skipped => "skipped", - } - } +string_enum!(JobState { + Blocked = "blocked", + Queued = "queued", + Running = "running", + Success = "success", + Failure = "failure", + Cancelled = "cancelled", + Error = "error", + Skipped = "skipped", +}); +impl JobState { pub fn is_terminal(self) -> bool { matches!( self, @@ -94,24 +70,6 @@ impl JobState { } } -impl FromStr for JobState { - type Err = Error; - - fn from_str(s: &str) -> Result { - Ok(match s { - "blocked" => JobState::Blocked, - "queued" => JobState::Queued, - "running" => JobState::Running, - "success" => JobState::Success, - "failure" => JobState::Failure, - "cancelled" => JobState::Cancelled, - "error" => JobState::Error, - "skipped" => JobState::Skipped, - other => return Err(Error::Database(format!("unknown CI job state {other:?}"))), - }) - } -} - #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiRunner { pub id: String, diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index 16e3b2e..c01ee00 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -6,14 +6,21 @@ use serde::{Deserialize, Deserializer}; use crate::error::{Error, Result}; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Registration { + #[default] Closed, Invite, Open, } +string_enum!(Registration { + Closed = "closed", + Invite = "invite", + Open = "open", +}); + fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result, D::Error> { @@ -166,7 +173,7 @@ impl AlertsConfig { #[serde(deny_unknown_fields, default)] pub struct BannerConfig { pub message: String, - pub level: String, + pub level: BannerLevel, pub expires: String, } @@ -174,12 +181,25 @@ impl Default for BannerConfig { fn default() -> Self { BannerConfig { message: String::new(), - level: "info".into(), + level: BannerLevel::Info, expires: String::new(), } } } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum BannerLevel { + #[default] + Info, + Warning, +} + +string_enum!(BannerLevel { + Info = "info", + Warning = "warning", +}); + impl BannerConfig { pub fn expires_unix(&self) -> Option { parse_banner_expiry(&self.expires) @@ -261,6 +281,11 @@ pub enum OrgCreation { Admin, } +string_enum!(OrgCreation { + All = "all", + Admin = "admin", +}); + #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct MailConfig { @@ -275,6 +300,11 @@ pub enum MailTransport { Log, } +string_enum!(MailTransport { + Smtp = "smtp", + Log = "log", +}); + #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct CiConfig { @@ -450,6 +480,12 @@ pub enum StorageBackend { R2, } +string_enum!(StorageBackend { + Fs = "fs", + S3 = "s3", + R2 = "r2", +}); + #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct S3Config { @@ -468,19 +504,38 @@ pub struct S3Config { pub struct R2Config { pub account_id: String, pub bucket: String, - pub jurisdiction: String, + pub jurisdiction: R2Jurisdiction, pub prefix: String, pub access_key_id: String, pub secret_access_key_file: PathBuf, } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum R2Jurisdiction { + #[default] + #[serde(rename = "")] + Global, + Eu, + Fedramp, +} + +string_enum!(R2Jurisdiction { + Global = "", + Eu = "eu", + Fedramp = "fedramp", +}); + impl R2Config { pub fn endpoint(&self) -> String { - match self.jurisdiction.as_str() { - "" => format!("https://{}.r2.cloudflarestorage.com", self.account_id), + match self.jurisdiction { + R2Jurisdiction::Global => { + format!("https://{}.r2.cloudflarestorage.com", self.account_id) + } jurisdiction => format!( - "https://{}.{jurisdiction}.r2.cloudflarestorage.com", - self.account_id + "https://{}.{}.r2.cloudflarestorage.com", + self.account_id, + jurisdiction.as_str() ), } } @@ -553,12 +608,6 @@ impl StorageConfig { require("storage.r2", "bucket", &r2.bucket)?; require("storage.r2", "access_key_id", &r2.access_key_id)?; check_secret_file("storage.r2", &r2.secret_access_key_file)?; - if !matches!(r2.jurisdiction.as_str(), "" | "eu" | "fedramp") { - return Err(Error::Config(format!( - "[storage.r2] jurisdiction must be \"eu\", \"fedramp\", or left empty, not \"{}\"", - r2.jurisdiction - ))); - } Ok(()) } } @@ -1023,17 +1072,26 @@ mod tests { #[test] fn r2_endpoint_follows_jurisdiction() { let cases = [ - ("", "https://acct.r2.cloudflarestorage.com"), - ("eu", "https://acct.eu.r2.cloudflarestorage.com"), - ("fedramp", "https://acct.fedramp.r2.cloudflarestorage.com"), + ( + R2Jurisdiction::Global, + "https://acct.r2.cloudflarestorage.com", + ), + ( + R2Jurisdiction::Eu, + "https://acct.eu.r2.cloudflarestorage.com", + ), + ( + R2Jurisdiction::Fedramp, + "https://acct.fedramp.r2.cloudflarestorage.com", + ), ]; for (jurisdiction, expected) in cases { let cfg = R2Config { account_id: "acct".into(), - jurisdiction: jurisdiction.into(), + jurisdiction, ..R2Config::default() }; - assert_eq!(cfg.endpoint(), expected, "jurisdiction `{jurisdiction}`"); + assert_eq!(cfg.endpoint(), expected, "jurisdiction {jurisdiction:?}"); } } diff --git a/crates/forge-core/src/discussions.rs b/crates/forge-core/src/discussions.rs index a42c68b..a2e5133 100644 --- a/crates/forge-core/src/discussions.rs +++ b/crates/forge-core/src/discussions.rs @@ -15,16 +15,14 @@ pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[ DiscussionCategory::Announcements, ]; -impl DiscussionCategory { - pub fn as_str(self) -> &'static str { - match self { - DiscussionCategory::General => "general", - DiscussionCategory::Ideas => "ideas", - DiscussionCategory::Qa => "qa", - DiscussionCategory::Announcements => "announcements", - } - } +string_enum!(DiscussionCategory { + General = "general", + Ideas = "ideas", + Qa = "qa", + Announcements = "announcements", +}); +impl DiscussionCategory { pub fn label(self) -> &'static str { match self { DiscussionCategory::General => "General", @@ -33,13 +31,6 @@ impl DiscussionCategory { DiscussionCategory::Announcements => "Announcements", } } - - pub fn parse(name: &str) -> Option { - DISCUSSION_CATEGORIES - .iter() - .copied() - .find(|c| c.as_str() == name) - } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -70,22 +61,10 @@ pub enum DiscussionReason { Reply, } -impl DiscussionReason { - pub fn as_str(self) -> &'static str { - match self { - DiscussionReason::Mention => "mention", - DiscussionReason::Reply => "reply", - } - } - - pub fn parse(name: &str) -> Option { - match name { - "mention" => Some(DiscussionReason::Mention), - "reply" => Some(DiscussionReason::Reply), - _ => None, - } - } -} +string_enum!(DiscussionReason { + Mention = "mention", + Reply = "reply", +}); #[derive(Debug, Clone, PartialEq, Eq)] pub struct DiscussionNotification { diff --git a/crates/forge-core/src/issues.rs b/crates/forge-core/src/issues.rs index 24ebbe0..312e7fb 100644 --- a/crates/forge-core/src/issues.rs +++ b/crates/forge-core/src/issues.rs @@ -13,26 +13,10 @@ pub enum IssueState { Closed, } -impl IssueState { - pub fn as_str(&self) -> &'static str { - match self { - IssueState::Open => "open", - IssueState::Closed => "closed", - } - } -} - -impl std::str::FromStr for IssueState { - type Err = Error; - - fn from_str(s: &str) -> Result { - match s { - "open" => Ok(IssueState::Open), - "closed" => Ok(IssueState::Closed), - other => Err(Error::Invalid(format!("issue state {other:?}"))), - } - } -} +string_enum!(IssueState { + Open = "open", + Closed = "closed", +}); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StateReason { @@ -40,26 +24,10 @@ pub enum StateReason { NotPlanned, } -impl StateReason { - pub fn as_str(&self) -> &'static str { - match self { - StateReason::Completed => "completed", - StateReason::NotPlanned => "not_planned", - } - } -} - -impl std::str::FromStr for StateReason { - type Err = Error; - - fn from_str(s: &str) -> Result { - match s { - "completed" => Ok(StateReason::Completed), - "not_planned" => Ok(StateReason::NotPlanned), - other => Err(Error::Invalid(format!("state reason {other:?}"))), - } - } -} +string_enum!(StateReason { + Completed = "completed", + NotPlanned = "not_planned", +}); #[derive(Debug, Clone, PartialEq)] pub struct Issue { @@ -167,28 +135,11 @@ pub enum IssueSort { RecentlyUpdated, } -impl IssueSort { - pub fn as_str(&self) -> &'static str { - match self { - IssueSort::Newest => "newest", - IssueSort::Oldest => "oldest", - IssueSort::RecentlyUpdated => "updated", - } - } -} - -impl std::str::FromStr for IssueSort { - type Err = Error; - - fn from_str(s: &str) -> Result { - match s { - "newest" => Ok(IssueSort::Newest), - "oldest" => Ok(IssueSort::Oldest), - "updated" => Ok(IssueSort::RecentlyUpdated), - other => Err(Error::Invalid(format!("sort {other:?}"))), - } - } -} +string_enum!(IssueSort { + Newest = "newest", + Oldest = "oldest", + RecentlyUpdated = "updated", +}); #[derive(Debug, Clone, PartialEq)] pub struct IssueListItem { diff --git a/crates/forge-core/src/lfs_token.rs b/crates/forge-core/src/lfs_token.rs index bbb77cf..b8b5715 100644 --- a/crates/forge-core/src/lfs_token.rs +++ b/crates/forge-core/src/lfs_token.rs @@ -1,11 +1,5 @@ +use crate::signed_token; use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; -use hmac::{Hmac, KeyInit, Mac}; -use sha2::Sha256; -use subtle::ConstantTimeEq; - -type HmacSha256 = Hmac; - -const MAC_LEN: usize = 32; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LfsOp { @@ -14,43 +8,28 @@ pub enum LfsOp { Any, } -impl LfsOp { - pub fn as_str(self) -> &'static str { - match self { - LfsOp::Download => "download", - LfsOp::Upload => "upload", - LfsOp::Any => "any", - } - } - - fn parse(s: &str) -> Option { - match s { - "download" => Some(LfsOp::Download), - "upload" => Some(LfsOp::Upload), - "any" => Some(LfsOp::Any), - _ => None, - } - } -} - -fn mac_for(key: &[u8; 32], repo_id: &str, op: &str, expires_unix: i64) -> HmacSha256 { - let mut mac = - ::new_from_slice(key).expect("HMAC accepts any key length"); - mac.update(b"lfs\0"); - mac.update(repo_id.as_bytes()); - mac.update(b"\0"); - mac.update(op.as_bytes()); - mac.update(b"\0"); - mac.update(expires_unix.to_string().as_bytes()); - mac +string_enum!(LfsOp { + Download = "download", + Upload = "upload", + Any = "any", +}); + +fn framing<'a>(repo_id: &'a str, op: &'a str, expires: &'a str) -> [&'a [u8]; 6] { + [ + b"lfs\0", + repo_id.as_bytes(), + b"\0", + op.as_bytes(), + b"\0", + expires.as_bytes(), + ] } pub fn issue(key: &[u8; 32], repo_id: &str, op: LfsOp, expires_unix: i64) -> String { - let tag = mac_for(key, repo_id, op.as_str(), expires_unix) - .finalize() - .into_bytes(); + let expires = expires_unix.to_string(); + let tag = signed_token::mac(key, &framing(repo_id, op.as_str(), &expires)); format!( - "{expires_unix}.{}.{}", + "{expires}.{}.{}", op.as_str(), BASE64_URL_SAFE_NO_PAD.encode(tag) ) @@ -63,16 +42,13 @@ pub fn verify(key: &[u8; 32], token: &str, repo_id: &str, wanted: LfsOp, now_uni else { return false; }; - let Ok(expires) = expires_str.parse::() else { + let Some(expires) = signed_token::parse_expiry(expires_str) else { return false; }; - if expires.to_string() != expires_str { - return false; - } if now_unix >= expires { return false; } - let Some(token_op) = LfsOp::parse(op_str) else { + let Ok(token_op) = op_str.parse::() else { return false; }; let satisfies = token_op == LfsOp::Any || token_op == wanted; @@ -82,18 +58,13 @@ pub fn verify(key: &[u8; 32], token: &str, repo_id: &str, wanted: LfsOp, now_uni let Ok(tag) = BASE64_URL_SAFE_NO_PAD.decode(mac_str) else { return false; }; - if tag.len() != MAC_LEN { - return false; - } - let expected = mac_for(key, repo_id, op_str, expires) - .finalize() - .into_bytes(); - bool::from(expected.as_slice().ct_eq(&tag)) + signed_token::verify(key, &framing(repo_id, op_str, expires_str), &tag) } #[cfg(test)] mod tests { use super::*; + use crate::signed_token::MAC_LEN; const KEY: [u8; 32] = [7; 32]; const OTHER_KEY: [u8; 32] = [9; 32]; diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index 1748977..e129725 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -1,3 +1,29 @@ +macro_rules! string_enum { + ($name:ident { $($variant:ident = $text:literal),+ $(,)? }) => { + impl $name { + pub const fn as_str(self) -> &'static str { + match self { + $(Self::$variant => $text),+ + } + } + } + + impl std::str::FromStr for $name { + type Err = crate::error::Error; + + fn from_str(s: &str) -> std::result::Result { + match s { + $($text => Ok(Self::$variant),)+ + other => Err(crate::error::Error::Invalid(format!( + "{}: {other:?}", + stringify!($name) + ))), + } + } + } + }; +} + pub mod advisories; pub mod alerts; pub mod audit; @@ -28,6 +54,7 @@ pub mod releases; pub mod reviews; pub mod secret; pub mod server_settings; +pub mod signed_token; pub mod store; pub mod suggestions; pub mod time; diff --git a/crates/forge-core/src/mail.rs b/crates/forge-core/src/mail.rs index 717a9c4..2f596d5 100644 --- a/crates/forge-core/src/mail.rs +++ b/crates/forge-core/src/mail.rs @@ -25,24 +25,11 @@ pub enum Security { Plain, } -impl Security { - pub fn as_str(self) -> &'static str { - match self { - Security::StartTls => "starttls", - Security::Tls => "tls", - Security::Plain => "none", - } - } - - pub fn parse(s: &str) -> Option { - match s { - "starttls" => Some(Security::StartTls), - "tls" => Some(Security::Tls), - "none" => Some(Security::Plain), - _ => None, - } - } -} +string_enum!(Security { + StartTls = "starttls", + Tls = "tls", + Plain = "none", +}); #[derive(Debug, Clone, PartialEq, Eq)] pub struct MailSettings { @@ -121,23 +108,17 @@ impl MailKind { MailKind::Test, MailKind::Other, ]; - - pub fn as_str(self) -> &'static str { - match self { - MailKind::Verification => "verification", - MailKind::PasswordReset => "password_reset", - MailKind::Invite => "invite", - MailKind::Notification => "notification", - MailKind::Test => "test", - MailKind::Other => "other", - } - } - - pub fn parse(s: &str) -> Option { - MailKind::ALL.into_iter().find(|kind| kind.as_str() == s) - } } +string_enum!(MailKind { + Verification = "verification", + PasswordReset = "password_reset", + Invite = "invite", + Notification = "notification", + Test = "test", + Other = "other", +}); + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MailState { Queued, @@ -157,23 +138,17 @@ impl MailState { MailState::Failed, MailState::Discarded, ]; - - pub fn as_str(self) -> &'static str { - match self { - MailState::Queued => "queued", - MailState::Retrying => "retrying", - MailState::Sending => "sending", - MailState::Sent => "sent", - MailState::Failed => "failed", - MailState::Discarded => "discarded", - } - } - - pub fn parse(s: &str) -> Option { - MailState::ALL.into_iter().find(|state| state.as_str() == s) - } } +string_enum!(MailState { + Queued = "queued", + Retrying = "retrying", + Sending = "sending", + Sent = "sent", + Failed = "failed", + Discarded = "discarded", +}); + #[derive(Clone, PartialEq, Eq)] pub struct OutgoingMail { pub to: String, @@ -415,17 +390,17 @@ mod tests { #[test] fn enum_names_round_trip_and_unknown_names_are_refused() { for s in [Security::StartTls, Security::Tls, Security::Plain] { - assert_eq!(Security::parse(s.as_str()), Some(s)); + assert_eq!(s.as_str().parse::().ok(), Some(s)); } - assert_eq!(Security::parse("ssl"), None); + assert!("ssl".parse::().is_err()); for kind in MailKind::ALL { - assert_eq!(MailKind::parse(kind.as_str()), Some(kind)); + assert_eq!(kind.as_str().parse::().ok(), Some(kind)); } - assert_eq!(MailKind::parse("spam"), None); + assert!("spam".parse::().is_err()); for state in MailState::ALL { - assert_eq!(MailState::parse(state.as_str()), Some(state)); + assert_eq!(state.as_str().parse::().ok(), Some(state)); } - assert_eq!(MailState::parse("gave up"), None); + assert!("gave up".parse::().is_err()); } #[test] diff --git a/crates/forge-core/src/merge_queue.rs b/crates/forge-core/src/merge_queue.rs index 453c1c4..8f66b6c 100644 --- a/crates/forge-core/src/merge_queue.rs +++ b/crates/forge-core/src/merge_queue.rs @@ -1,4 +1,3 @@ -use crate::error::{Error, Result}; use crate::pulls::MergeStyle; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -10,36 +9,13 @@ pub enum QueueState { Removed, } -impl QueueState { - pub fn as_str(self) -> &'static str { - match self { - QueueState::Queued => "queued", - QueueState::Testing => "testing", - QueueState::Merging => "merging", - QueueState::Failed => "failed", - QueueState::Removed => "removed", - } - } -} - -impl std::str::FromStr for QueueState { - type Err = Error; - - fn from_str(s: &str) -> Result { - Ok(match s { - "queued" => QueueState::Queued, - "testing" => QueueState::Testing, - "merging" => QueueState::Merging, - "failed" => QueueState::Failed, - "removed" => QueueState::Removed, - other => { - return Err(Error::Database(format!( - "unknown merge queue state {other}" - ))); - } - }) - } -} +string_enum!(QueueState { + Queued = "queued", + Testing = "testing", + Merging = "merging", + Failed = "failed", + Removed = "removed", +}); #[derive(Debug, Clone, PartialEq, Eq)] pub struct QueueEntry { diff --git a/crates/forge-core/src/mirrors.rs b/crates/forge-core/src/mirrors.rs index 42cc60a..d3110ee 100644 --- a/crates/forge-core/src/mirrors.rs +++ b/crates/forge-core/src/mirrors.rs @@ -6,28 +6,10 @@ pub enum MirrorDirection { Push, } -impl MirrorDirection { - pub fn as_str(self) -> &'static str { - match self { - MirrorDirection::Pull => "pull", - MirrorDirection::Push => "push", - } - } -} - -impl std::str::FromStr for MirrorDirection { - type Err = crate::error::Error; - - fn from_str(s: &str) -> Result { - match s { - "pull" => Ok(MirrorDirection::Pull), - "push" => Ok(MirrorDirection::Push), - other => Err(crate::error::Error::Database(format!( - "unknown mirror direction {other:?}" - ))), - } - } -} +string_enum!(MirrorDirection { + Pull = "pull", + Push = "push", +}); #[derive(Debug, Clone, PartialEq, Eq)] pub struct Mirror { diff --git a/crates/forge-core/src/model.rs b/crates/forge-core/src/model.rs index 7f62d0b..8247978 100644 --- a/crates/forge-core/src/model.rs +++ b/crates/forge-core/src/model.rs @@ -147,55 +147,18 @@ impl std::fmt::Debug for Session { } } -impl Visibility { - pub fn as_str(&self) -> &'static str { - match self { - Visibility::Public => "public", - Visibility::Private => "private", - } - } -} - -impl std::str::FromStr for Visibility { - type Err = crate::error::Error; - - fn from_str(s: &str) -> Result { - match s { - "public" => Ok(Visibility::Public), - "private" => Ok(Visibility::Private), - other => Err(crate::error::Error::Invalid(format!( - "visibility {other:?}" - ))), - } - } -} - -impl Role { - pub fn as_str(&self) -> &'static str { - match self { - Role::Read => "read", - Role::Triage => "triage", - Role::Write => "write", - Role::Maintain => "maintain", - Role::Admin => "admin", - } - } -} - -impl std::str::FromStr for Role { - type Err = crate::error::Error; - - fn from_str(s: &str) -> Result { - match s { - "read" => Ok(Role::Read), - "triage" => Ok(Role::Triage), - "write" => Ok(Role::Write), - "maintain" => Ok(Role::Maintain), - "admin" => Ok(Role::Admin), - other => Err(crate::error::Error::Invalid(format!("role {other:?}"))), - } - } -} +string_enum!(Visibility { + Public = "public", + Private = "private", +}); + +string_enum!(Role { + Read = "read", + Triage = "triage", + Write = "write", + Maintain = "maintain", + Admin = "admin", +}); #[cfg(test)] mod tests { diff --git a/crates/forge-core/src/notifications.rs b/crates/forge-core/src/notifications.rs index f5deac8..f8b710e 100644 --- a/crates/forge-core/src/notifications.rs +++ b/crates/forge-core/src/notifications.rs @@ -8,24 +8,11 @@ pub enum WatchLevel { Ignoring, } -impl WatchLevel { - pub fn as_str(self) -> &'static str { - match self { - WatchLevel::Watching => "watching", - WatchLevel::Participating => "participating", - WatchLevel::Ignoring => "ignoring", - } - } - - pub fn parse(s: &str) -> Option { - match s { - "watching" => Some(WatchLevel::Watching), - "participating" => Some(WatchLevel::Participating), - "ignoring" => Some(WatchLevel::Ignoring), - _ => None, - } - } -} +string_enum!(WatchLevel { + Watching = "watching", + Participating = "participating", + Ignoring = "ignoring", +}); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SubState { @@ -33,22 +20,10 @@ pub enum SubState { Ignored, } -impl SubState { - pub fn as_str(self) -> &'static str { - match self { - SubState::Subscribed => "subscribed", - SubState::Ignored => "ignored", - } - } - - pub fn parse(s: &str) -> Option { - match s { - "subscribed" => Some(SubState::Subscribed), - "ignored" => Some(SubState::Ignored), - _ => None, - } - } -} +string_enum!(SubState { + Subscribed = "subscribed", + Ignored = "ignored", +}); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Reason { @@ -62,34 +37,18 @@ pub enum Reason { Watching, } -impl Reason { - pub fn as_str(self) -> &'static str { - match self { - Reason::Mention => "mention", - Reason::Assign => "assign", - Reason::ReviewRequested => "review_requested", - Reason::Author => "author", - Reason::Comment => "comment", - Reason::StateChange => "state_change", - Reason::Subscribed => "subscribed", - Reason::Watching => "watching", - } - } - - pub fn parse(s: &str) -> Option { - match s { - "mention" => Some(Reason::Mention), - "assign" => Some(Reason::Assign), - "review_requested" => Some(Reason::ReviewRequested), - "author" => Some(Reason::Author), - "comment" => Some(Reason::Comment), - "state_change" => Some(Reason::StateChange), - "subscribed" => Some(Reason::Subscribed), - "watching" => Some(Reason::Watching), - _ => None, - } - } +string_enum!(Reason { + Mention = "mention", + Assign = "assign", + ReviewRequested = "review_requested", + Author = "author", + Comment = "comment", + StateChange = "state_change", + Subscribed = "subscribed", + Watching = "watching", +}); +impl Reason { pub fn rank(self) -> u8 { match self { Reason::Mention => 8, diff --git a/crates/forge-core/src/oci.rs b/crates/forge-core/src/oci.rs index 0ad11b7..f3ac53c 100644 --- a/crates/forge-core/src/oci.rs +++ b/crates/forge-core/src/oci.rs @@ -1,10 +1,6 @@ +use crate::signed_token; use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; -use hmac::{Hmac, KeyInit, Mac}; use serde_json::Value; -use sha2::Sha256; -use subtle::ConstantTimeEq; - -type HmacSha256 = Hmac; pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [ "application/vnd.oci.image.manifest.v1+json", @@ -134,17 +130,13 @@ fn descriptor_size(descriptor: &Value) -> u64 { descriptor.get("size").and_then(Value::as_u64).unwrap_or(0) } -fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 { - let mut mac = - ::new_from_slice(key).expect("HMAC accepts any key length"); - mac.update(b"oci\0"); - mac.update(payload); - mac +fn framing(payload: &[u8]) -> [&[u8]; 2] { + [b"oci\0", payload] } pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String { let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or("")); - let tag = mac_for(key, payload.as_bytes()).finalize().into_bytes(); + let tag = signed_token::mac(key, &framing(payload.as_bytes())); format!( "{}.{}", BASE64_URL_SAFE_NO_PAD.encode(payload.as_bytes()), @@ -156,8 +148,7 @@ pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option