diff --git a/Cargo.lock b/Cargo.lock index 36cc994..d7e5419 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -582,6 +582,7 @@ dependencies = [ "anyhow", "askama", "async-trait", + "axum", "base64 0.23.1", "bytes", "cached", @@ -621,12 +622,14 @@ name = "dco2-server" version = "0.1.0" dependencies = [ "anyhow", + "async-trait", "axum", "clap", "dco2", "figment", "hex", "hmac", + "indoc", "serde", "sha2", "tokio", @@ -737,6 +740,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "figment" version = "0.10.19" @@ -744,9 +753,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" dependencies = [ "atomic", + "parking_lot 0.12.5", "pear", "serde", "serde_yaml", + "tempfile", "uncased", "version_check", ] @@ -1386,6 +1397,12 @@ version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2137,6 +2154,19 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.52.0", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2448,6 +2478,19 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.3.4", + "once_cell", + "rustix", + "windows-sys 0.52.0", +] + [[package]] name = "termtree" version = "0.5.1" diff --git a/README.md b/README.md index ffcdbe1..64d0d49 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,9 @@ git commit -s -m 'Commit message' Once installed, this application will create a check indicating whether or not all commits in a Pull Request contain a valid `Signed-off-by` line. +> [!NOTE] +> Pull requests containing more than 1000 commits are not checked: the check fails with a message explaining why. + ![check-passed](docs/screenshots/check-passed.png) More information about the check result is available on the check details page. This information includes a full list of the commits checked (including the reason why each of them passed or failed the check), some additional details about each error found and some instructions on how to fix them. diff --git a/charts/dco2/templates/server_secret.yaml b/charts/dco2/templates/server_secret.yaml index 4885b18..de9ff7a 100644 --- a/charts/dco2/templates/server_secret.yaml +++ b/charts/dco2/templates/server_secret.yaml @@ -9,9 +9,9 @@ stringData: {{- if .Values.server.config.githubApp.apiHost }} api_host: {{ .Values.server.config.githubApp.apiHost }} {{- end }} - app_id: {{ .Values.server.config.githubApp.appId }} + app_id: {{ .Values.server.config.githubApp.appId | int64 }} private_key: |- {{ .Values.server.config.githubApp.privateKey | default "" | nindent 8 }} - webhook_secret: {{ .Values.server.config.githubApp.webhookSecret | quote }} + webhook_secret: {{ required "server.config.githubApp.webhookSecret is required" .Values.server.config.githubApp.webhookSecret | quote }} log_format: {{ .Values.server.config.logFormat }} server_addr: {{ .Values.server.config.addr }} diff --git a/charts/dco2/values.yaml b/charts/dco2/values.yaml index b4af861..3891995 100644 --- a/charts/dco2/values.yaml +++ b/charts/dco2/values.yaml @@ -42,7 +42,7 @@ server: appId: 0 # GitHub application private key privateKey: "" - # GitHub webhook secret + # GitHub webhook secret (required, it cannot be empty) webhookSecret: "" # Log output format [json|pretty] diff --git a/dco2-aws-lambda/src/main.rs b/dco2-aws-lambda/src/main.rs index e4c15ac..a823bf1 100644 --- a/dco2-aws-lambda/src/main.rs +++ b/dco2-aws-lambda/src/main.rs @@ -5,7 +5,10 @@ use figment::{Figment, providers::Env}; use lambda_http::{Error, run, tracing}; use dco2::github::{AppConfig, GHClientOctorust}; -use dco2_server::handlers::setup_router; +use dco2_server::{env::env_with_raw_keys, handlers::setup_router}; + +/// Configuration keys whose environment variables values must not be parsed. +const RAW_ENV_KEYS: &[&str] = &["webhook_secret"]; #[tokio::main] async fn main() -> Result<(), Error> { @@ -18,11 +21,14 @@ async fn main() -> Result<(), Error> { } tracing::init_default_subscriber(); - // Setup GitHub client + // Setup configuration let cfg: AppConfig = Figment::new() - .merge(Env::prefixed("DCO2_")) + .merge(env_with_raw_keys(&Env::prefixed("DCO2_"), RAW_ENV_KEYS)) .extract() .context("error setting up configuration")?; + cfg.validate().context("invalid configuration")?; + + // Setup GitHub client let gh_client = Arc::new(GHClientOctorust::new(&cfg).context("error setting up github client")?); // Start lambda runtime diff --git a/dco2-server/Cargo.toml b/dco2-server/Cargo.toml index 74185e7..cf94f7f 100644 --- a/dco2-server/Cargo.toml +++ b/dco2-server/Cargo.toml @@ -21,3 +21,9 @@ tower = { workspace = true } tower-http = { workspace = true } tracing = { workspace = true } tracing-subscriber = { workspace = true } + +[dev-dependencies] +async-trait = { workspace = true } +figment = { workspace = true, features = ["test"] } +indoc = { workspace = true } +tower = { workspace = true, features = ["util"] } diff --git a/dco2-server/src/config.rs b/dco2-server/src/config.rs index 819abb0..5eb83c5 100644 --- a/dco2-server/src/config.rs +++ b/dco2-server/src/config.rs @@ -2,7 +2,7 @@ use std::path::PathBuf; -use anyhow::Result; +use anyhow::{Context, Result}; use figment::{ Figment, providers::{Env, Format, Serialized, Yaml}, @@ -10,6 +10,13 @@ use figment::{ use serde::{Deserialize, Serialize}; use dco2::github::AppConfig; +use dco2_server::env::env_with_raw_keys; + +#[cfg(test)] +mod tests; + +/// Configuration keys whose environment variables values must not be parsed. +const RAW_ENV_KEYS: &[&str] = &["github_app.webhook_secret"]; /// Server configuration. #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] @@ -22,13 +29,24 @@ pub(crate) struct Config { impl Config { /// Create a new Config instance. pub(crate) fn new(config_file: Option<&PathBuf>) -> Result { + // Setup defaults let mut figment = Figment::new() .merge(Serialized::default("log_format", "json")) .merge(Serialized::default("server_addr", "localhost:9000")); + + // Merge the config file provided (it must exist at the exact path) if let Some(config_file) = config_file { - figment = figment.merge(Yaml::file(config_file)); + figment = figment.merge(Yaml::file_exact(config_file)); } - figment.merge(Env::prefixed("DCO2_").split("__")).extract().map_err(Into::into) + + // Merge the environment variables, which take precedence + let env = Env::prefixed("DCO2_").split("__"); + let cfg: Self = figment.merge(env_with_raw_keys(&env, RAW_ENV_KEYS)).extract()?; + + // Validate the resulting configuration + cfg.github_app.validate().context("invalid configuration")?; + + Ok(cfg) } } diff --git a/dco2-server/src/config/tests.rs b/dco2-server/src/config/tests.rs new file mode 100644 index 0000000..7f8f315 --- /dev/null +++ b/dco2-server/src/config/tests.rs @@ -0,0 +1,206 @@ +// figment::Jail closures must return figment::Result, whose error type is large +#![allow(clippy::result_large_err)] + +use std::path::PathBuf; + +use figment::Jail; +use indoc::indoc; + +use dco2::github::AppConfig; + +use super::{Config, LogFormat}; + +/// Name of the configuration file created in the tests. +const CONFIG_FILE: &str = "dco2-server.yml"; + +#[test] +fn chart_rendered_config_parses() { + Jail::expect_with(|jail| { + // Setup config file as rendered by the chart's server secret template + jail.clear_env(); + jail.create_file( + CONFIG_FILE, + indoc! {r#" + github_app: + api_host: ghe.example.com + app_id: 1234 + private_key: |- + + -----BEGIN RSA PRIVATE KEY----- + key + -----END RSA PRIVATE KEY----- + webhook_secret: "0123" + log_format: pretty + server_addr: 0.0.0.0:9000 + "#}, + )?; + + // Load the configuration + let cfg = Config::new(Some(&PathBuf::from(CONFIG_FILE))).unwrap(); + + // Check all the values were loaded from the config file + assert_eq!( + cfg, + Config { + github_app: AppConfig { + api_host: Some("ghe.example.com".to_string()), + app_id: 1234, + private_key: "\n-----BEGIN RSA PRIVATE KEY-----\nkey\n-----END RSA PRIVATE KEY-----" + .to_string(), + webhook_secret: "0123".to_string(), + }, + log_format: LogFormat::Pretty, + server_addr: "0.0.0.0:9000".to_string(), + } + ); + Ok(()) + }); +} + +#[test] +fn empty_webhook_secret_is_rejected() { + Jail::expect_with(|jail| { + // Setup environment with an empty webhook secret + jail.clear_env(); + set_github_app_env(jail); + jail.set_env("DCO2_GITHUB_APP__WEBHOOK_SECRET", ""); + + // Load the configuration and check it is rejected + let err = Config::new(None).unwrap_err(); + assert_eq!( + format!("{err:#}"), + "invalid configuration: github app webhook secret cannot be empty" + ); + Ok(()) + }); +} + +#[test] +fn env_vars_override_config_file() { + Jail::expect_with(|jail| { + // Setup config file and environment variables overriding some values + jail.clear_env(); + jail.create_file( + CONFIG_FILE, + indoc! {r#" + github_app: + app_id: 1234 + private_key: key + webhook_secret: "secret" + log_format: pretty + server_addr: 0.0.0.0:9000 + "#}, + )?; + jail.set_env("DCO2_GITHUB_APP__WEBHOOK_SECRET", "env-secret"); + jail.set_env("DCO2_LOG_FORMAT", "json"); + jail.set_env("DCO2_SERVER_ADDR", "127.0.0.1:1"); + + // Load the configuration + let cfg = Config::new(Some(&PathBuf::from(CONFIG_FILE))).unwrap(); + + // Check the environment values (nested ones included) took precedence + assert_eq!( + cfg, + Config { + github_app: AppConfig { + api_host: None, + app_id: 1234, + private_key: "key".to_string(), + webhook_secret: "env-secret".to_string(), + }, + log_format: LogFormat::Json, + server_addr: "127.0.0.1:1".to_string(), + } + ); + Ok(()) + }); +} + +#[test] +fn missing_config_file_is_rejected() { + Jail::expect_with(|jail| { + // Setup environment with all the required values + jail.clear_env(); + set_github_app_env(jail); + let config_file = PathBuf::from(CONFIG_FILE); + + // Check a config file that does not exist is rejected + let err = Config::new(Some(&config_file)).unwrap_err(); + assert!(err.to_string().contains(CONFIG_FILE), "{err:#}"); + + // Check parent directories are not searched for the config file + jail.create_file(CONFIG_FILE, "log_format: pretty")?; + jail.change_dir(jail.create_dir("subdir")?)?; + let err = Config::new(Some(&config_file)).unwrap_err(); + assert!(err.to_string().contains(CONFIG_FILE), "{err:#}"); + Ok(()) + }); +} + +#[test] +fn quoted_webhook_secret_in_config_file_is_rejected() { + Jail::expect_with(|jail| { + // Setup config file with a webhook secret wrapped in quotes + jail.clear_env(); + jail.create_file( + CONFIG_FILE, + indoc! {r#" + github_app: + app_id: 1234 + private_key: key + webhook_secret: '"0123"' + "#}, + )?; + + // Load the configuration and check it is rejected + let err = Config::new(Some(&PathBuf::from(CONFIG_FILE))).unwrap_err(); + assert_eq!( + format!("{err:#}"), + "invalid configuration: github app webhook secret cannot be wrapped in quotes" + ); + Ok(()) + }); +} + +#[test] +fn webhook_secret_env_var_is_trimmed_and_unquoted_but_not_parsed() { + for (webhook_secret, expected_webhook_secret) in [ + ("0123", "0123"), + ("123456", "123456"), + ("true", "true"), + (" secret\n", "secret"), + ("\"0123\"", "0123"), + ] { + Jail::expect_with(|jail| { + // Setup environment with a webhook secret figment would parse + jail.clear_env(); + set_github_app_env(jail); + jail.set_env("DCO2_GITHUB_APP__WEBHOOK_SECRET", webhook_secret); + + // Load the configuration + let cfg = Config::new(None).unwrap(); + + // Check the webhook secret is kept as a string and the app id is parsed + assert_eq!( + cfg.github_app, + AppConfig { + api_host: None, + app_id: 1234, + private_key: "key".to_string(), + webhook_secret: expected_webhook_secret.to_string(), + }, + "webhook secret: {webhook_secret:?}" + ); + Ok(()) + }); + } +} + +// Helpers. + +/// Set the environment variables with the required GitHub app settings. +fn set_github_app_env(jail: &mut Jail) { + jail.set_env("DCO2_GITHUB_APP__APP_ID", "1234"); + jail.set_env("DCO2_GITHUB_APP__PRIVATE_KEY", "key"); + jail.set_env("DCO2_GITHUB_APP__WEBHOOK_SECRET", "secret"); +} diff --git a/dco2-server/src/env.rs b/dco2-server/src/env.rs new file mode 100644 index 0000000..d2d892e --- /dev/null +++ b/dco2-server/src/env.rs @@ -0,0 +1,36 @@ +//! This module provides helpers to load configuration from environment +//! variables. + +use figment::{ + Figment, + providers::{Env, Serialized}, +}; + +#[cfg(test)] +mod tests; + +/// Create a provider that loads the environment variables selected by `env`, +/// keeping the values of the `raw_keys` provided as strings. +/// +/// Figment parses the values of environment variables, so a secret like `0123` +/// would become the number `123`, and `true` a boolean. The values of the raw +/// keys bypass that parsing and are always loaded as strings. As figment does +/// when parsing values, leading and trailing whitespace is trimmed and the +/// double quotes wrapping a value are removed. +pub fn env_with_raw_keys(env: &Env, raw_keys: &[&str]) -> Figment { + // Load the values of all keys but the raw ones, parsing them + let parsed = Figment::from(env.clone().ignore(raw_keys)); + + // Load the values of the raw keys as strings + env.clone().only(raw_keys).iter().fold(parsed, |figment, (key, value)| { + figment.merge(Serialized::default(key.as_str(), raw_value(&value))) + }) +} + +/// Prepare the value of a raw key: leading and trailing whitespace is trimmed +/// and, when the value is wrapped in double quotes, they are removed. The rest +/// of the value is kept as is (escape sequences are not processed). +fn raw_value(value: &str) -> &str { + let value = value.trim(); + value.strip_prefix('"').and_then(|unquoted| unquoted.strip_suffix('"')).unwrap_or(value) +} diff --git a/dco2-server/src/env/tests.rs b/dco2-server/src/env/tests.rs new file mode 100644 index 0000000..15b3c57 --- /dev/null +++ b/dco2-server/src/env/tests.rs @@ -0,0 +1,104 @@ +// figment::Jail closures must return figment::Result, whose error type is large +#![allow(clippy::result_large_err)] + +use figment::{Jail, providers::Env}; +use serde::Deserialize; + +use dco2::github::AppConfig; + +use super::env_with_raw_keys; + +#[test] +fn flat_raw_key_is_loaded_as_trimmed_string() { + for (value, expected_value) in [("0123", "0123"), ("true", "true"), (" 0123\n", "0123")] { + Jail::expect_with(|jail| { + // Setup environment as the lambda does (flat keys) + jail.clear_env(); + jail.set_env("DCO2_APP_ID", "1234"); + jail.set_env("DCO2_PRIVATE_KEY", "key"); + jail.set_env("DCO2_WEBHOOK_SECRET", value); + + // Load the configuration + let cfg: AppConfig = env_with_raw_keys(&Env::prefixed("DCO2_"), &["webhook_secret"]).extract()?; + + // Check the raw key is kept as a string and other keys are parsed + assert_eq!( + cfg, + AppConfig { + api_host: None, + app_id: 1234, + private_key: "key".to_string(), + webhook_secret: expected_value.to_string(), + }, + "value: {value:?}" + ); + Ok(()) + }); + } +} + +#[test] +fn nested_raw_key_is_loaded_as_trimmed_string() { + for (value, expected_value) in [("0123", "0123"), ("true", "true"), (" 0123\n", "0123")] { + Jail::expect_with(|jail| { + // Setup environment as the server does (nested keys) + jail.clear_env(); + jail.set_env("DCO2_GITHUB_APP__APP_ID", "1234"); + jail.set_env("DCO2_GITHUB_APP__PRIVATE_KEY", "key"); + jail.set_env("DCO2_GITHUB_APP__WEBHOOK_SECRET", value); + + // Load the configuration + let env = Env::prefixed("DCO2_").split("__"); + let cfg: Wrapper = env_with_raw_keys(&env, &["github_app.webhook_secret"]).extract()?; + + // Check the raw key is kept as a string and other keys are parsed + assert_eq!( + cfg.github_app, + AppConfig { + api_host: None, + app_id: 1234, + private_key: "key".to_string(), + webhook_secret: expected_value.to_string(), + }, + "value: {value:?}" + ); + Ok(()) + }); + } +} + +#[test] +fn raw_key_wrapping_quotes_are_removed() { + for (value, expected_value) in [ + ("\"0123\"", "0123"), + (" \"0123\"\n", "0123"), + ("\" 0123 \"", " 0123 "), + ("\"\"0123\"\"", "\"0123\""), + ("\"0123", "\"0123"), + ("01\"23", "01\"23"), + ("\"", "\""), + ] { + Jail::expect_with(|jail| { + // Setup environment with a raw key that may be wrapped in quotes + jail.clear_env(); + jail.set_env("DCO2_APP_ID", "1234"); + jail.set_env("DCO2_PRIVATE_KEY", "key"); + jail.set_env("DCO2_WEBHOOK_SECRET", value); + + // Load the configuration + let cfg: AppConfig = env_with_raw_keys(&Env::prefixed("DCO2_"), &["webhook_secret"]).extract()?; + + // Check only the quotes wrapping the value were removed + assert_eq!(cfg.webhook_secret, expected_value, "value: {value:?}"); + Ok(()) + }); + } +} + +// Helpers. + +/// Configuration with the GitHub app settings nested under a key. +#[derive(Debug, Deserialize)] +struct Wrapper { + github_app: AppConfig, +} diff --git a/dco2-server/src/handlers.rs b/dco2-server/src/handlers.rs index 25643ef..d98bec8 100644 --- a/dco2-server/src/handlers.rs +++ b/dco2-server/src/handlers.rs @@ -20,6 +20,9 @@ use dco2::{ github::{DynGHClient, EVENT_ID_HEADER, EVENT_SIGNATURE_HEADER, Event, EventError}, }; +#[cfg(test)] +mod tests; + /// Router's state. #[derive(Clone, FromRef)] struct RouterState { diff --git a/dco2-server/src/handlers/tests.rs b/dco2-server/src/handlers/tests.rs new file mode 100644 index 0000000..2e85ae1 --- /dev/null +++ b/dco2-server/src/handlers/tests.rs @@ -0,0 +1,278 @@ +use std::sync::{Arc, Mutex}; + +use anyhow::{Result, format_err}; +use async_trait::async_trait; +use axum::{ + Router, + body::{Body, to_bytes}, + http::{HeaderMap, HeaderValue, Method, Request, StatusCode}, +}; +use hmac::{Hmac, KeyInit, Mac}; +use sha2::Sha256; +use tower::ServiceExt; + +use dco2::github::{ + CheckRun, Commit, Config, Ctx, DynGHClient, EVENT_SIGNATURE_HEADER, GHClient, PullRequestState, +}; + +use super::{setup_router, verify_signature}; + +/// Body used in the signature verification tests. +const BODY: &[u8] = br#"{"action":"checks_requested"}"#; + +/// Header containing the name of the webhook event. +const EVENT_NAME_HEADER: &str = "X-GitHub-Event"; + +/// Merge group checks requested event payload. +const MERGE_GROUP_PAYLOAD: &str = r#"{ + "action": "checks_requested", + "installation": { "id": 1 }, + "merge_group": { "head_commit": { "id": "abc" } }, + "repository": { "id": 1, "name": "repo", "owner": { "login": "owner" } } +}"#; + +/// Webhook secret configured in the router. +const SECRET: &str = "secret"; + +#[tokio::test] +async fn health_check_returns_ok() { + // Setup router and request + let router = setup_router(FakeGHClient::new().into_dyn(), SECRET); + let request = Request::builder().uri("/health-check").body(Body::empty()).unwrap(); + + // Send request and check the response + assert_eq!(send(router, request).await, (StatusCode::OK, String::new())); +} + +#[tokio::test] +async fn processed_event_returns_ok() { + // Setup router and signed merge group event request + let gh_client = FakeGHClient::new(); + let router = setup_router(gh_client.clone().into_dyn(), SECRET); + let body = MERGE_GROUP_PAYLOAD.as_bytes(); + let request = webhook_request(Some("merge_group"), Some(&sign(SECRET, body)), body); + + // Send request and check the response + assert_eq!(send(router, request).await, (StatusCode::OK, String::new())); + + // Check the event was processed creating a check run + let ctx = Ctx { + inst_id: 1, + owner: "owner".to_string(), + repo: "repo".to_string(), + }; + assert_eq!(gh_client.check_runs(), vec![(ctx, "abc".to_string())]); +} + +#[tokio::test] +async fn processing_error_returns_internal_server_error() { + // Setup router (failing to create check runs) and signed event request + let gh_client = FakeGHClient::failing(); + let router = setup_router(gh_client.clone().into_dyn(), SECRET); + let body = MERGE_GROUP_PAYLOAD.as_bytes(); + let request = webhook_request(Some("merge_group"), Some(&sign(SECRET, body)), body); + + // Send request and check the response + assert_eq!( + send(router, request).await, + (StatusCode::INTERNAL_SERVER_ERROR, String::new()) + ); + + // Check the error came from processing the event + assert_eq!(gh_client.check_runs().len(), 1); +} + +#[tokio::test] +async fn signature_is_verified_before_parsing_event() { + // Setup router + let gh_client = FakeGHClient::new(); + let router = setup_router(gh_client.clone().into_dyn(), SECRET); + + // Send unsigned requests (unsupported event and no event header) + for event in [Some("push"), None] { + let request = webhook_request(event, None, b"{}"); + assert_eq!( + send(router.clone(), request).await, + (StatusCode::BAD_REQUEST, "no valid signature found".to_string()), + "event: {event:?}" + ); + } + + // Check no events were processed + assert!(gh_client.check_runs().is_empty()); +} + +#[test] +fn signature_with_wrong_secret_or_tampered_body_fails() { + // Check a signature generated with another secret fails + let headers = signature_headers(&sign("other-secret", BODY)); + assert!(verify_signature(SECRET.as_bytes(), &headers, BODY).is_err()); + + // Check a signature generated for another body fails + let headers = signature_headers(&sign(SECRET, BODY)); + assert!(verify_signature(SECRET.as_bytes(), &headers, br#"{"action":"other"}"#).is_err()); +} + +#[test] +fn truncated_signature_fails() { + // Check a signature missing its last byte fails + let signature = sign(SECRET, BODY); + let headers = signature_headers(&signature[..signature.len() - 2]); + assert!(verify_signature(SECRET.as_bytes(), &headers, BODY).is_err()); + + // Check an empty signature fails + let headers = signature_headers("sha256="); + assert!(verify_signature(SECRET.as_bytes(), &headers, BODY).is_err()); +} + +#[tokio::test] +async fn unsupported_event_returns_ok_without_processing() { + // Setup router and signed unsupported event request + let gh_client = FakeGHClient::new(); + let router = setup_router(gh_client.clone().into_dyn(), SECRET); + let request = webhook_request(Some("push"), Some(&sign(SECRET, b"{}")), b"{}"); + + // Send request and check the response + assert_eq!(send(router, request).await, (StatusCode::OK, String::new())); + + // Check the event was not processed + assert!(gh_client.check_runs().is_empty()); +} + +#[test] +fn valid_signature_passes() { + let headers = signature_headers(&sign(SECRET, BODY)); + assert!(verify_signature(SECRET.as_bytes(), &headers, BODY).is_ok()); +} + +#[tokio::test] +async fn webhook_with_invalid_payload_returns_bad_request() { + // Setup router and signed request with an invalid merge group payload + let gh_client = FakeGHClient::new(); + let router = setup_router(gh_client.clone().into_dyn(), SECRET); + let request = webhook_request(Some("merge_group"), Some(&sign(SECRET, b"{}")), b"{}"); + + // Send request and check the response + assert_eq!( + send(router, request).await, + (StatusCode::BAD_REQUEST, "invalid payload".to_string()) + ); + + // Check the event was not processed + assert!(gh_client.check_runs().is_empty()); +} + +// Helpers. + +/// GHClient fake that records the check runs created (context and head sha). +/// Calling any other method makes the test fail, as no other calls are +/// expected. +#[derive(Clone, Default)] +struct FakeGHClient { + /// Check runs created so far. + check_runs: Arc>>, + /// Whether creating check runs fails (after recording them). + create_check_run_fails: bool, +} + +impl FakeGHClient { + /// Create a new FakeGHClient instance. + fn new() -> Self { + Self::default() + } + + /// Get the check runs created so far. + fn check_runs(&self) -> Vec<(Ctx, String)> { + self.check_runs.lock().unwrap().clone() + } + + /// Create a new FakeGHClient instance that fails to create check runs. + fn failing() -> Self { + Self { + create_check_run_fails: true, + ..Self::default() + } + } + + /// Convert the fake into a GHClient trait object. + fn into_dyn(self) -> DynGHClient { + Arc::new(self) + } +} + +#[async_trait] +impl GHClient for FakeGHClient { + async fn add_label(&self, _ctx: &Ctx, _issue_number: i64, _name: &str) -> Result<()> { + panic!("unexpected call to add_label") + } + + async fn can_manage_labels(&self, _ctx: &Ctx) -> Result { + panic!("unexpected call to can_manage_labels") + } + + async fn compare_commits(&self, _ctx: &Ctx, _base_sha: &str, _head_sha: &str) -> Result> { + panic!("unexpected call to compare_commits") + } + + async fn create_check_run(&self, ctx: &Ctx, check_run: &CheckRun) -> Result<()> { + // Record check run + self.check_runs.lock().unwrap().push((ctx.clone(), check_run.head_sha().to_string())); + + // Fail when requested + if self.create_check_run_fails { + return Err(format_err!("fake error")); + } + Ok(()) + } + + async fn get_config(&self, _ctx: &Ctx) -> Result> { + panic!("unexpected call to get_config") + } + + async fn get_pull_request(&self, _ctx: &Ctx, _number: i64) -> Result { + panic!("unexpected call to get_pull_request") + } + + async fn is_organization_member(&self, _ctx: &Ctx, _org: &str, _login: &str) -> Result { + panic!("unexpected call to is_organization_member") + } + + async fn remove_label(&self, _ctx: &Ctx, _issue_number: i64, _name: &str) -> Result<()> { + panic!("unexpected call to remove_label") + } +} + +/// Send the request provided to the router and return the response status +/// and body. +async fn send(router: Router, request: Request) -> (StatusCode, String) { + let response = router.oneshot(request).await.unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + (status, String::from_utf8(body.to_vec()).unwrap()) +} + +/// Compute the signature header value GitHub would send for the body. +fn sign(secret: &str, body: &[u8]) -> String { + let mut mac = Hmac::::new_from_slice(secret.as_bytes()).unwrap(); + mac.update(body); + format!("sha256={}", hex::encode(mac.finalize().into_bytes())) +} + +/// Build a header map containing the signature provided. +fn signature_headers(signature: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(EVENT_SIGNATURE_HEADER, HeaderValue::from_str(signature).unwrap()); + headers +} + +/// Build a webhook request with the event, signature and body provided. +fn webhook_request(event: Option<&str>, signature: Option<&str>, body: &[u8]) -> Request { + let mut builder = Request::builder().method(Method::POST).uri("/webhook/github"); + if let Some(event) = event { + builder = builder.header(EVENT_NAME_HEADER, event); + } + if let Some(signature) = signature { + builder = builder.header(EVENT_SIGNATURE_HEADER, signature); + } + builder.body(Body::from(body.to_vec())).unwrap() +} diff --git a/dco2-server/src/lib.rs b/dco2-server/src/lib.rs index c3d4495..4970687 100644 --- a/dco2-server/src/lib.rs +++ b/dco2-server/src/lib.rs @@ -1 +1,2 @@ +pub mod env; pub mod handlers; diff --git a/dco2/Cargo.toml b/dco2/Cargo.toml index 1b62245..d89a3bc 100644 --- a/dco2/Cargo.toml +++ b/dco2/Cargo.toml @@ -29,7 +29,8 @@ tokio = { workspace = true } tracing = { workspace = true } [dev-dependencies] +axum = { workspace = true } indoc = { workspace = true } mockall = { workspace = true } pretty_assertions = { workspace = true } -tokio = { workspace = true, features = ["test-util"] } +tokio = { workspace = true, features = ["net", "test-util"] } diff --git a/dco2/src/dco/check/mod.rs b/dco2/src/dco/check/mod.rs index bc4eb9d..efe5546 100644 --- a/dco2/src/dco/check/mod.rs +++ b/dco2/src/dco/check/mod.rs @@ -15,6 +15,12 @@ mod filters; #[cfg(test)] mod tests; +/// Maximum number of commits displayed in the output summary table. +/// +/// Keeps the rendered output well below the check run summary length limit +/// enforced by GitHub, so that the sections after the table are not lost. +const MAX_SUMMARY_TABLE_COMMITS: usize = 200; + /// Check input. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub(crate) struct CheckInput { @@ -35,6 +41,63 @@ pub(crate) struct CheckOutput { pub only_last_commit_contains_errors: bool, } +impl CheckOutput { + /// Prepare the summary table displayed in the output template. + pub(crate) fn summary_table(&self) -> SummaryTable<'_> { + SummaryTable::new(&self.commits, MAX_SUMMARY_TABLE_COMMITS) + } +} + +/// Summary table displayed in the check output. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct SummaryTable<'a> { + /// Commits displayed in the table, in their original order. + pub commits: Vec<&'a CommitCheckOutput>, + /// Number of commits with errors not displayed in the table. + pub hidden_failing_commits: usize, + /// Number of commits without errors not displayed in the table. + pub hidden_passing_commits: usize, +} + +impl<'a> SummaryTable<'a> { + /// Create a new summary table displaying up to `max_commits` commits. + /// + /// Commits with errors are displayed before any commit without errors is + /// considered, so that all of them are visible whenever possible. + fn new(commits: &'a [CommitCheckOutput], max_commits: usize) -> Self { + // Decide how many failing and passing commits fit in the table + let failing_commits = commits.iter().filter(|c| !c.errors.is_empty()).count(); + let passing_commits = commits.len() - failing_commits; + let displayed_failing_commits = failing_commits.min(max_commits); + let displayed_passing_commits = passing_commits.min(max_commits - displayed_failing_commits); + + // Select the commits to display, preserving their original order + let mut failing_slots = displayed_failing_commits; + let mut passing_slots = displayed_passing_commits; + let displayed_commits = commits + .iter() + .filter(|c| { + let slots = if c.errors.is_empty() { + &mut passing_slots + } else { + &mut failing_slots + }; + let is_displayed = *slots > 0; + if is_displayed { + *slots -= 1; + } + is_displayed + }) + .collect(); + + Self { + commits: displayed_commits, + hidden_failing_commits: failing_commits - displayed_failing_commits, + hidden_passing_commits: passing_commits - displayed_passing_commits, + } + } +} + /// Commit check output. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub(crate) struct CommitCheckOutput { @@ -103,11 +166,20 @@ pub(crate) fn check(input: &CheckInput) -> CheckOutput { only_last_commit_contains_errors: false, }; - // Get remediations from all commits - let remediations = get_remediations(&input.config, &input.commits); + // Validate the emails and sign-off of each commit + let validations: Vec<_> = input.commits.iter().map(validate_signoff).collect(); + + // Get remediations from properly signed off commits only + let signed_off_commits: Vec<&Commit> = input + .commits + .iter() + .zip(&validations) + .filter_map(|(commit, validation)| validation.is_ok().then_some(commit)) + .collect(); + let remediations = get_remediations(&input.config, &signed_off_commits); // Check each commit - for commit in &input.commits { + for (commit, validation) in input.commits.iter().zip(validations) { let mut commit_output = CommitCheckOutput::new(commit.clone()); // Check if we should skip this commit @@ -118,28 +190,10 @@ pub(crate) fn check(input: &CheckInput) -> CheckOutput { continue; } - // Validate author and committer emails - let emails_are_valid = match validate_emails(commit) { - Ok(()) => true, - Err(errors) => { - commit_output.errors.extend(errors); - false - } - }; - - // Check if sign-off is present - let signoffs = get_signoffs(commit); - if signoffs.is_empty() { - commit_output.errors.push(CommitError::SignOffNotFound); - } - - // Check if any of the sign-offs matches the author's or committer's email - if emails_are_valid && !signoffs.is_empty() { - if signoffs_match(&signoffs, commit) { - commit_output.success_reason = Some(CommitSuccessReason::ValidSignOff); - } else { - commit_output.errors.push(CommitError::SignOffMismatch); - } + // Track the result of the emails and sign-off validation + match validation { + Ok(()) => commit_output.success_reason = Some(CommitSuccessReason::ValidSignOff), + Err(errors) => commit_output.errors = errors, } // Check if the sign-off is present in a remediation commit @@ -211,6 +265,26 @@ fn validate_emails(commit: &Commit) -> Result<(), Vec> { if errors.is_empty() { Ok(()) } else { Err(errors) } } +/// Validate the commit's author and committer emails and its sign-off. +/// +/// Validation passes only when the emails are valid and at least one sign-off +/// matches the author or committer. +fn validate_signoff(commit: &Commit) -> Result<(), Vec> { + // Validate author and committer emails + let mut errors = validate_emails(commit).err().unwrap_or_default(); + let emails_are_valid = errors.is_empty(); + + // Check if sign-off is present and matches the author's or committer's email + let signoffs = get_signoffs(commit); + if signoffs.is_empty() { + errors.push(CommitError::SignOffNotFound); + } else if emails_are_valid && !signoffs_match(&signoffs, commit) { + errors.push(CommitError::SignOffMismatch); + } + + if errors.is_empty() { Ok(()) } else { Err(errors) } +} + /// Validate email address. fn is_valid_email(email: &str) -> bool { // Exception for GitHub bots noreply email addresses @@ -268,13 +342,13 @@ fn signoffs_match(signoffs: &[SignOff], commit: &Commit) -> bool { /// Individual remediation regular expression. static INDIVIDUAL_REMEDIATION: LazyLock = LazyLock::new(|| { - Regex::new(r"(?mi)^I, (.*) <(.*)>, hereby add my Signed-off-by to this commit: (.*)\s*$") + Regex::new(r"(?mi)^I, (.*) <(.*)>, hereby add my Signed-off-by to this commit: (.*?)\s*$") .expect("expr in INDIVIDUAL_REMEDIATION to be valid") }); /// Third party remediation regular expression. static THIRD_PARTY_REMEDIATION: LazyLock = LazyLock::new(|| { - Regex::new(r"(?mi)^On behalf of (.*) <(.*)>, I, (.*) <(.*)>, hereby add my Signed-off-by to this commit: (.*)\s*$") + Regex::new(r"(?mi)^On behalf of (.*) <(.*)>, I, (.*) <(.*)>, hereby add my Signed-off-by to this commit: (.*?)\s*$") .expect("expr in THIRD_PARTY_REMEDIATION to be valid") }); @@ -343,8 +417,8 @@ impl Remediation { } } -/// Get remediations found in the list of commits provided. -fn get_remediations(config: &Config, commits: &[Commit]) -> Vec { +/// Get remediations found in the list of properly signed off commits provided. +fn get_remediations(config: &Config, commits: &[&Commit]) -> Vec { let mut remediations = Vec::new(); // Nothing to do if this feature isn't enabled in the config diff --git a/dco2/src/dco/check/tests.rs b/dco2/src/dco/check/tests.rs index 10e7010..cffdf64 100644 --- a/dco2/src/dco/check/tests.rs +++ b/dco2/src/dco/check/tests.rs @@ -1,10 +1,13 @@ use std::vec; +use askama::Template; use indoc::indoc; use pretty_assertions::assert_eq; use crate::{ - dco::check::{CheckInput, CheckOutput, CommitCheckOutput, CommitError, CommitSuccessReason, check}, + dco::check::{ + CheckInput, CheckOutput, CommitCheckOutput, CommitError, CommitSuccessReason, SummaryTable, check, + }, github::{Commit, Config, ConfigAllowRemediationCommits, ConfigRequire, User}, }; @@ -196,6 +199,47 @@ fn single_commit_no_signoff_author_is_member_but_the_commit_is_not_verified() { ); } +#[test] +fn single_commit_no_signoff_author_is_member_but_the_commit_verification_is_unknown() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + login: Some("user1".to_string()), + ..Default::default() + }), + verified: None, + ..Default::default() + }; + + let config = Config { + require: Some(ConfigRequire { members: Some(false) }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec!["user1".to_string()], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: true, + } + ); +} + #[test] fn single_commit_valid_signoff_author_match() { let commit1 = Commit { @@ -352,7 +396,7 @@ fn single_commit_valid_signoff_signoff_case_insensitive() { message: indoc! {r" Test commit message - signed-off-by: USER1 + signed-off-by: USER1 "} .to_string(), ..Default::default() @@ -2255,7 +2299,7 @@ fn two_commits_no_signoff_in_first_valid_remediation_commit_matching_committer_i } #[test] -fn two_commits_invalid_signoff_incorrect_name_in_first_valid_remediation_commit_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_committed_by_declarant_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2267,19 +2311,14 @@ fn two_commits_invalid_signoff_incorrect_name_in_first_valid_remediation_commit_ email: "user1@email.test".to_string(), ..Default::default() }), - message: indoc! {r" - Test commit message - - Signed-off-by: userx - "} - .to_string(), + message: "Test commit message".to_string(), sha: "sha1".to_string(), ..Default::default() }; let commit2 = Commit { author: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "user2".to_string(), + email: "user2@email.test".to_string(), ..Default::default() }), committer: Some(User { @@ -2337,44 +2376,39 @@ fn two_commits_invalid_signoff_incorrect_name_in_first_valid_remediation_commit_ } #[test] -fn two_commits_invalid_signoff_incorrect_email_in_first_valid_remediation_commit_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_case_insensitive_declarant_in_second() { let commit1 = Commit { author: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "User1".to_string(), + email: "User1@Email.Test".to_string(), ..Default::default() }), committer: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "User1".to_string(), + email: "User1@Email.Test".to_string(), ..Default::default() }), - message: indoc! {r" - Test commit message - - Signed-off-by: user1 - "} - .to_string(), + message: "Test commit message".to_string(), sha: "sha1".to_string(), ..Default::default() }; let commit2 = Commit { author: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "User1".to_string(), + email: "User1@Email.Test".to_string(), ..Default::default() }), committer: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "User1".to_string(), + email: "User1@Email.Test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - I, user1 , hereby add my Signed-off-by to this commit: sha1 + i, user1 , HEREBY add my Signed-off-by to this commit: sha1 - Signed-off-by: user1 + Signed-off-by: User1 "} .to_string(), ..Default::default() @@ -2419,7 +2453,7 @@ fn two_commits_invalid_signoff_incorrect_email_in_first_valid_remediation_commit } #[test] -fn two_commits_valid_signoff_in_first_redundant_remediation_commit_in_second() { +fn two_commits_invalid_signoff_incorrect_name_in_first_valid_remediation_commit_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2434,7 +2468,7 @@ fn two_commits_valid_signoff_in_first_redundant_remediation_commit_in_second() { message: indoc! {r" Test commit message - Signed-off-by: user1 + Signed-off-by: userx "} .to_string(), sha: "sha1".to_string(), @@ -2484,7 +2518,7 @@ fn two_commits_valid_signoff_in_first_redundant_remediation_commit_in_second() { CommitCheckOutput { commit: commit1, errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOff), + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), }, CommitCheckOutput { commit: commit2, @@ -2501,7 +2535,7 @@ fn two_commits_valid_signoff_in_first_redundant_remediation_commit_in_second() { } #[test] -fn two_commits_valid_signoff_in_first_remediation_commit_non_existent_sha_in_second() { +fn two_commits_invalid_signoff_incorrect_email_in_first_valid_remediation_commit_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2516,7 +2550,7 @@ fn two_commits_valid_signoff_in_first_remediation_commit_non_existent_sha_in_sec message: indoc! {r" Test commit message - Signed-off-by: user1 + Signed-off-by: user1 "} .to_string(), sha: "sha1".to_string(), @@ -2536,7 +2570,7 @@ fn two_commits_valid_signoff_in_first_remediation_commit_non_existent_sha_in_sec message: indoc! {r" Test commit message - I, user1 , hereby add my Signed-off-by to this commit: non-existent + I, user1 , hereby add my Signed-off-by to this commit: sha1 Signed-off-by: user1 "} @@ -2566,7 +2600,7 @@ fn two_commits_valid_signoff_in_first_remediation_commit_non_existent_sha_in_sec CommitCheckOutput { commit: commit1, errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOff), + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), }, CommitCheckOutput { commit: commit2, @@ -2583,7 +2617,7 @@ fn two_commits_valid_signoff_in_first_remediation_commit_non_existent_sha_in_sec } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_no_signoff_in_second() { +fn two_commits_valid_signoff_in_first_redundant_remediation_commit_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2595,7 +2629,12 @@ fn two_commits_no_signoff_in_first_remediation_commit_no_signoff_in_second() { email: "user1@email.test".to_string(), ..Default::default() }), - message: "Test commit message".to_string(), + message: indoc! {r" + Test commit message + + Signed-off-by: user1 + "} + .to_string(), sha: "sha1".to_string(), ..Default::default() }; @@ -2614,6 +2653,8 @@ fn two_commits_no_signoff_in_first_remediation_commit_no_signoff_in_second() { Test commit message I, user1 , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user1 "} .to_string(), ..Default::default() @@ -2641,24 +2682,24 @@ fn two_commits_no_signoff_in_first_remediation_commit_no_signoff_in_second() { CommitCheckOutput { commit: commit1, errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + success_reason: Some(CommitSuccessReason::ValidSignOff), }, CommitCheckOutput { commit: commit2, - errors: vec![CommitError::SignOffNotFound], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), } ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, - only_last_commit_contains_errors: true, + num_commits_with_errors: 0, + only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_second() { +fn two_commits_valid_signoff_in_first_remediation_commit_non_existent_sha_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2670,27 +2711,32 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_second() email: "user1@email.test".to_string(), ..Default::default() }), - message: "Test commit message".to_string(), + message: indoc! {r" + Test commit message + + Signed-off-by: user1 + "} + .to_string(), sha: "sha1".to_string(), ..Default::default() }; let commit2 = Commit { author: Some(User { - name: "userx".to_string(), + name: "user1".to_string(), email: "user1@email.test".to_string(), ..Default::default() }), committer: Some(User { - name: "userx".to_string(), + name: "user1".to_string(), email: "user1@email.test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - I, userx , hereby add my Signed-off-by to this commit: sha1 + I, user1 , hereby add my Signed-off-by to this commit: non-existent - Signed-off-by: userx + Signed-off-by: user1 "} .to_string(), ..Default::default() @@ -2717,8 +2763,8 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_second() commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![CommitError::SignOffNotFound], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), }, CommitCheckOutput { commit: commit2, @@ -2728,14 +2774,14 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_second() ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, + num_commits_with_errors: 0, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_no_signoff_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2754,20 +2800,18 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_second( let commit2 = Commit { author: Some(User { name: "user1".to_string(), - email: "userx@email.test".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), committer: Some(User { name: "user1".to_string(), - email: "userx@email.test".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - I, user1 , hereby add my Signed-off-by to this commit: sha1 - - Signed-off-by: user1 + I, user1 , hereby add my Signed-off-by to this commit: sha1 "} .to_string(), ..Default::default() @@ -2799,20 +2843,20 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_second( }, CommitCheckOutput { commit: commit2, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOff), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, } ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, + num_commits_with_errors: 2, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_in_second() { +fn two_commits_no_signoff_in_first_remediation_merge_commit_no_signoff_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2830,21 +2874,20 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_i }; let commit2 = Commit { author: Some(User { - name: "userx".to_string(), - email: "userx@email.test".to_string(), + name: "user1".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), committer: Some(User { - name: "userx".to_string(), - email: "userx@email.test".to_string(), + name: "user1".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), + is_merge: true, message: indoc! {r" - Test commit message - - I, userx , hereby add my Signed-off-by to this commit: sha1 + Merge branch 'main' into feature - Signed-off-by: userx + I, user1 , hereby add my Signed-off-by to this commit: sha1 "} .to_string(), ..Default::default() @@ -2877,7 +2920,7 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_i CommitCheckOutput { commit: commit2, errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOff), + success_reason: Some(CommitSuccessReason::IsMerge), } ], config, @@ -2889,7 +2932,7 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_i } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_signoff_in_second() { +fn two_commits_no_signoff_in_first_valid_remediation_merge_commit_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2916,12 +2959,13 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_signoff_ email: "user1@email.test".to_string(), ..Default::default() }), + is_merge: true, message: indoc! {r" - Test commit message + Merge branch 'main' into feature I, user1 , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: userx + Signed-off-by: user1 "} .to_string(), ..Default::default() @@ -2953,20 +2997,20 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_signoff_ }, CommitCheckOutput { commit: commit2, - errors: vec![CommitError::SignOffMismatch], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::IsMerge), } ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, - only_last_commit_contains_errors: true, + num_commits_with_errors: 0, + only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_signoff_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -2984,21 +3028,21 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_signoff }; let commit2 = Commit { author: Some(User { - name: "user1".to_string(), + name: "userx".to_string(), email: "user1@email.test".to_string(), ..Default::default() }), committer: Some(User { - name: "user1".to_string(), + name: "userx".to_string(), email: "user1@email.test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - I, user1 , hereby add my Signed-off-by to this commit: sha1 + I, userx , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: user1 + Signed-off-by: userx "} .to_string(), ..Default::default() @@ -3025,25 +3069,25 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_signoff commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, - errors: vec![CommitError::SignOffMismatch], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), } ], config, head_ref: "main".to_string(), num_commits_with_errors: 1, - only_last_commit_contains_errors: true, + only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_in_signoff_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3062,20 +3106,20 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_i let commit2 = Commit { author: Some(User { name: "user1".to_string(), - email: "user1@email.test".to_string(), + email: "userx@email.test".to_string(), ..Default::default() }), committer: Some(User { name: "user1".to_string(), - email: "user1@email.test".to_string(), + email: "userx@email.test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - I, user1 , hereby add my Signed-off-by to this commit: sha1 + I, user1 , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: userx + Signed-off-by: user1 "} .to_string(), ..Default::default() @@ -3102,25 +3146,25 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_i commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, - errors: vec![CommitError::SignOffMismatch], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), } ], config, head_ref: "main".to_string(), num_commits_with_errors: 1, - only_last_commit_contains_errors: true, + only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_remediation_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3138,21 +3182,21 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_remediat }; let commit2 = Commit { author: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "userx".to_string(), + email: "userx@email.test".to_string(), ..Default::default() }), committer: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "userx".to_string(), + email: "userx@email.test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - I, userx , hereby add my Signed-off-by to this commit: sha1 + I, userx , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: user1 + Signed-off-by: userx "} .to_string(), ..Default::default() @@ -3197,7 +3241,7 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_remediat } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_remediation_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_signoff_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3227,9 +3271,9 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_remedia message: indoc! {r" Test commit message - I, user1 , hereby add my Signed-off-by to this commit: sha1 + I, user1 , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: user1 + Signed-off-by: userx "} .to_string(), ..Default::default() @@ -3261,20 +3305,20 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_remedia }, CommitCheckOutput { commit: commit2, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOff), + errors: vec![CommitError::SignOffMismatch], + success_reason: None, } ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, + num_commits_with_errors: 2, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_in_remediation_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_signoff_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3304,9 +3348,9 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_i message: indoc! {r" Test commit message - I, userx , hereby add my Signed-off-by to this commit: sha1 + I, user1 , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: user1 + Signed-off-by: user1 "} .to_string(), ..Default::default() @@ -3338,20 +3382,20 @@ fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_i }, CommitCheckOutput { commit: commit2, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOff), + errors: vec![CommitError::SignOffMismatch], + success_reason: None, } ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, + num_commits_with_errors: 2, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_remediation_commit_sha_mismatch_in_second() { +fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_in_signoff_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3381,9 +3425,9 @@ fn two_commits_no_signoff_in_first_remediation_commit_sha_mismatch_in_second() { message: indoc! {r" Test commit message - I, user1 , hereby add my Signed-off-by to this commit: sha2 + I, user1 , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: user1 + Signed-off-by: userx "} .to_string(), ..Default::default() @@ -3415,11 +3459,698 @@ fn two_commits_no_signoff_in_first_remediation_commit_sha_mismatch_in_second() { }, CommitCheckOutput { commit: commit2, - errors: vec![], + errors: vec![CommitError::SignOffMismatch], + success_reason: None, + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 2, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_remediation_commit_different_name_in_remediation_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + I, userx , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user1 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_remediation_commit_different_email_in_remediation_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + I, user1 , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user1 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_remediation_commit_different_name_and_email_in_remediation_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + I, userx , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user1 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_remediation_commit_from_different_author_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + I, user1 , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user2 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_remediation_commit_sha_mismatch_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + I, user1 , hereby add my Signed-off-by to this commit: sha2 + + Signed-off-by: user1 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_remediation_commit_abbreviated_sha_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "1111111111abcdef".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + I, user1 , hereby add my Signed-off-by to this commit: 1111111 + + Signed-off-by: user1 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_remediation_commit_with_trailing_whitespace_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: concat!( + "Test commit message\n", + "\n", + "I, user1 , hereby add my Signed-off-by to this commit: sha1 \n", + "\n", + "Signed-off-by: user1 \n", + ) + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 0, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_remediation_commit_with_crlf_line_endings_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + I, user1 , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user1 + "} + .replace('\n', "\r\n"), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 0, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_remediation_not_enabled_in_config() + { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + On behalf of user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user2 + "} + .to_string(), + ..Default::default() + }; + + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: Default::default(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], success_reason: Some(CommitSuccessReason::ValidSignOff), } ], - config, + config: Default::default(), head_ref: "main".to_string(), num_commits_with_errors: 1, only_last_commit_contains_errors: false, @@ -3428,7 +4159,7 @@ fn two_commits_no_signoff_in_first_remediation_commit_sha_mismatch_in_second() { } #[test] -fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_remediation_not_enabled_in_config() +fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_3p_remediation_not_enabled_in_config() { let commit1 = Commit { author: Some(User { @@ -3467,9 +4198,248 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_rem ..Default::default() }; + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + ..Default::default() + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![CommitError::SignOffNotFound], + success_reason: None, + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_same_author_and_committer_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user1 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + third_party: Some(true), + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 0, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_different_author_and_committer_in_second() +{ + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + On behalf of user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user2 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + third_party: Some(true), + }), + ..Default::default() + }; + let input = CheckInput { + commits: vec![commit1.clone(), commit2.clone()], + config: config.clone(), + head_ref: "main".to_string(), + members: vec![], + }; + let output = check(&input); + + assert_eq!( + output, + CheckOutput { + commits: vec![ + CommitCheckOutput { + commit: commit1, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + }, + CommitCheckOutput { + commit: commit2, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOff), + } + ], + config, + head_ref: "main".to_string(), + num_commits_with_errors: 0, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_committer_in_second() { + let commit1 = Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + message: "Test commit message".to_string(), + sha: "sha1".to_string(), + ..Default::default() + }; + let commit2 = Commit { + author: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + committer: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + ..Default::default() + }), + message: indoc! {r" + Test commit message + + On behalf of user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 + + Signed-off-by: user2 + "} + .to_string(), + ..Default::default() + }; + + let config = Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(true), + third_party: Some(true), + }), + ..Default::default() + }; let input = CheckInput { commits: vec![commit1.clone(), commit2.clone()], - config: Default::default(), + config: config.clone(), head_ref: "main".to_string(), members: vec![], }; @@ -3481,8 +4451,8 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_rem commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![CommitError::SignOffNotFound], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), }, CommitCheckOutput { commit: commit2, @@ -3490,26 +4460,25 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_rem success_reason: Some(CommitSuccessReason::ValidSignOff), } ], - config: Default::default(), + config, head_ref: "main".to_string(), - num_commits_with_errors: 1, + num_commits_with_errors: 0, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_3p_remediation_not_enabled_in_config() - { +fn two_commits_no_signoff_in_first_3p_remediation_commit_case_insensitive_in_second() { let commit1 = Commit { author: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "User1".to_string(), + email: "User1@Email.Test".to_string(), ..Default::default() }), committer: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "User1".to_string(), + email: "User1@Email.Test".to_string(), ..Default::default() }), message: "Test commit message".to_string(), @@ -3518,21 +4487,21 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_3p_ }; let commit2 = Commit { author: Some(User { - name: "user2".to_string(), - email: "user2@email.test".to_string(), + name: "User2".to_string(), + email: "User2@Email.Test".to_string(), ..Default::default() }), committer: Some(User { - name: "user2".to_string(), - email: "user2@email.test".to_string(), + name: "User2".to_string(), + email: "User2@Email.Test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - On behalf of user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 + on behalf of user1 , i, user2 , HEREBY add my Signed-off-by to this commit: sha1 - Signed-off-by: user2 + Signed-off-by: User2 "} .to_string(), ..Default::default() @@ -3541,7 +4510,7 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_3p_ let config = Config { allow_remediation_commits: Some(ConfigAllowRemediationCommits { individual: Some(true), - ..Default::default() + third_party: Some(true), }), ..Default::default() }; @@ -3559,8 +4528,8 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_3p_ commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![CommitError::SignOffNotFound], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), }, CommitCheckOutput { commit: commit2, @@ -3570,14 +4539,14 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_but_3p_ ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, + num_commits_with_errors: 0, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_same_author_and_committer_in_second() { +fn two_commits_no_signoff_in_first_3p_remediation_commit_committed_by_representative_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3595,21 +4564,21 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_same_author_ }; let commit2 = Commit { author: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "user3".to_string(), + email: "user3@email.test".to_string(), ..Default::default() }), committer: Some(User { - name: "user1".to_string(), - email: "user1@email.test".to_string(), + name: "user2".to_string(), + email: "user2@email.test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 + On behalf of user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: user1 + Signed-off-by: user2 "} .to_string(), ..Default::default() @@ -3654,8 +4623,7 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_same_author_ } #[test] -fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_different_author_and_committer_in_second() -{ +fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_individual_remediations_disabled() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3673,21 +4641,21 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_different_au }; let commit2 = Commit { author: Some(User { - name: "user2".to_string(), - email: "user2@email.test".to_string(), + name: "user1".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), committer: Some(User { - name: "user2".to_string(), - email: "user2@email.test".to_string(), + name: "user1".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - On behalf of user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 + On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: user2 + Signed-off-by: user1 "} .to_string(), ..Default::default() @@ -3695,7 +4663,7 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_different_au let config = Config { allow_remediation_commits: Some(ConfigAllowRemediationCommits { - individual: Some(true), + individual: Some(false), third_party: Some(true), }), ..Default::default() @@ -3714,8 +4682,8 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_different_au commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, @@ -3725,14 +4693,14 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_different_au ], config, head_ref: "main".to_string(), - num_commits_with_errors: 0, + num_commits_with_errors: 1, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_committer_in_second() { +fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_name_mismatch_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3740,8 +4708,8 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_committer_in ..Default::default() }), committer: Some(User { - name: "user2".to_string(), - email: "user2@email.test".to_string(), + name: "user1".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), message: "Test commit message".to_string(), @@ -3750,21 +4718,21 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_committer_in }; let commit2 = Commit { author: Some(User { - name: "user2".to_string(), - email: "user2@email.test".to_string(), + name: "user1".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), committer: Some(User { - name: "user2".to_string(), - email: "user2@email.test".to_string(), + name: "user1".to_string(), + email: "user1@email.test".to_string(), ..Default::default() }), message: indoc! {r" Test commit message - On behalf of user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 + On behalf of user2 , I, user1 , hereby add my Signed-off-by to this commit: sha1 - Signed-off-by: user2 + Signed-off-by: user1 "} .to_string(), ..Default::default() @@ -3791,8 +4759,8 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_committer_in commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, @@ -3802,14 +4770,14 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_from_committer_in ], config, head_ref: "main".to_string(), - num_commits_with_errors: 0, + num_commits_with_errors: 1, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_individual_remediations_disabled() { +fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_email_mismatch_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3839,7 +4807,7 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_individ message: indoc! {r" Test commit message - On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 + On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 Signed-off-by: user1 "} @@ -3849,7 +4817,7 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_individ let config = Config { allow_remediation_commits: Some(ConfigAllowRemediationCommits { - individual: Some(false), + individual: Some(true), third_party: Some(true), }), ..Default::default() @@ -3886,7 +4854,7 @@ fn two_commits_no_signoff_in_first_3p_valid_remediation_commit_in_second_individ } #[test] -fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_name_mismatch_in_second() { +fn two_commits_no_signoff_in_first_3p_remediation_commit_sha_mismatch_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3916,7 +4884,7 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_name_mismatch message: indoc! {r" Test commit message - On behalf of user2 , I, user1 , hereby add my Signed-off-by to this commit: sha1 + On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha2 Signed-off-by: user1 "} @@ -3963,7 +4931,7 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_name_mismatch } #[test] -fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_email_mismatch_in_second() { +fn two_commits_no_signoff_in_first_3p_remediation_commit_with_trailing_whitespace_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -3990,13 +4958,13 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_email_mismatc email: "user1@email.test".to_string(), ..Default::default() }), - message: indoc! {r" - Test commit message - - On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 - - Signed-off-by: user1 - "} + message: concat!( + "Test commit message\n", + "\n", + "On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 \n", + "\n", + "Signed-off-by: user1 \n", + ) .to_string(), ..Default::default() }; @@ -4022,8 +4990,8 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_email_mismatc commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![CommitError::SignOffNotFound], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), }, CommitCheckOutput { commit: commit2, @@ -4033,14 +5001,14 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_declarant_email_mismatc ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, + num_commits_with_errors: 0, only_last_commit_contains_errors: false, } ); } #[test] -fn two_commits_no_signoff_in_first_3p_remediation_commit_sha_mismatch_in_second() { +fn two_commits_no_signoff_in_first_3p_remediation_commit_with_crlf_line_endings_in_second() { let commit1 = Commit { author: Some(User { name: "user1".to_string(), @@ -4070,11 +5038,11 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_sha_mismatch_in_second( message: indoc! {r" Test commit message - On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha2 + On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 Signed-off-by: user1 "} - .to_string(), + .replace('\n', "\r\n"), ..Default::default() }; @@ -4099,8 +5067,8 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_sha_mismatch_in_second( commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![CommitError::SignOffNotFound], - success_reason: None, + errors: vec![], + success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), }, CommitCheckOutput { commit: commit2, @@ -4110,7 +5078,7 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_sha_mismatch_in_second( ], config, head_ref: "main".to_string(), - num_commits_with_errors: 1, + num_commits_with_errors: 0, only_last_commit_contains_errors: false, } ); @@ -4224,7 +5192,7 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_representative_name_mis message: indoc! {r" Test commit message - For user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 + On behalf of user1 , I, user2 , hereby add my Signed-off-by to this commit: sha1 Signed-off-by: user1 "} @@ -4301,7 +5269,7 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_representative_email_mi message: indoc! {r" Test commit message - For user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 + On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 Signed-off-by: user1 "} @@ -4378,7 +5346,7 @@ fn two_commits_no_signoff_in_first_3p_remediation_commit_no_signoff_in_second() message: indoc! {r" Test commit message - For user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 + On behalf of user1 , I, user1 , hereby add my Signed-off-by to this commit: sha1 "} .to_string(), ..Default::default() @@ -4805,8 +5773,8 @@ fn three_commits_no_signoff_in_first_remediation_commit_without_signoff_in_secon commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, @@ -4821,7 +5789,7 @@ fn three_commits_no_signoff_in_first_remediation_commit_without_signoff_in_secon ], config, head_ref: "main".to_string(), - num_commits_with_errors: 0, + num_commits_with_errors: 1, only_last_commit_contains_errors: false, } ); @@ -5221,8 +6189,8 @@ fn three_commits_no_signoff_in_first_remediation_commit_no_signoff_in_second_val commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, @@ -5237,7 +6205,7 @@ fn three_commits_no_signoff_in_first_remediation_commit_no_signoff_in_second_val ], config, head_ref: "main".to_string(), - num_commits_with_errors: 0, + num_commits_with_errors: 1, only_last_commit_contains_errors: false, } ); @@ -5324,8 +6292,8 @@ fn three_commits_no_signoff_in_first_3p_remediation_commit_no_signoff_in_second_ commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, @@ -5340,7 +6308,7 @@ fn three_commits_no_signoff_in_first_3p_remediation_commit_no_signoff_in_second_ ], config, head_ref: "main".to_string(), - num_commits_with_errors: 0, + num_commits_with_errors: 1, only_last_commit_contains_errors: false, } ); @@ -5427,8 +6395,8 @@ fn three_commits_no_signoff_in_first_3p_remediation_commit_no_signoff_in_second_ commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, @@ -5443,7 +6411,7 @@ fn three_commits_no_signoff_in_first_3p_remediation_commit_no_signoff_in_second_ ], config, head_ref: "main".to_string(), - num_commits_with_errors: 0, + num_commits_with_errors: 1, only_last_commit_contains_errors: false, } ); @@ -5528,13 +6496,13 @@ fn three_commits_no_signoff_in_first_3p_remediation_commit_no_signoff_in_second_ commits: vec![ CommitCheckOutput { commit: commit1, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit2, - errors: vec![], - success_reason: Some(CommitSuccessReason::ValidSignOffInRemediationCommit), + errors: vec![CommitError::SignOffNotFound], + success_reason: None, }, CommitCheckOutput { commit: commit3, @@ -5544,8 +6512,471 @@ fn three_commits_no_signoff_in_first_3p_remediation_commit_no_signoff_in_second_ ], config, head_ref: "main".to_string(), + num_commits_with_errors: 3, + only_last_commit_contains_errors: false, + } + ); +} + +#[test] +fn output_check_passed_renders_summary_table() { + // Setup a passing check output with a long commit subject + let mut commit2_output = render_commit_output( + "fedcba9876543210", + "This is a very long commit subject that exceeds fifty characters", + vec![], + ); + commit2_output.success_reason = Some(CommitSuccessReason::ValidSignOffInRemediationCommit); + let output = CheckOutput { + commits: vec![ + render_commit_output( + "0123456789abcdef", + "Test commit message\n\nSigned-off-by: user1 ", + vec![], + ), + commit2_output, + ], + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 0, + only_last_commit_contains_errors: false, + }; + + // Check the whole rendered output + assert_eq!( + output.render().unwrap(), + indoc! {r" + All commits are signed off, the check **passed**. + ## Summary + +
+ + | | Sha | Message | Pass or fail reason | + | -- | ---- | :---- | :---- | + | :green_circle: | [0123456](https://github.com/org/repo/commit/0123456789abcdef) |Test commit message|`Valid sign-off found`| + | :green_circle: | [fedcba9](https://github.com/org/repo/commit/fedcba9876543210) |This is a very long commit subject that exceeds fi...|`Valid sign-off found in remediation commit`| + + "} + ); +} + +#[test] +fn output_errors_details_include_each_error_found_once() { + // Setup a check output where two commits share the same error + let output = CheckOutput { + commits: vec![ + render_commit_output( + "0123456789abcdef", + "Test commit message", + vec![CommitError::InvalidCommitterEmail, CommitError::SignOffNotFound], + ), + render_commit_output( + "fedcba9876543210", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + ], + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 2, + only_last_commit_contains_errors: false, + }; + + // Render the output + let rendered = output.render().unwrap(); + + // Check only the errors found are detailed, once each + assert_eq!(rendered.matches("## Errors details").count(), 1); + assert_eq!(rendered.matches("### Invalid committer email").count(), 1); + assert_eq!(rendered.matches("### Sign-off not found").count(), 1); + assert!(!rendered.contains("### Invalid author email")); + assert!(!rendered.contains("### No sign-off matches the author or committer")); +} + +#[test] +fn output_errors_details_without_how_to_fix_for_email_errors_only() { + // Setup a check output with an email error only + let output = CheckOutput { + commits: vec![render_commit_output( + "0123456789abcdef", + "Test commit message", + vec![CommitError::InvalidAuthorEmail], + )], + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: true, + }; + + // Render the output + let rendered = output.render().unwrap(); + + // Check the error is detailed without sign-off fixing instructions + assert!(rendered.contains("|`Invalid author email`|")); + assert!(rendered.contains("### Invalid author email")); + assert!(!rendered.contains("## How to fix")); +} + +#[test] +fn output_headline_counts_failing_commits() { + // Check the headline when the only commit fails + let output = CheckOutput { + commits: vec![render_commit_output( + "0123456789abcdef", + "Test commit message", + vec![CommitError::SignOffNotFound], + )], + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: true, + }; + let rendered = output.render().unwrap(); + assert!( + rendered.starts_with("**All commits** are incorrectly signed off, the check **did not pass**.\n") + ); + + // Check the headline when one of several commits fails + let output = CheckOutput { + commits: vec![ + render_commit_output("0123456789abcdef", "Test commit message", vec![]), + render_commit_output( + "fedcba9876543210", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + ], + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: true, + }; + let rendered = output.render().unwrap(); + assert!( + rendered.starts_with("There is **one commit** incorrectly signed off, the check **did not pass**.\n") + ); + + // Check the headline and summary rows when some commits fail + let output = CheckOutput { + commits: vec![ + render_commit_output( + "0123456789abcdef", + "Test commit message", + vec![CommitError::InvalidAuthorEmail, CommitError::SignOffNotFound], + ), + render_commit_output( + "fedcba9876543210", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + render_commit_output("abcdef0123456789", "Test commit message", vec![]), + ], + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 2, + only_last_commit_contains_errors: false, + }; + let rendered = output.render().unwrap(); + assert!( + rendered.starts_with("There are **2 commits** incorrectly signed off, the check **did not pass**.\n") + ); + assert!(rendered.contains(indoc! {r" + | :red_circle: | [0123456](https://github.com/org/repo/commit/0123456789abcdef) |Test commit message|`Invalid author email` `Sign-off not found`| + | :red_circle: | [fedcba9](https://github.com/org/repo/commit/fedcba9876543210) |Test commit message|`Sign-off not found`| + | :green_circle: | [abcdef0](https://github.com/org/repo/commit/abcdef0123456789) |Test commit message|`Valid sign-off found`| + "})); +} + +#[test] +fn output_how_to_fix_amend_last_commit_when_only_last_commit_fails() { + // Setup a check output where only the last commit fails + let output = CheckOutput { + commits: vec![ + render_commit_output("0123456789abcdef", "Test commit message", vec![]), + render_commit_output( + "fedcba9876543210", + "Test commit message", + vec![CommitError::SignOffMismatch], + ), + ], + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: true, + }; + + // Render the output + let rendered = output.render().unwrap(); + + // Check the instructions amend the last commit and push the head ref + assert!(rendered.contains("## How to fix missing or invalid sign-offs")); + assert!(rendered.contains("#### Amend last commit")); + assert!(rendered.contains("`git commit --amend --signoff`")); + assert!(rendered.contains("`git push --force-with-lease origin feature`")); + assert!(!rendered.contains("#### Rebase the branch")); +} + +#[test] +fn output_how_to_fix_rebase_branch_when_not_only_last_commit_fails() { + // Setup a check output where a commit other than the last one fails + let output = CheckOutput { + commits: vec![ + render_commit_output( + "0123456789abcdef", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + render_commit_output("fedcba9876543210", "Test commit message", vec![]), + render_commit_output("abcdef0123456789", "Test commit message", vec![]), + ], + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + }; + + // Render the output + let rendered = output.render().unwrap(); + + // Check the instructions rebase all commits and push the head ref + assert!(rendered.contains("## How to fix missing or invalid sign-offs")); + assert!(rendered.contains("#### Rebase the branch")); + assert!(rendered.contains("`git rebase HEAD~3 --signoff`")); + assert!(rendered.contains("`git push --force-with-lease origin feature`")); + assert!(!rendered.contains("#### Amend last commit")); +} + +#[test] +fn output_how_to_fix_remediation_options_depend_on_config() { + // Setup the expected snippets and a renderer for each remediation config + let not_allowed = "Remediation commits are not allowed for this repository"; + let individual_link = "https://github.com/cncf/dco2?tab=readme-ov-file#individual"; + let third_party_link = "https://github.com/cncf/dco2?tab=readme-ov-file#third-party"; + let render = |individual: bool, third_party: bool| { + CheckOutput { + commits: vec![render_commit_output( + "0123456789abcdef", + "Test commit message", + vec![CommitError::SignOffNotFound], + )], + config: Config { + allow_remediation_commits: Some(ConfigAllowRemediationCommits { + individual: Some(individual), + third_party: Some(third_party), + }), + ..Default::default() + }, + head_ref: "feature".to_string(), num_commits_with_errors: 1, only_last_commit_contains_errors: true, } + .render() + .unwrap() + }; + + // Remediation commits disabled + let rendered = render(false, false); + assert!(rendered.contains(not_allowed)); + assert!(!rendered.contains(individual_link)); + assert!(!rendered.contains(third_party_link)); + + // Third-party remediation commits require individual ones to be enabled + let rendered = render(false, true); + assert!(rendered.contains(not_allowed)); + assert!(!rendered.contains(individual_link)); + assert!(!rendered.contains(third_party_link)); + + // Only individual remediation commits enabled + let rendered = render(true, false); + assert!(!rendered.contains(not_allowed)); + assert!(rendered.contains(individual_link)); + assert!(!rendered.contains(third_party_link)); + + // Individual and third-party remediation commits enabled + let rendered = render(true, true); + assert!(!rendered.contains(not_allowed)); + assert!(rendered.contains(individual_link)); + assert!(rendered.contains(third_party_link)); +} + +#[test] +fn output_summary_table_lists_commits_not_displayed() { + // Setup a check output with more commits than the summary table displays + let mut commits: Vec<_> = (0..998) + .map(|i| render_commit_output(&format!("{i:040x}"), "Test commit message", vec![])) + .collect(); + commits.push(render_commit_output( + "fedcba9876543210", + "Failing commit message", + vec![CommitError::SignOffNotFound], + )); + commits.push(render_commit_output( + "abcdef0123456789", + "Test commit message", + vec![], + )); + let output = CheckOutput { + commits, + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: 1, + only_last_commit_contains_errors: false, + }; + + // Render the output + let rendered = output.render().unwrap(); + + // Check the table is limited and the failing commit is displayed + assert_eq!(rendered.matches("| :green_circle: |").count(), 199); + assert_eq!(rendered.matches("| :red_circle: |").count(), 1); + assert!(rendered.contains( + "| :red_circle: | [fedcba9](https://github.com/org/repo/commit/fedcba9876543210) |Failing commit message|`Sign-off not found`|" + )); + assert!(!rendered.contains("[abcdef0]")); + + // Check the commits not displayed are reported after the table + assert!(rendered.contains("|\n\nShowing 200 of 1000 commits (not displayed: 800 passing).\n\n## Errors")); + + // Check the fixing instructions are rendered for the whole branch + assert!(rendered.contains("## Errors details")); + assert!(rendered.contains("`git rebase HEAD~1000 --signoff`")); +} + +#[test] +fn output_summary_table_lists_failing_commits_not_displayed() { + // Setup a renderer for outputs with the given failing and passing commits + let render = |failing: usize, passing: usize| { + let failing_commits = (0..failing).map(|i| { + render_commit_output( + &format!("{i:040x}"), + "Test commit message", + vec![CommitError::SignOffNotFound], + ) + }); + let passing_commits = (failing..failing + passing) + .map(|i| render_commit_output(&format!("{i:040x}"), "Test commit message", vec![])); + CheckOutput { + commits: failing_commits.chain(passing_commits).collect(), + config: Default::default(), + head_ref: "feature".to_string(), + num_commits_with_errors: failing, + only_last_commit_contains_errors: false, + } + .render() + .unwrap() + }; + + // Only failing commits not displayed + let rendered = render(201, 0); + assert_eq!(rendered.matches("| :red_circle: |").count(), 200); + assert!(rendered.contains("Showing 200 of 201 commits (not displayed: 1 failing).\n")); + + // Failing and passing commits not displayed + let rendered = render(250, 3); + assert_eq!(rendered.matches("| :red_circle: |").count(), 200); + assert!(!rendered.contains("| :green_circle: |")); + assert!(rendered.contains("Showing 200 of 253 commits (not displayed: 50 failing, 3 passing).\n")); +} + +#[test] +fn summary_table_displays_all_commits_below_limit() { + // Setup commits below the limit + let commits = vec![ + render_commit_output("0123456789abcdef", "Test commit message", vec![]), + render_commit_output( + "fedcba9876543210", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + ]; + + // Check all commits are displayed + assert_eq!( + SummaryTable::new(&commits, 2), + SummaryTable { + commits: vec![&commits[0], &commits[1]], + hidden_failing_commits: 0, + hidden_passing_commits: 0, + } + ); +} + +#[test] +fn summary_table_displays_failing_commits_first() { + // Setup failing commits interleaved with passing ones + let commits = vec![ + render_commit_output("0000000000000000", "Test commit message", vec![]), + render_commit_output( + "1111111111111111", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + render_commit_output("2222222222222222", "Test commit message", vec![]), + render_commit_output( + "3333333333333333", + "Test commit message", + vec![CommitError::SignOffMismatch], + ), + render_commit_output("4444444444444444", "Test commit message", vec![]), + ]; + + // Check failing commits fill the table first, preserving the original order + assert_eq!( + SummaryTable::new(&commits, 3), + SummaryTable { + commits: vec![&commits[0], &commits[1], &commits[3]], + hidden_failing_commits: 0, + hidden_passing_commits: 2, + } ); } + +#[test] +fn summary_table_limits_failing_commits_above_limit() { + // Setup more failing commits than the limit + let commits = vec![ + render_commit_output( + "0000000000000000", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + render_commit_output("1111111111111111", "Test commit message", vec![]), + render_commit_output( + "2222222222222222", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + render_commit_output( + "3333333333333333", + "Test commit message", + vec![CommitError::SignOffNotFound], + ), + ]; + + // Check only the first failing commits are displayed + assert_eq!( + SummaryTable::new(&commits, 2), + SummaryTable { + commits: vec![&commits[0], &commits[2]], + hidden_failing_commits: 1, + hidden_passing_commits: 1, + } + ); +} + +// Helpers. + +/// Create a commit check output to be used in the output render tests. +fn render_commit_output(sha: &str, message: &str, errors: Vec) -> CommitCheckOutput { + let success_reason = errors.is_empty().then_some(CommitSuccessReason::ValidSignOff); + CommitCheckOutput { + commit: Commit { + html_url: format!("https://github.com/org/repo/commit/{sha}"), + message: message.to_string(), + sha: sha.to_string(), + ..Default::default() + }, + errors, + success_reason, + } +} diff --git a/dco2/src/dco/event/mod.rs b/dco2/src/dco/event/mod.rs index 6a6be5c..0ac41df 100644 --- a/dco2/src/dco/event/mod.rs +++ b/dco2/src/dco/event/mod.rs @@ -17,7 +17,7 @@ use crate::{ CheckRun, CheckRunAction, CheckRunConclusion, CheckRunEvent, CheckRunEventAction, CheckRunStatus, Commit, Config, Ctx, DynGHClient, Event, LabelsPermissionError, MergeGroupEvent, MergeGroupEventAction, NewCheckRunInput, PullRequestEvent, PullRequestEventAction, PullRequestLabel, - is_rate_limit_error, + TooManyCommitsError, is_rate_limit_error, }, }; @@ -183,11 +183,18 @@ async fn process_pull_request_event(gh_client: DynGHClient, event: &PullRequestE return Ok(()); } - // Get pull request commits - let commits: Vec = gh_client + // Get pull request commits (the check can't be run when there are too + // many of them) + let commits = match gh_client .compare_commits(&ctx, &event.pull_request.base.sha, &event.pull_request.head.sha) .await - .context("error getting pull request commits")?; + { + Ok(commits) => Ok(commits), + Err(err) => match too_many_commits_error(&err) { + Some(too_many_commits_err) => Err(too_many_commits_err.clone()), + None => return Err(err).context("error getting pull request commits"), + }, + }; // Get repository configuration let config = gh_client @@ -196,29 +203,44 @@ async fn process_pull_request_event(gh_client: DynGHClient, event: &PullRequestE .context("error getting repository configuration")? .unwrap_or_default(); - // Create a list of members that are not required to sign-off commits - let mut members = vec![]; - if !config.members_signoff_is_required() { - members = collect_members(gh_client.clone(), event, &commits) - .await - .context("error collecting members")? - }; + // Run DCO check (it fails when there are too many commits to check) + let (check_failed, summary) = match commits { + Ok(commits) => { + // Create a list of members that are not required to sign-off commits + let mut members = vec![]; + if !config.members_signoff_is_required() { + members = collect_members(gh_client.clone(), event, &commits) + .await + .context("error collecting members")? + }; - // Run DCO check - let input = CheckInput { - commits, - config, - head_ref: event.pull_request.head.ref_.clone(), - members, + // Check the commits and render the output + let input = CheckInput { + commits, + config: config.clone(), + head_ref: event.pull_request.head.ref_.clone(), + members, + }; + let output = check(&input); + let summary = output.render().context("error rendering output template")?; + (output.num_commits_with_errors > 0, summary) + } + Err(err) => { + info!( + owner = %ctx.owner, + repo = %ctx.repo, + pr_number = event.number, + "too many commits in pull request, check not run" + ); + (true, too_many_commits_summary(err.max)) + } }; - let output = check(&input); - let check_failed = output.num_commits_with_errors > 0; // Prepare check run let (conclusion, title, actions) = if !check_failed { (CheckRunConclusion::Success, CHECK_PASSED_TITLE, vec![]) } else { - let actions = if output.config.override_action_is_allowed() { + let actions = if config.override_action_is_allowed() { vec![CheckRunAction { label: OVERRIDE_ACTION_LABEL.to_string(), description: OVERRIDE_ACTION_DESCRIPTION.to_string(), @@ -239,7 +261,7 @@ async fn process_pull_request_event(gh_client: DynGHClient, event: &PullRequestE name: CHECK_NAME.to_string(), started_at, status: CheckRunStatus::Completed, - summary: output.render().context("error rendering output template")?, + summary, title: title.to_string(), }); @@ -252,7 +274,7 @@ async fn process_pull_request_event(gh_client: DynGHClient, event: &PullRequestE pr_number: event.number, should_be_labeled: check_failed, }; - sync_label(&gh_client, &ctx, &output.config, &input).await; + sync_label(&gh_client, &ctx, &config, &input).await; // Create check run gh_client.create_check_run(&ctx, &check_run).await.context("error creating check run")?; @@ -362,6 +384,20 @@ async fn sync_label(gh_client: &DynGHClient, ctx: &Ctx, config: &Config, input: } } +/// Find the error returned when a pull request has too many commits to get +/// them, if any. +fn too_many_commits_error(err: &anyhow::Error) -> Option<&TooManyCommitsError> { + err.chain().find_map(|cause| cause.downcast_ref::()) +} + +/// Prepare the summary of the check run created when a pull request has too +/// many commits to run the check. +fn too_many_commits_summary(max_commits: usize) -> String { + format!( + "The check **did not pass**: this pull request contains too many commits to be checked (the maximum supported is {max_commits})." + ) +} + /// Synchronize the configured label of a pull request with the result of the /// DCO check, returning any error found. async fn try_sync_label( diff --git a/dco2/src/dco/event/tests.rs b/dco2/src/dco/event/tests.rs index 41849db..b9edadf 100644 --- a/dco2/src/dco/event/tests.rs +++ b/dco2/src/dco/event/tests.rs @@ -1,11 +1,13 @@ use std::{future, sync::Arc}; use anyhow::{Ok, anyhow}; +use askama::Template; use indoc::indoc; use mockall::{Sequence, predicate::eq}; use crate::{ dco::{ + check::{CheckInput, check}, event::{ CHECK_FAILED_TITLE, CHECK_NAME, CHECK_PASSED_TITLE, MERGE_GROUP_CHECKS_REQUESTED_SUMMARY, OVERRIDE_ACTION_DESCRIPTION, OVERRIDE_ACTION_IDENTIFIER, OVERRIDE_ACTION_LABEL, @@ -20,30 +22,23 @@ use crate::{ MergeGroupEvent, MergeGroupEventAction, MergeGroupEventMergeGroup, MergeGroupHeadCommit, MockGHClient, Organization, PullRequest, PullRequestBase, PullRequestEvent, PullRequestEventAction, PullRequestHead, PullRequestLabel, PullRequestState, Repository, RepositoryOwner, RequestedAction, - User, + TooManyCommitsError, User, }, }; const LABEL: &str = "needs-dco"; +/// Maximum number of commits reported by the too many commits error. +const MAX_COMMITS: usize = 1000; + +/// Summary of the check run created when there are too many commits. +const TOO_MANY_COMMITS_SUMMARY: &str = "The check **did not pass**: this pull request contains too many commits to be checked (the maximum supported is 1000)."; + #[tokio::test] async fn check_run_event_other_action() { let event = CheckRunEvent { action: CheckRunEventAction::Other, - check_run: CheckRunEventCheckRun { - external_id: None, - head_sha: "head_sha".to_string(), - pull_requests: vec![], - }, - installation: Installation { id: 1 }, - repository: Repository { - id: 1, - name: "repo".to_string(), - owner: RepositoryOwner { - login: "owner".to_string(), - }, - }, - requested_action: None, + ..override_event(Some("42"), &[]) }; let gh_client = MockGHClient::new(); @@ -127,6 +122,21 @@ async fn check_run_event_requested_action_override_error_creating_check_run() { process_event(Arc::new(gh_client), &Event::CheckRun(event)).await.unwrap(); } +#[tokio::test] +#[should_panic(expected = "error getting repository configuration")] +async fn check_run_event_requested_action_override_error_getting_repository_configuration() { + let event = override_event(Some("42"), &[]); + let mut gh_client = MockGHClient::new(); + gh_client + .expect_get_config() + .with(eq(event.ctx())) + .times(1) + .returning(|_| Box::pin(future::ready(Err(anyhow!("test error"))))); + gh_client.expect_create_check_run().never(); + + process_event(Arc::new(gh_client), &Event::CheckRun(event)).await.unwrap(); +} + #[tokio::test] async fn check_run_event_requested_action_override_ignored_when_disabled() { let event = CheckRunEvent { @@ -205,6 +215,33 @@ async fn check_run_event_requested_action_override_label_ignores_other_repositor process_event(Arc::new(gh_client), &Event::CheckRun(event)).await.unwrap(); } +#[tokio::test] +#[should_panic(expected = "error creating check run")] +async fn check_run_event_requested_action_override_label_not_removed_when_check_run_creation_fails() { + // Setup labeling enabled and check run creation failing + let event = override_event(Some("42"), &[]); + let mut gh_client = MockGHClient::new(); + gh_client + .expect_get_config() + .with(eq(event.ctx())) + .times(1) + .returning(|_| Box::pin(future::ready(Ok(Some(config_with_label()))))); + let expected_ctx = event.ctx(); + gh_client + .expect_create_check_run() + .withf(move |ctx, check_run| *ctx == expected_ctx && check_run.external_id() == Some("42")) + .times(1) + .returning(|_, _| Box::pin(future::ready(Err(anyhow!("test error"))))); + + // Setup expectations: the label must not be touched + gh_client.expect_can_manage_labels().never(); + gh_client.expect_get_pull_request().never(); + gh_client.expect_remove_label().never(); + + // Process event + process_event(Arc::new(gh_client), &Event::CheckRun(event)).await.unwrap(); +} + #[tokio::test] async fn check_run_event_requested_action_override_label_permission_not_granted() { let event = override_event(Some("42"), &[]); @@ -760,6 +797,38 @@ async fn pull_request_event_other_action() { process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); } +#[tokio::test] +async fn pull_request_event_opened_action_check_run_summary_rendered_from_check_output() { + // Setup check input + let event = pr_opened_event(&[]); + let mut gh_client = MockGHClient::new(); + let commits = vec![commit_with_signoff(false)]; + expect_pr_check_input(&mut gh_client, &event, commits.clone(), Config::default()); + + // Setup check run expectation, with the summary rendered from the output + let expected_summary = check(&CheckInput { + commits, + config: Config::default(), + head_ref: "head_ref".to_string(), + members: vec![], + }) + .render() + .unwrap(); + let expected_ctx = event.ctx(); + gh_client + .expect_create_check_run() + .withf(move |ctx, check_run| { + *ctx == expected_ctx + && check_run.conclusion() == &CheckRunConclusion::ActionRequired + && check_run.summary() == expected_summary + }) + .times(1) + .returning(|_, _| Box::pin(future::ready(Ok(())))); + + // Process event + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + #[tokio::test] #[should_panic(expected = "error getting pull request commits")] async fn pull_request_event_opened_action_error_getting_pr_commits() { @@ -1012,6 +1081,34 @@ async fn pull_request_event_opened_action_error_creating_check_run() { process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); } +#[tokio::test] +async fn pull_request_event_opened_action_membership_check_skipped_for_unverified_commits() { + let event = pr_opened_event_in_org(); + let mut gh_client = MockGHClient::new(); + let commits = vec![ + commit_without_signoff(Some("user1"), None), + commit_without_signoff(Some("user2"), Some(false)), + commit_without_signoff(None, Some(true)), + ]; + expect_pr_check_input(&mut gh_client, &event, commits, config_without_members_signoff()); + gh_client.expect_is_organization_member().never(); + expect_pr_check_run(&mut gh_client, &event, CheckRunConclusion::ActionRequired); + + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + +#[tokio::test] +async fn pull_request_event_opened_action_membership_check_skipped_when_members_signoff_required() { + let event = pr_opened_event_in_org(); + let mut gh_client = MockGHClient::new(); + let commits = vec![commit_without_signoff(Some("user1"), Some(true))]; + expect_pr_check_input(&mut gh_client, &event, commits, Config::default()); + gh_client.expect_is_organization_member().never(); + expect_pr_check_run(&mut gh_client, &event, CheckRunConclusion::ActionRequired); + + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + #[tokio::test] async fn pull_request_event_opened_action_success_check_passed() { let event = PullRequestEvent { @@ -1174,6 +1271,18 @@ async fn pull_request_event_opened_action_success_check_passed_author_is_member( process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); } +#[tokio::test] +async fn pull_request_event_opened_action_success_check_passed_author_is_repository_owner() { + let event = pr_opened_event(&[]); + let mut gh_client = MockGHClient::new(); + let commits = vec![commit_without_signoff(Some("owner"), Some(true))]; + expect_pr_check_input(&mut gh_client, &event, commits, config_without_members_signoff()); + gh_client.expect_is_organization_member().never(); + expect_pr_check_run(&mut gh_client, &event, CheckRunConclusion::Success); + + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + #[tokio::test] async fn pull_request_event_opened_action_success_check_failed_author_is_not_member() { let event = PullRequestEvent { @@ -1446,6 +1555,29 @@ async fn pull_request_event_opened_action_success_check_passed_author_membership process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); } +#[tokio::test] +async fn pull_request_event_opened_action_success_check_failed_non_member_membership_checked_once() { + // Setup two commits from the same non-member author + let event = pr_opened_event_in_org(); + let mut gh_client = MockGHClient::new(); + let commits = vec![ + commit_without_signoff(Some("user1"), Some(true)), + commit_without_signoff(Some("user1"), Some(true)), + ]; + expect_pr_check_input(&mut gh_client, &event, commits, config_without_members_signoff()); + + // Setup expectations: membership must be checked only once + gh_client + .expect_is_organization_member() + .with(eq(event.ctx()), eq("org"), eq("user1")) + .times(1) + .returning(|_, _, _| Box::pin(future::ready(Ok(false)))); + expect_pr_check_run(&mut gh_client, &event, CheckRunConclusion::ActionRequired); + + // Process event + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + #[tokio::test] async fn pull_request_event_opened_action_success_check_failed() { let event = PullRequestEvent { @@ -1608,6 +1740,112 @@ async fn pull_request_event_opened_action_success_check_failed_override_action_d process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); } +#[tokio::test] +async fn pull_request_event_opened_action_too_many_commits_check_failed() { + // Setup pull request with too many commits to get them + let event = pr_opened_event_in_org(); + let mut gh_client = MockGHClient::new(); + expect_pr_too_many_commits(&mut gh_client, &event, config_without_members_signoff()); + gh_client.expect_is_organization_member().never(); + + // Setup check run expectation: it fails explaining why and can be overridden + let expected_ctx = event.ctx(); + gh_client + .expect_create_check_run() + .withf(move |ctx, check_run| { + *ctx == expected_ctx + && check_run.actions() + == [CheckRunAction { + label: OVERRIDE_ACTION_LABEL.to_string(), + description: OVERRIDE_ACTION_DESCRIPTION.to_string(), + identifier: OVERRIDE_ACTION_IDENTIFIER.to_string(), + }] + && check_run.conclusion() == &CheckRunConclusion::ActionRequired + && check_run.external_id() == Some("42") + && check_run.head_sha() == "head_sha" + && check_run.summary() == TOO_MANY_COMMITS_SUMMARY + && check_run.title() == CHECK_FAILED_TITLE + }) + .times(1) + .returning(|_, _| Box::pin(future::ready(Ok(())))); + + // Process event + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + +#[tokio::test] +async fn pull_request_event_opened_action_too_many_commits_check_failed_override_action_disabled() { + // Setup pull request with too many commits and the override action disabled + let event = pr_opened_event(&[]); + let mut gh_client = MockGHClient::new(); + let config = Config { + allow_override_action: Some(false), + ..Default::default() + }; + expect_pr_too_many_commits(&mut gh_client, &event, config); + + // Setup check run expectation: it fails without offering any action + let expected_ctx = event.ctx(); + gh_client + .expect_create_check_run() + .withf(move |ctx, check_run| { + *ctx == expected_ctx + && check_run.actions().is_empty() + && check_run.conclusion() == &CheckRunConclusion::ActionRequired + && check_run.summary() == TOO_MANY_COMMITS_SUMMARY + }) + .times(1) + .returning(|_, _| Box::pin(future::ready(Ok(())))); + + // Process event + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + +#[tokio::test] +async fn pull_request_event_opened_action_too_many_commits_label_added() { + // Setup pull request with too many commits and labeling enabled + let event = pr_opened_event(&[]); + let mut gh_client = MockGHClient::new(); + expect_pr_too_many_commits(&mut gh_client, &event, config_with_label()); + + // Setup expectations: the label is added before creating the check run + let mut seq = Sequence::new(); + expect_can_manage_labels(&mut gh_client, &event.ctx(), true); + expect_get_pull_request(&mut gh_client, &event.ctx(), 42, pr_state("head_sha", true, &[])); + gh_client + .expect_add_label() + .with(eq(event.ctx()), eq(42), eq(LABEL)) + .times(1) + .in_sequence(&mut seq) + .returning(|_, _, _| Box::pin(future::ready(Ok(())))); + let expected_ctx = event.ctx(); + gh_client + .expect_create_check_run() + .withf(move |ctx, check_run| { + *ctx == expected_ctx && check_run.conclusion() == &CheckRunConclusion::ActionRequired + }) + .times(1) + .in_sequence(&mut seq) + .returning(|_, _| Box::pin(future::ready(Ok(())))); + + // Process event + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + +#[tokio::test] +async fn pull_request_event_synchronize_action_runs_check() { + let event = PullRequestEvent { + action: PullRequestEventAction::Synchronize, + ..pr_opened_event(&[]) + }; + let mut gh_client = MockGHClient::new(); + expect_pr_check(&mut gh_client, &event, Config::default(), true); + + process_event(Arc::new(gh_client), &Event::PullRequest(event)).await.unwrap(); +} + +// Helpers. + fn commit_with_signoff(is_valid: bool) -> Commit { let signoff = if is_valid { "user1 " @@ -1630,6 +1868,23 @@ fn commit_with_signoff(is_valid: bool) -> Commit { } } +/// Build a verified or unverified commit without any sign-off in its message. +fn commit_without_signoff(login: Option<&str>, verified: Option) -> Commit { + let user = User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + login: login.map(ToString::to_string), + ..Default::default() + }; + Commit { + author: Some(user.clone()), + committer: Some(user), + message: "Test commit message".to_string(), + verified, + ..Default::default() + } +} + fn config_with_label() -> Config { Config { label: Some(LABEL.to_string()), @@ -1637,6 +1892,14 @@ fn config_with_label() -> Config { } } +/// Build a configuration that does not require members to sign-off commits. +fn config_without_members_signoff() -> Config { + Config { + require: Some(ConfigRequire { members: Some(false) }), + ..Default::default() + } +} + fn expect_can_manage_labels(gh_client: &mut MockGHClient, ctx: &Ctx, can_manage_labels: bool) { gh_client .expect_can_manage_labels() @@ -1673,35 +1936,71 @@ fn expect_override_check(gh_client: &mut MockGHClient, event: &CheckRunEvent, co } fn expect_pr_check(gh_client: &mut MockGHClient, event: &PullRequestEvent, config: Config, passes: bool) { - let commit = commit_with_signoff(passes); + expect_pr_check_input(gh_client, event, vec![commit_with_signoff(passes)], config); + let expected_conclusion = if passes { + CheckRunConclusion::Success + } else { + CheckRunConclusion::ActionRequired + }; + expect_pr_check_run(gh_client, event, expected_conclusion); +} + +/// Expect the pull request commits and the repository configuration to be fetched. +fn expect_pr_check_input( + gh_client: &mut MockGHClient, + event: &PullRequestEvent, + commits: Vec, + config: Config, +) { gh_client .expect_compare_commits() .with(eq(event.ctx()), eq("base_sha"), eq("head_sha")) .times(1) - .returning(move |_, _, _| Box::pin(future::ready(Ok(vec![commit.clone()])))); + .returning(move |_, _, _| Box::pin(future::ready(Ok(commits.clone())))); gh_client .expect_get_config() .with(eq(event.ctx())) .times(1) .returning(move |_| Box::pin(future::ready(Ok(Some(config.clone()))))); - let expected_conclusion = if passes { - CheckRunConclusion::Success - } else { - CheckRunConclusion::ActionRequired - }; +} + +/// Expect a check run with the conclusion provided for the pull request. +fn expect_pr_check_run( + gh_client: &mut MockGHClient, + event: &PullRequestEvent, + conclusion: CheckRunConclusion, +) { let expected_ctx = event.ctx(); let expected_external_id = event.number.to_string(); gh_client .expect_create_check_run() .withf(move |ctx, check_run| { *ctx == expected_ctx - && check_run.conclusion() == &expected_conclusion + && check_run.conclusion() == &conclusion && check_run.external_id() == Some(expected_external_id.as_str()) }) .times(1) .returning(|_, _| Box::pin(future::ready(Ok(())))); } +/// Expect the pull request commits not to be fetched because there are too +/// many of them, and the repository configuration to be fetched. +fn expect_pr_too_many_commits(gh_client: &mut MockGHClient, event: &PullRequestEvent, config: Config) { + gh_client + .expect_compare_commits() + .with(eq(event.ctx()), eq("base_sha"), eq("head_sha")) + .times(1) + .returning(|_, _, _| { + let err = TooManyCommitsError { max: MAX_COMMITS }; + Box::pin(future::ready(Err(anyhow::Error::new(err)))) + }); + gh_client + .expect_get_config() + .with(eq(event.ctx())) + .times(1) + .returning(move |_| Box::pin(future::ready(Ok(Some(config.clone()))))); +} + fn expect_remove_label(gh_client: &mut MockGHClient, ctx: &Ctx, number: i64, name: &'static str) { gh_client .expect_remove_label() @@ -1773,6 +2072,16 @@ fn pr_opened_event(labels: &[&str]) -> PullRequestEvent { } } +/// Build a pull request opened event for a repository owned by an organization. +fn pr_opened_event_in_org() -> PullRequestEvent { + PullRequestEvent { + organization: Some(Organization { + login: "org".to_string(), + }), + ..pr_opened_event(&[]) + } +} + fn pr_state(head_sha: &str, is_open: bool, labels: &[&str]) -> PullRequestState { PullRequestState { head_sha: head_sha.to_string(), diff --git a/dco2/src/github/client.rs b/dco2/src/github/client.rs index bbc43bf..e250068 100644 --- a/dco2/src/github/client.rs +++ b/dco2/src/github/client.rs @@ -22,6 +22,13 @@ use serde::{Deserialize, Serialize}; use thiserror::Error; use tracing::{debug, warn}; +#[cfg(test)] +mod tests; + +/// Number of commits requested per page when comparing commits (maximum +/// allowed by GitHub). +const COMPARE_COMMITS_PER_PAGE: i64 = 100; + /// Path of the configuration file in the repository. const CONFIG_FILE_PATH: &str = ".github/dco.yml"; @@ -43,6 +50,10 @@ const MAX_CACHED_CLIENTS: usize = 1000; /// Maximum number of installations kept in the labels permissions cache. const MAX_CACHED_LABELS_PERMISSIONS: usize = 1000; +/// Maximum number of commits supported when comparing commits, so that the +/// number of requests needed to fetch them stays bounded. +const MAX_COMPARE_COMMITS: usize = 1000; + /// Maximum number of times a request that failed with a transient error is /// retried. const MAX_RETRIES: u32 = 2; @@ -79,7 +90,9 @@ pub trait GHClient { /// manage labels. async fn can_manage_labels(&self, ctx: &Ctx) -> Result; - /// Compare two commits. + /// Compare two commits, returning all the commits between them in + /// chronological order. A [`TooManyCommitsError`] is returned when there + /// are more commits than the maximum supported. async fn compare_commits(&self, ctx: &Ctx, base_sha: &str, head_sha: &str) -> Result>; /// Create a check run. @@ -298,17 +311,37 @@ impl GHClient for GHClientOctorust { // Setup client for installation provided let client = self.setup_client(ctx.inst_id)?; - // Compare commits + // Compare commits, fetching all pages (without paging parameters, + // GitHub only returns the 250 most recent commits). When paging, the + // commits of each page are returned in chronological order let basehead = format!("{}...{}", base_sha, head_sha); - let commits = client - .repos() - .compare_commits(&ctx.owner, &ctx.repo, 0, 0, &basehead) - .await? - .body - .commits - .into_iter() - .map(Into::into) - .collect(); + let mut commits = vec![]; + let mut page = 1; + loop { + let comparison = client + .repos() + .compare_commits(&ctx.owner, &ctx.repo, page, COMPARE_COMMITS_PER_PAGE, &basehead) + .await? + .body; + let page_len = comparison.commits.len(); + commits.extend(comparison.commits.into_iter().map(Commit::from)); + + // Reject comparisons with more commits than the maximum supported + let total_commits = usize::try_from(comparison.total_commits).unwrap_or_default(); + if total_commits.max(commits.len()) > MAX_COMPARE_COMMITS { + bail!(TooManyCommitsError { + max: MAX_COMPARE_COMMITS + }); + } + + // Stop once the last page or the total number of commits is reached + // (the total is only trusted when reported) + let all_commits_fetched = total_commits > 0 && commits.len() >= total_commits; + if page_len < COMPARE_COMMITS_PER_PAGE as usize || all_commits_fetched { + break; + } + page += 1; + } Ok(commits) } @@ -344,12 +377,14 @@ impl GHClient for GHClientOctorust { /// [GHClient::get_config] async fn get_config(&self, ctx: &Ctx) -> Result> { + // Configuration is cached per repository ('/' can't be part of owner + // or repository names, so keys can't collide) #[cached( max_size = 1000, ttl_secs = 3600, sync_writes = "default", key = "String", - convert = r#"{ format!("{}-{}", ctx.owner, ctx.repo) }"# + convert = r#"{ format!("{}/{}", ctx.owner, ctx.repo) }"# )] async fn inner(client: &octorust::Client, ctx: &Ctx) -> Result> { // Get configuration file content @@ -401,12 +436,14 @@ impl GHClient for GHClientOctorust { /// [GHClient::is_organization_member] async fn is_organization_member(&self, ctx: &Ctx, org: &str, username: &str) -> Result { + // Membership is cached per organization and user ('/' can't be part of + // their names, so keys can't collide) #[cached( max_size = 1000, ttl_secs = 3600, sync_writes = "default", key = "String", - convert = r#"{ format!("{}-{}", org, username) }"# + convert = r#"{ format!("{}/{}", org, username) }"# )] async fn inner(client: &octorust::Client, org: &str, username: &str) -> Result { // Check if user is a member of the organization @@ -461,6 +498,27 @@ pub struct AppConfig { pub webhook_secret: String, } +impl AppConfig { + /// Validate the configuration, returning an error when it is not valid. + pub fn validate(&self) -> Result<()> { + // Anyone can sign webhook payloads with an empty secret + if self.webhook_secret.trim().is_empty() { + bail!("github app webhook secret cannot be empty"); + } + + // Quotes around the secret are most likely a mistake (only the ones + // wrapping environment variables values are removed when loading + // them), so we fail early instead of rejecting the signature of every + // webhook payload + let secret = &self.webhook_secret; + if secret.len() >= 2 && secret.starts_with('"') && secret.ends_with('"') { + bail!("github app webhook secret cannot be wrapped in quotes"); + } + + Ok(()) + } +} + /// Check run information. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct CheckRun { @@ -494,12 +552,14 @@ impl CheckRun { }; // Make sure the length of some fields is below the maximum allowed by - // GitHub (we'll truncate them if necessary). + // GitHub (we'll truncate them at a char boundary if necessary). // Output summary const MAX_OUTPUT_SUMMARY_LENGTH: usize = 65535; if check_run.summary.len() > MAX_OUTPUT_SUMMARY_LENGTH { - check_run.summary.truncate(MAX_OUTPUT_SUMMARY_LENGTH); + check_run + .summary + .truncate(check_run.summary.floor_char_boundary(MAX_OUTPUT_SUMMARY_LENGTH)); warn!("check run summary truncated"); } @@ -508,21 +568,25 @@ impl CheckRun { // Action label const MAX_ACTION_LABEL_LENGTH: usize = 20; if action.label.len() > MAX_ACTION_LABEL_LENGTH { - action.label.truncate(MAX_ACTION_LABEL_LENGTH); + action.label.truncate(action.label.floor_char_boundary(MAX_ACTION_LABEL_LENGTH)); warn!("check run action label truncated"); } // Action description const MAX_ACTION_DESCRIPTION_LENGTH: usize = 40; if action.description.len() > MAX_ACTION_DESCRIPTION_LENGTH { - action.description.truncate(MAX_ACTION_DESCRIPTION_LENGTH); + action + .description + .truncate(action.description.floor_char_boundary(MAX_ACTION_DESCRIPTION_LENGTH)); warn!("check run action description truncated"); } // Action identifier const MAX_ACTION_IDENTIFIER_LENGTH: usize = 20; if action.identifier.len() > MAX_ACTION_IDENTIFIER_LENGTH { - action.identifier.truncate(MAX_ACTION_IDENTIFIER_LENGTH); + action + .identifier + .truncate(action.identifier.floor_char_boundary(MAX_ACTION_IDENTIFIER_LENGTH)); warn!("check run action identifier truncated"); } } @@ -870,6 +934,15 @@ impl RetryableStrategy for RetryStrategy { } } +/// Error returned when a comparison includes more commits than the maximum +/// supported. +#[derive(Error, Debug, Clone, PartialEq)] +#[error("too many commits to compare (maximum supported: {max})")] +pub struct TooManyCommitsError { + /// Maximum number of commits supported. + pub max: usize, +} + /// Check if the error provided was caused by GitHub rate limiting the requests /// (primary or secondary rate limits). pub fn is_rate_limit_error(err: &anyhow::Error) -> bool { @@ -951,215 +1024,3 @@ fn new_octorust_client( Ok(client) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn config_label_absent() { - let config = Config::default(); - assert_eq!(config.label(), None); - } - - #[test] - fn config_label_blank() { - let config = config_with_label(" "); - assert_eq!(config.label(), None); - } - - #[test] - fn config_label_dot_segment() { - assert_eq!(config_with_label(".").label(), None); - assert_eq!(config_with_label("..").label(), None); - } - - #[test] - fn config_label_max_length() { - let label = "a".repeat(50); - let config = config_with_label(&label); - assert_eq!(config.label(), Some(label.as_str())); - } - - #[test] - fn config_label_too_long() { - let config = config_with_label(&"a".repeat(51)); - assert_eq!(config.label(), None); - } - - #[test] - fn config_label_trimmed() { - let config = config_with_label(" needs-dco "); - assert_eq!(config.label(), Some("needs-dco")); - } - - #[test] - fn config_label_yaml() { - let config: Config = serde_yaml::from_str("label: needs-dco").unwrap(); - assert_eq!(config.label(), Some("needs-dco")); - } - - #[test] - fn encode_label_name_encodes_path_characters() { - assert_eq!( - encode_label_name("do-not-merge/dco%\\"), - "do-not-merge%2Fdco%25%5C" - ); - } - - #[test] - fn encode_label_name_keeps_other_characters() { - assert_eq!(encode_label_name("needs dco"), "needs dco"); - } - - #[test] - fn is_permissions_error_not_found() { - let err = http_error(StatusCode::NOT_FOUND, "Not Found"); - assert!(!is_permissions_error(&err)); - } - - #[test] - fn is_permissions_error_permissions_not_granted() { - let err = http_error( - StatusCode::FORBIDDEN, - r#"{"message":"Resource not accessible by integration","status":"403"}"#, - ); - assert!(is_permissions_error(&err)); - } - - #[test] - fn is_permissions_error_secondary_rate_limit() { - let err = http_error( - StatusCode::FORBIDDEN, - r#"{"message":"You have exceeded a secondary rate limit","status":"403"}"#, - ); - assert!(!is_permissions_error(&err)); - } - - #[test] - fn is_rate_limit_error_forbidden_with_rate_limit_message() { - let err = http_error(StatusCode::FORBIDDEN, "You have exceeded a secondary rate limit."); - assert!(is_rate_limit_error( - &anyhow::Error::new(err).context("error adding label") - )); - } - - #[test] - fn is_rate_limit_error_forbidden_with_rate_limit_remaining_zero() { - let err = http_error_with_header(StatusCode::FORBIDDEN, RATE_LIMIT_REMAINING_HEADER, "0"); - assert!(is_rate_limit_error(&anyhow::Error::new(err))); - } - - #[test] - fn is_rate_limit_error_forbidden_with_retry_after_header() { - let err = http_error_with_header(StatusCode::FORBIDDEN, RETRY_AFTER.as_str(), "60"); - assert!(is_rate_limit_error(&anyhow::Error::new(err))); - } - - #[test] - fn is_rate_limit_error_forbidden_without_rate_limit_details() { - let err = http_error(StatusCode::FORBIDDEN, PERMISSIONS_NOT_GRANTED_MESSAGE); - assert!(!is_rate_limit_error(&anyhow::Error::new(err))); - } - - #[test] - fn is_rate_limit_error_other_error() { - assert!(!is_rate_limit_error(&anyhow::anyhow!("test error"))); - } - - #[test] - fn is_rate_limit_error_primary_rate_limit() { - let err = octorust::ClientError::RateLimited { duration: 60 }; - assert!(is_rate_limit_error(&anyhow::Error::new(err))); - } - - #[test] - fn is_rate_limit_error_too_many_requests() { - let err = http_error(StatusCode::TOO_MANY_REQUESTS, ""); - assert!(is_rate_limit_error(&anyhow::Error::new(err))); - } - - #[test] - fn labels_permissions_granted_issues_write() { - let permissions = app_permissions(r#"{"issues": "write", "metadata": "read"}"#); - assert!(labels_permissions_granted(&permissions)); - } - - #[test] - fn labels_permissions_granted_not_granted() { - let permissions = app_permissions(r#"{"checks": "write", "metadata": "read"}"#); - assert!(!labels_permissions_granted(&permissions)); - } - - #[test] - fn labels_permissions_granted_pull_requests_write() { - let permissions = app_permissions(r#"{"metadata": "read", "pull_requests": "write"}"#); - assert!(labels_permissions_granted(&permissions)); - } - - #[test] - fn labels_permissions_granted_read_only() { - let permissions = app_permissions(r#"{"issues": "read", "pull_requests": "read"}"#); - assert!(!labels_permissions_granted(&permissions)); - } - - #[test] - fn retry_strategy_forbidden_not_retried() { - let result = Ok(response(StatusCode::FORBIDDEN)); - assert!(RetryStrategy.handle(&result) == Some(Retryable::Fatal)); - } - - #[test] - fn retry_strategy_server_error_retried() { - let result = Ok(response(StatusCode::BAD_GATEWAY)); - assert!(RetryStrategy.handle(&result) == Some(Retryable::Transient)); - } - - #[test] - fn retry_strategy_success_not_retried() { - let result = Ok(response(StatusCode::OK)); - assert!(RetryStrategy.handle(&result).is_none()); - } - - #[test] - fn retry_strategy_too_many_requests_not_retried() { - let result = Ok(response(StatusCode::TOO_MANY_REQUESTS)); - assert!(RetryStrategy.handle(&result) == Some(Retryable::Fatal)); - } - - fn app_permissions(json: &str) -> octorust::types::AppPermissions { - serde_json::from_str(json).unwrap() - } - - fn config_with_label(label: &str) -> Config { - Config { - label: Some(label.to_string()), - ..Default::default() - } - } - - fn http_error(status: StatusCode, error: &str) -> octorust::ClientError { - octorust::ClientError::HttpError { - status, - headers: http::HeaderMap::new(), - error: error.to_string(), - } - } - fn http_error_with_header( - status: StatusCode, - name: &'static str, - value: &'static str, - ) -> octorust::ClientError { - let mut headers = http::HeaderMap::new(); - headers.insert(name, http::HeaderValue::from_static(value)); - octorust::ClientError::HttpError { - status, - headers, - error: String::new(), - } - } - - fn response(status: StatusCode) -> reqwest::Response { - http::Response::builder().status(status).body("").unwrap().into() - } -} diff --git a/dco2/src/github/client/tests.rs b/dco2/src/github/client/tests.rs new file mode 100644 index 0000000..a4b9ee4 --- /dev/null +++ b/dco2/src/github/client/tests.rs @@ -0,0 +1,1223 @@ +use std::sync::{Arc, Mutex}; + +use axum::response::{IntoResponse, Response}; +use chrono::TimeZone; +use http::Method; +use indoc::indoc; +use pretty_assertions::assert_eq; +use serde_json::{Value, json}; + +use super::*; + +/// Private key generated for these tests only. It does not belong to any +/// GitHub App and must never be used outside of them. +const TEST_APP_PRIVATE_KEY: &str = include_str!("../testdata/test-app-private-key.pem"); + +#[tokio::test] +async fn add_label_creates_missing_label() { + // Setup mock GitHub server + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/repo/labels/needs-dco") => not_found(), + ("POST", "/repos/owner/repo/labels") => { + (StatusCode::CREATED, axum::Json(label_json("needs-dco"))).into_response() + } + ("POST", "/repos/owner/repo/issues/1/labels") => { + axum::Json(json!([label_json("needs-dco")])).into_response() + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Add the label + gh.add_label(&ctx("owner", "repo"), 1, "needs-dco").await.unwrap(); + + // Check the label was created before being added to the pull request + let requests = server.requests(); + assert_eq!( + request_lines(&requests), + vec![ + "GET /repos/owner/repo/labels/needs-dco", + "POST /repos/owner/repo/labels", + "POST /repos/owner/repo/issues/1/labels", + ] + ); + assert_eq!( + requests[1].json_body(), + json!({ + "color": "ededed", + "description": "DCO check requires attention", + "name": "needs-dco", + }) + ); + assert_eq!(requests[2].json_body(), json!({"labels": ["needs-dco"]})); +} + +#[tokio::test] +async fn add_label_ignores_label_created_concurrently() { + // Setup mock GitHub server (label creation fails as it already exists) + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/repo/labels/needs-dco") => not_found(), + ("POST", "/repos/owner/repo/labels") => { + let body = json!({"message": "Validation Failed"}); + (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(body)).into_response() + } + ("POST", "/repos/owner/repo/issues/1/labels") => { + axum::Json(json!([label_json("needs-dco")])).into_response() + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Add the label + gh.add_label(&ctx("owner", "repo"), 1, "needs-dco").await.unwrap(); + + // Check the label was still added to the pull request + assert_eq!( + request_lines(&server.requests()), + vec![ + "GET /repos/owner/repo/labels/needs-dco", + "POST /repos/owner/repo/labels", + "POST /repos/owner/repo/issues/1/labels", + ] + ); +} + +#[test] +fn app_config_validate_accepts_webhook_secret() { + assert!(app_config(" secret ").validate().is_ok()); +} + +#[test] +fn app_config_validate_rejects_blank_webhook_secret() { + for webhook_secret in ["", " \t\n"] { + let err = app_config(webhook_secret).validate().unwrap_err(); + assert_eq!( + err.to_string(), + "github app webhook secret cannot be empty", + "webhook secret: {webhook_secret:?}" + ); + } +} + +#[test] +fn app_config_validate_rejects_quoted_webhook_secret() { + for webhook_secret in ["\"\"", "\"secret\""] { + let err = app_config(webhook_secret).validate().unwrap_err(); + assert_eq!( + err.to_string(), + "github app webhook secret cannot be wrapped in quotes", + "webhook secret: {webhook_secret:?}" + ); + } + for webhook_secret in ["\"", "\"secret", "se\"cr\"et", "secret\""] { + assert!( + app_config(webhook_secret).validate().is_ok(), + "webhook secret: {webhook_secret:?}" + ); + } +} + +#[tokio::test] +async fn can_manage_labels_caches_permissions() { + // Setup mock GitHub server + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/app/installations/1") => { + let body = json!({"account": {}, "id": 1, "permissions": {"issues": "write"}}); + axum::Json(body).into_response() + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + let ctx = ctx("owner", "repo"); + + // Check permissions twice + let granted1 = gh.can_manage_labels(&ctx).await.unwrap(); + let granted2 = gh.can_manage_labels(&ctx).await.unwrap(); + + // Check permissions were granted and the installation requested once + assert!(granted1); + assert!(granted2); + assert_eq!( + request_lines(&server.requests()), + vec!["GET /app/installations/1"] + ); +} + +#[test] +fn check_run_new_truncates_fields_at_char_boundary() { + // Setup input whose limits fall in the middle of a two bytes character + let action = CheckRunAction { + label: format!("{}é", "l".repeat(19)), + description: format!("{}é", "d".repeat(39)), + identifier: format!("{}é", "i".repeat(19)), + }; + let summary = format!("{}é", "s".repeat(65534)); + + // Create the check run + let check_run = CheckRun::new(new_check_run_input(vec![action], &summary)); + + // Check the characters crossing the limits were dropped + assert_eq!( + check_run.actions(), + &[CheckRunAction { + label: "l".repeat(19), + description: "d".repeat(39), + identifier: "i".repeat(19), + }] + ); + assert_eq!(check_run.summary(), "s".repeat(65534)); +} + +#[test] +fn check_run_new_truncates_fields_to_max_length() { + // Setup input exceeding the limits by one byte + let action = CheckRunAction { + label: "l".repeat(21), + description: "d".repeat(41), + identifier: "i".repeat(21), + }; + let summary = "s".repeat(65536); + + // Create the check run + let check_run = CheckRun::new(new_check_run_input(vec![action], &summary)); + + // Check the fields were truncated to the limits + assert_eq!( + check_run.actions(), + &[CheckRunAction { + label: "l".repeat(20), + description: "d".repeat(40), + identifier: "i".repeat(20), + }] + ); + assert_eq!(check_run.summary(), "s".repeat(65535)); +} + +#[test] +fn commit_from_commit_data_maps_fields() { + let commit_data = commit_data(json!({ + "author": {"login": "bot[bot]", "type": "Bot"}, + "commit": { + "author": {"email": "bot@email.test", "name": "bot"}, + "committer": {"email": "user1@email.test", "name": "user1"}, + "message": "Test commit message", + "tree": {}, + "url": "", + "verification": {"verified": true}, + }, + "committer": {"login": "user1", "type": "User"}, + "html_url": "https://github.com/owner/repo/commit/sha", + "parents": [{"sha": "parent1"}, {"sha": "parent2"}], + "sha": "sha", + })); + + assert_eq!( + Commit::from(commit_data), + Commit { + author: Some(User { + name: "bot".to_string(), + email: "bot@email.test".to_string(), + is_bot: true, + login: Some("bot[bot]".to_string()), + }), + committer: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + is_bot: false, + login: Some("user1".to_string()), + }), + html_url: "https://github.com/owner/repo/commit/sha".to_string(), + is_merge: true, + message: "Test commit message".to_string(), + sha: "sha".to_string(), + verified: Some(true), + } + ); +} + +#[test] +fn commit_from_commit_data_without_github_accounts() { + let commit_data = commit_data(json!({ + "commit": { + "author": {"email": "user1@email.test", "name": "user1"}, + "committer": {"email": "user2@email.test", "name": "user2"}, + "message": "Test commit message", + "tree": {}, + "url": "", + }, + "html_url": "https://github.com/owner/repo/commit/sha", + "parents": [{"sha": "parent1"}], + "sha": "sha", + })); + + assert_eq!( + Commit::from(commit_data), + Commit { + author: Some(User { + name: "user1".to_string(), + email: "user1@email.test".to_string(), + is_bot: false, + login: None, + }), + committer: Some(User { + name: "user2".to_string(), + email: "user2@email.test".to_string(), + is_bot: false, + login: None, + }), + html_url: "https://github.com/owner/repo/commit/sha".to_string(), + is_merge: false, + message: "Test commit message".to_string(), + sha: "sha".to_string(), + verified: None, + } + ); +} + +#[tokio::test] +async fn compare_commits_accepts_max_commits() { + // Setup mock GitHub server with a comparison of the maximum size supported + let shas: Vec = (1..=MAX_COMPARE_COMMITS).map(|i| format!("sha{i}")).collect(); + let server = MockGitHub::start({ + let shas = shas.clone(); + move |req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/compare-max-commits/compare/base_sha...head_sha") => { + compare_commits_response(&shas, shas.len(), req) + } + _ => unexpected(req), + } + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Compare commits + let commits = gh + .compare_commits(&ctx("owner", "compare-max-commits"), "base_sha", "head_sha") + .await + .unwrap(); + + // Check all commits were returned without requesting more pages than needed + assert_eq!(commits.into_iter().map(|c| c.sha).collect::>(), shas); + assert_eq!(server.requests().len(), MAX_COMPARE_COMMITS / 100); +} + +#[tokio::test] +async fn compare_commits_fetches_all_pages() { + // Setup mock GitHub server with a comparison longer than the 250 commits + // returned when no paging parameters are provided + let shas: Vec = (1..=300).map(|i| format!("sha{i}")).collect(); + let server = MockGitHub::start({ + let shas = shas.clone(); + move |req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/compare-all-pages/compare/base_sha...head_sha") => { + compare_commits_response(&shas, shas.len(), req) + } + _ => unexpected(req), + } + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Compare commits + let commits = gh + .compare_commits(&ctx("owner", "compare-all-pages"), "base_sha", "head_sha") + .await + .unwrap(); + + // Check all commits were returned in chronological order + assert_eq!(commits.into_iter().map(|c| c.sha).collect::>(), shas); + + // Check the pages requested + assert_eq!( + server.requests().iter().map(|req| req.query.as_str()).collect::>(), + vec![ + "page=1&per_page=100", + "page=2&per_page=100", + "page=3&per_page=100" + ] + ); +} + +#[tokio::test] +async fn compare_commits_fetches_all_pages_when_total_commits_not_reported() { + // Setup mock GitHub server whose comparison does not report the total + // number of commits + let shas: Vec = (1..=300).map(|i| format!("sha{i}")).collect(); + let server = MockGitHub::start({ + let shas = shas.clone(); + move |req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/compare-no-total/compare/base_sha...head_sha") => { + compare_commits_response(&shas, 0, req) + } + _ => unexpected(req), + } + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Compare commits + let commits = gh + .compare_commits(&ctx("owner", "compare-no-total"), "base_sha", "head_sha") + .await + .unwrap(); + + // Check all commits were returned, requesting pages until one is not full + assert_eq!(commits.into_iter().map(|c| c.sha).collect::>(), shas); + assert_eq!( + server.requests().iter().map(|req| req.query.as_str()).collect::>(), + vec![ + "page=1&per_page=100", + "page=2&per_page=100", + "page=3&per_page=100", + "page=4&per_page=100" + ] + ); +} + +#[tokio::test] +async fn compare_commits_rejects_too_many_commits() { + // Setup mock GitHub server with a comparison exceeding the maximum number + // of commits supported + let shas: Vec = (1..=MAX_COMPARE_COMMITS + 1).map(|i| format!("sha{i}")).collect(); + let server = MockGitHub::start(move |req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/compare-too-many/compare/base_sha...head_sha") => { + compare_commits_response(&shas, shas.len(), req) + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Compare commits + let err = gh + .compare_commits(&ctx("owner", "compare-too-many"), "base_sha", "head_sha") + .await + .unwrap_err(); + + // Check the comparison was rejected after requesting the first page only + assert_eq!( + err.downcast_ref::(), + Some(&TooManyCommitsError { + max: MAX_COMPARE_COMMITS + }) + ); + assert_eq!(server.requests().len(), 1); +} + +#[tokio::test] +async fn compare_commits_rejects_too_many_commits_when_total_commits_not_reported() { + // Setup mock GitHub server with a comparison exceeding the maximum number + // of commits supported that does not report the total number of commits + let shas: Vec = (1..=MAX_COMPARE_COMMITS + 1).map(|i| format!("sha{i}")).collect(); + let server = MockGitHub::start(move |req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/compare-too-many-no-total/compare/base_sha...head_sha") => { + compare_commits_response(&shas, 0, req) + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Compare commits + let err = gh + .compare_commits(&ctx("owner", "compare-too-many-no-total"), "base_sha", "head_sha") + .await + .unwrap_err(); + + // Check the comparison was rejected once the maximum was exceeded + assert_eq!( + err.downcast_ref::(), + Some(&TooManyCommitsError { + max: MAX_COMPARE_COMMITS + }) + ); + assert_eq!(server.requests().len(), MAX_COMPARE_COMMITS / 100 + 1); +} + +#[tokio::test] +async fn compare_commits_stops_at_last_page() { + // Setup mock GitHub server whose comparison reports more commits than the + // ones it actually returns + let shas: Vec = (1..=150).map(|i| format!("sha{i}")).collect(); + let server = MockGitHub::start({ + let shas = shas.clone(); + move |req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/compare-last-page/compare/base_sha...head_sha") + if req.query_param("page").as_deref() != Some("3") => + { + compare_commits_response(&shas, 300, req) + } + _ => unexpected(req), + } + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Compare commits + let commits = gh + .compare_commits(&ctx("owner", "compare-last-page"), "base_sha", "head_sha") + .await + .unwrap(); + + // Check the commits returned and that no pages were requested after the + // first one with fewer commits than requested (the third page would fail) + assert_eq!(commits.into_iter().map(|c| c.sha).collect::>(), shas); + assert_eq!( + server.requests().iter().map(|req| req.query.as_str()).collect::>(), + vec!["page=1&per_page=100", "page=2&per_page=100"] + ); +} + +#[test] +fn config_accessors_use_defaults_when_fields_missing() { + let config: Config = serde_yaml::from_str(indoc! {" + allowRemediationCommits: + individual: true + require: {} + "}) + .unwrap(); + + assert!(config.individual_remediation_commits_are_allowed()); + assert!(!config.third_party_remediation_commits_are_allowed()); + assert!(config.members_signoff_is_required()); +} + +#[test] +fn config_accessors_use_defaults_when_sections_missing() { + for yaml in ["label: needs-dco", "{}", "allowRemediationCommits:\nrequire:\n"] { + let config: Config = serde_yaml::from_str(yaml).unwrap(); + + assert!(config.override_action_is_allowed(), "{yaml}"); + assert!(!config.individual_remediation_commits_are_allowed(), "{yaml}"); + assert!(!config.third_party_remediation_commits_are_allowed(), "{yaml}"); + assert!(config.members_signoff_is_required(), "{yaml}"); + } +} + +#[test] +fn config_label_absent() { + let config = Config::default(); + assert_eq!(config.label(), None); +} + +#[test] +fn config_label_blank() { + let config = config_with_label(" "); + assert_eq!(config.label(), None); +} + +#[test] +fn config_label_dot_segment() { + assert_eq!(config_with_label(".").label(), None); + assert_eq!(config_with_label("..").label(), None); +} + +#[test] +fn config_label_max_length() { + let label = "a".repeat(50); + let config = config_with_label(&label); + assert_eq!(config.label(), Some(label.as_str())); +} + +#[test] +fn config_label_max_length_counts_characters() { + let label = "é".repeat(50); + assert_eq!(config_with_label(&label).label(), Some(label.as_str())); + assert_eq!(config_with_label(&"é".repeat(51)).label(), None); +} + +#[test] +fn config_label_too_long() { + let config = config_with_label(&"a".repeat(51)); + assert_eq!(config.label(), None); +} + +#[test] +fn config_label_trimmed() { + let config = config_with_label(" needs-dco "); + assert_eq!(config.label(), Some("needs-dco")); +} + +#[test] +fn config_label_yaml() { + let config: Config = serde_yaml::from_str("label: needs-dco").unwrap(); + assert_eq!(config.label(), Some("needs-dco")); +} + +#[test] +fn config_yaml_reference_file_matches_defaults() { + let config: Option = + serde_yaml::from_str(include_str!("../../../../docs/config/dco.yml")).unwrap(); + assert_eq!(config, Some(Config::default())); +} + +#[tokio::test] +async fn create_check_run_request_body_action_required() { + // Setup mock GitHub server and check run + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("POST", "/repos/owner/repo/check-runs") => check_run_created(), + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + let check_run = CheckRun::new(NewCheckRunInput { + actions: vec![CheckRunAction { + label: "Set DCO to pass".to_string(), + description: "Manually set DCO check result to passed".to_string(), + identifier: "override".to_string(), + }], + completed_at: timestamp(5), + conclusion: CheckRunConclusion::ActionRequired, + external_id: Some("42".to_string()), + head_sha: "head_sha".to_string(), + name: "DCO".to_string(), + started_at: timestamp(0), + status: CheckRunStatus::Completed, + summary: "summary".to_string(), + title: "Check failed".to_string(), + }); + + // Create the check run + gh.create_check_run(&ctx("owner", "repo"), &check_run).await.unwrap(); + + // Check the request body sent + let requests = server.requests(); + assert_eq!( + request_lines(&requests), + vec!["POST /repos/owner/repo/check-runs"] + ); + assert_eq!( + requests[0].json_body(), + json!({ + "actions": [{ + "description": "Manually set DCO check result to passed", + "identifier": "override", + "label": "Set DCO to pass", + }], + "completed_at": "1970-01-01T00:00:05Z", + "conclusion": "action_required", + "external_id": "42", + "head_sha": "head_sha", + "name": "DCO", + "output": {"summary": "summary", "title": "Check failed"}, + "started_at": "1970-01-01T00:00:00Z", + "status": "completed", + }) + ); +} + +#[tokio::test] +async fn create_check_run_request_body_success() { + // Setup mock GitHub server and check run + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("POST", "/repos/owner/repo/check-runs") => check_run_created(), + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + let check_run = CheckRun::new(NewCheckRunInput { + actions: vec![], + completed_at: timestamp(5), + conclusion: CheckRunConclusion::Success, + external_id: None, + head_sha: "head_sha".to_string(), + name: "DCO".to_string(), + started_at: timestamp(0), + status: CheckRunStatus::Completed, + summary: "summary".to_string(), + title: "Check passed!".to_string(), + }); + + // Create the check run + gh.create_check_run(&ctx("owner", "repo"), &check_run).await.unwrap(); + + // Check the request body sent (empty fields are omitted) + let requests = server.requests(); + assert_eq!( + request_lines(&requests), + vec!["POST /repos/owner/repo/check-runs"] + ); + assert_eq!( + requests[0].json_body(), + json!({ + "completed_at": "1970-01-01T00:00:05Z", + "conclusion": "success", + "head_sha": "head_sha", + "name": "DCO", + "output": {"summary": "summary", "title": "Check passed!"}, + "started_at": "1970-01-01T00:00:00Z", + "status": "completed", + }) + ); +} + +#[test] +fn encode_label_name_encodes_path_characters() { + assert_eq!( + encode_label_name("do-not-merge/dco%\\"), + "do-not-merge%2Fdco%25%5C" + ); +} + +#[test] +fn encode_label_name_keeps_other_characters() { + assert_eq!(encode_label_name("needs dco"), "needs dco"); +} + +#[tokio::test] +async fn get_config_cache_keys_do_not_collide_for_hyphenated_names() { + // Setup mock GitHub server (the configuration is cached per process, so + // these owners and repositories must not be used in other tests) + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/collide-web/app/contents/.github/dco.yml") => not_found(), + ("GET", "/repos/collide/web-app/contents/.github/dco.yml") => { + content_file(&b64.encode("label: needs-dco\n")) + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Get the configuration of both repositories + let config1 = gh.get_config(&ctx("collide-web", "app")).await.unwrap(); + let config2 = gh.get_config(&ctx("collide", "web-app")).await.unwrap(); + + // Check each repository got its own configuration + assert_eq!(config1, None); + assert_eq!(config2.as_ref().and_then(Config::label), Some("needs-dco")); + assert_eq!( + request_lines(&server.requests()), + vec![ + "GET /repos/collide-web/app/contents/.github/dco.yml", + "GET /repos/collide/web-app/contents/.github/dco.yml", + ] + ); +} + +#[tokio::test] +async fn get_config_requested_from_default_branch() { + // Setup mock GitHub server (the configuration is cached per process, so + // this owner and repository must not be used in other tests) + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/config-default-branch/repo/contents/.github/dco.yml") => { + content_file(&b64.encode("label: needs-dco\n")) + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Get the configuration + let config = gh.get_config(&ctx("config-default-branch", "repo")).await.unwrap(); + + // Check the configuration was requested without a ref + assert_eq!(config.as_ref().and_then(Config::label), Some("needs-dco")); + let requests = server.requests(); + assert_eq!( + request_lines(&requests), + vec!["GET /repos/config-default-branch/repo/contents/.github/dco.yml"] + ); + assert_eq!(requests[0].query, ""); +} + +#[tokio::test] +async fn is_organization_member_cache_keys_do_not_collide_for_hyphenated_names() { + // Setup mock GitHub server (memberships are cached per process, so these + // organizations and users must not be used in other tests) + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/orgs/collide-sigs/members/alice") => StatusCode::NO_CONTENT.into_response(), + ("GET", "/orgs/collide/members/sigs-alice") => not_found(), + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + let ctx = ctx("owner", "repo"); + + // Check both memberships + let is_member1 = gh.is_organization_member(&ctx, "collide-sigs", "alice").await.unwrap(); + let is_member2 = gh.is_organization_member(&ctx, "collide", "sigs-alice").await.unwrap(); + + // Check each membership was resolved independently + assert!(is_member1); + assert!(!is_member2); + assert_eq!( + request_lines(&server.requests()), + vec![ + "GET /orgs/collide-sigs/members/alice", + "GET /orgs/collide/members/sigs-alice", + ] + ); +} + +#[test] +fn is_permissions_error_not_found() { + let err = http_error(StatusCode::NOT_FOUND, "Not Found"); + assert!(!is_permissions_error(&err)); +} + +#[test] +fn is_permissions_error_permissions_not_granted() { + let err = http_error( + StatusCode::FORBIDDEN, + r#"{"message":"Resource not accessible by integration","status":"403"}"#, + ); + assert!(is_permissions_error(&err)); +} + +#[test] +fn is_permissions_error_secondary_rate_limit() { + let err = http_error( + StatusCode::FORBIDDEN, + r#"{"message":"You have exceeded a secondary rate limit","status":"403"}"#, + ); + assert!(!is_permissions_error(&err)); +} + +#[test] +fn is_rate_limit_error_forbidden_with_rate_limit_message() { + let err = http_error(StatusCode::FORBIDDEN, "You have exceeded a secondary rate limit."); + assert!(is_rate_limit_error( + &anyhow::Error::new(err).context("error adding label") + )); +} + +#[test] +fn is_rate_limit_error_forbidden_with_rate_limit_remaining_zero() { + let err = http_error_with_header(StatusCode::FORBIDDEN, RATE_LIMIT_REMAINING_HEADER, "0"); + assert!(is_rate_limit_error(&anyhow::Error::new(err))); +} + +#[test] +fn is_rate_limit_error_forbidden_with_remaining_requests() { + let err = http_error_with_header(StatusCode::FORBIDDEN, RATE_LIMIT_REMAINING_HEADER, "4999"); + assert!(!is_rate_limit_error(&anyhow::Error::new(err))); +} + +#[test] +fn is_rate_limit_error_forbidden_with_retry_after_header() { + let err = http_error_with_header(StatusCode::FORBIDDEN, RETRY_AFTER.as_str(), "60"); + assert!(is_rate_limit_error(&anyhow::Error::new(err))); +} + +#[test] +fn is_rate_limit_error_forbidden_without_rate_limit_details() { + let err = http_error(StatusCode::FORBIDDEN, PERMISSIONS_NOT_GRANTED_MESSAGE); + assert!(!is_rate_limit_error(&anyhow::Error::new(err))); +} + +#[test] +fn is_rate_limit_error_other_error() { + assert!(!is_rate_limit_error(&anyhow::anyhow!("test error"))); +} + +#[test] +fn is_rate_limit_error_primary_rate_limit() { + let err = octorust::ClientError::RateLimited { duration: 60 }; + assert!(is_rate_limit_error(&anyhow::Error::new(err))); +} + +#[test] +fn is_rate_limit_error_too_many_requests() { + let err = http_error(StatusCode::TOO_MANY_REQUESTS, ""); + assert!(is_rate_limit_error(&anyhow::Error::new(err))); +} + +#[test] +fn labels_error_permissions_error_evicts_installation() { + // Setup cached clients and permissions for two installations + let gh = gh_client(None); + for inst_id in [1, 2] { + gh.setup_client(inst_id).unwrap(); + gh.labels_permissions.lock().unwrap().cache_set(inst_id, true); + } + + // Convert a permissions error returned for the first installation + let err = gh.labels_error( + 1, + http_error(StatusCode::FORBIDDEN, PERMISSIONS_NOT_GRANTED_MESSAGE), + ); + + // Check only the first installation was evicted from both caches + assert!(err.is::()); + let mut clients = gh.clients.lock().unwrap(); + assert!(clients.cache_get(&1).is_none()); + assert!(clients.cache_get(&2).is_some()); + let mut labels_permissions = gh.labels_permissions.lock().unwrap(); + assert_eq!(labels_permissions.cache_get(&1), None); + assert_eq!(labels_permissions.cache_get(&2), Some(&true)); +} + +#[test] +fn labels_permissions_granted_issues_write() { + let permissions = app_permissions(r#"{"issues": "write", "metadata": "read"}"#); + assert!(labels_permissions_granted(&permissions)); +} + +#[test] +fn labels_permissions_granted_not_granted() { + let permissions = app_permissions(r#"{"checks": "write", "metadata": "read"}"#); + assert!(!labels_permissions_granted(&permissions)); +} + +#[test] +fn labels_permissions_granted_pull_requests_write() { + let permissions = app_permissions(r#"{"metadata": "read", "pull_requests": "write"}"#); + assert!(labels_permissions_granted(&permissions)); +} + +#[test] +fn labels_permissions_granted_read_only() { + let permissions = app_permissions(r#"{"issues": "read", "pull_requests": "read"}"#); + assert!(!labels_permissions_granted(&permissions)); +} + +#[tokio::test] +async fn new_octorust_client_does_not_retry_too_many_requests() { + // Setup mock GitHub server + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/repo/pulls/1") => { + let headers = [ + (RATE_LIMIT_REMAINING_HEADER, "0"), + ("x-ratelimit-reset", "4102444800"), + ]; + (StatusCode::TOO_MANY_REQUESTS, headers).into_response() + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Get the pull request + let err = gh.get_pull_request(&ctx("owner", "repo"), 1).await.unwrap_err(); + + // Check the rate limited request was sent only once + assert!(is_rate_limit_error(&err)); + assert_eq!( + request_lines(&server.requests()), + vec!["GET /repos/owner/repo/pulls/1"] + ); +} + +#[tokio::test] +async fn new_octorust_client_retries_server_errors() { + // Setup mock GitHub server + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("GET", "/repos/owner/repo/pulls/1") => StatusCode::BAD_GATEWAY.into_response(), + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Get the pull request + let result = gh.get_pull_request(&ctx("owner", "repo"), 1).await; + + // Check the request failed after being retried the maximum number of times + assert!(matches!( + result.unwrap_err().downcast_ref::(), + Some(octorust::ClientError::HttpError { status, .. }) if *status == StatusCode::BAD_GATEWAY + )); + assert_eq!( + request_lines(&server.requests()), + vec!["GET /repos/owner/repo/pulls/1"; MAX_RETRIES as usize + 1] + ); +} + +#[tokio::test] +async fn remove_label_encodes_name_in_path() { + // Setup mock GitHub server + let server = MockGitHub::start(|req| match (req.method.as_str(), req.path.as_str()) { + ("DELETE", "/repos/owner/repo/issues/1/labels/area%2Fdco%20100%25") => { + axum::Json(json!([])).into_response() + } + _ => unexpected(req), + }) + .await; + let gh = gh_client(Some(&server.url)); + + // Remove the label + gh.remove_label(&ctx("owner", "repo"), 1, "area/dco 100%").await.unwrap(); + + // Check the label name was encoded as a single path segment + assert_eq!( + request_lines(&server.requests()), + vec!["DELETE /repos/owner/repo/issues/1/labels/area%2Fdco%20100%25"] + ); +} + +#[test] +fn retry_strategy_forbidden_not_retried() { + let result = Ok(response(StatusCode::FORBIDDEN)); + assert!(RetryStrategy.handle(&result) == Some(Retryable::Fatal)); +} + +#[test] +fn retry_strategy_server_error_retried() { + let result = Ok(response(StatusCode::BAD_GATEWAY)); + assert!(RetryStrategy.handle(&result) == Some(Retryable::Transient)); +} + +#[test] +fn retry_strategy_success_not_retried() { + let result = Ok(response(StatusCode::OK)); + assert!(RetryStrategy.handle(&result).is_none()); +} + +#[test] +fn retry_strategy_too_many_requests_not_retried() { + let result = Ok(response(StatusCode::TOO_MANY_REQUESTS)); + assert!(RetryStrategy.handle(&result) == Some(Retryable::Fatal)); +} + +// Helpers. + +/// Mock GitHub API server. Installation access token requests are answered +/// automatically and not recorded; the responder answers the others. +struct MockGitHub { + /// Requests received (installation access token requests excluded). + requests: Arc>>, + /// Base URL of the server, used as the GitHub API host override. + url: String, +} + +impl MockGitHub { + /// Start a new mock server listening on a random local port. + async fn start(responder: F) -> Self + where + F: Fn(&MockRequest) -> Response + Send + Sync + 'static, + { + // Setup router recording requests and answering them + let requests = Arc::new(Mutex::new(vec![])); + let responder = Arc::new(responder); + let router = axum::Router::new().fallback({ + let requests = requests.clone(); + move |method: Method, uri: http::Uri, body: String| async move { + let req = MockRequest { + body, + method, + path: uri.path().to_string(), + query: uri.query().unwrap_or_default().to_string(), + }; + + // Issue installation access tokens + if req.method == Method::POST && req.path.ends_with("/access_tokens") { + let token = json!({"expires_at": "2099-01-01T00:00:00Z", "token": "test-token"}); + return (StatusCode::CREATED, axum::Json(token)).into_response(); + } + + // Record and answer any other request + requests.lock().unwrap().push(req.clone()); + responder(&req) + } + }); + + // Start server + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + + Self { requests, url } + } + + /// Get the requests received so far. + fn requests(&self) -> Vec { + self.requests.lock().unwrap().clone() + } +} + +/// Request received by the mock GitHub API server. +#[derive(Debug, Clone)] +struct MockRequest { + /// Request body. + body: String, + /// Request method. + method: Method, + /// Request path (percent-encoded, as received). + path: String, + /// Request query string (empty when not provided). + query: String, +} + +impl MockRequest { + /// Parse the request body as JSON. + fn json_body(&self) -> Value { + serde_json::from_str(&self.body).unwrap() + } + + /// Get the value of the query parameter provided, if any. + fn query_param(&self, name: &str) -> Option { + self.query + .split('&') + .filter_map(|pair| pair.split_once('=')) + .find(|(key, _)| *key == name) + .map(|(_, value)| value.to_string()) + } +} + +/// Build a GitHub application configuration with the webhook secret +/// provided. +fn app_config(webhook_secret: &str) -> AppConfig { + AppConfig { + api_host: None, + app_id: 1, + private_key: TEST_APP_PRIVATE_KEY.to_string(), + webhook_secret: webhook_secret.to_string(), + } +} + +/// Parse the installation permissions provided. +fn app_permissions(json: &str) -> octorust::types::AppPermissions { + serde_json::from_str(json).unwrap() +} + +/// Response returned by GitHub when a check run is created. +fn check_run_created() -> Response { + let check_run = json!({"id": 1, "name": "DCO", "output": {}, "status": "completed"}); + (StatusCode::CREATED, axum::Json(check_run)).into_response() +} + +/// Parse the commit data provided. +fn commit_data(json: Value) -> octorust::types::CommitDataType { + serde_json::from_value(json).unwrap() +} + +/// Emulate GitHub's compare commits endpoint for a comparison including the +/// commits provided (in chronological order), reporting the total number of +/// commits given. Without paging parameters only the 250 most recent commits +/// are returned. +fn compare_commits_response(shas: &[String], total_commits: usize, req: &MockRequest) -> Response { + const MAX_COMMITS_WITHOUT_PAGINATION: usize = 250; + + // Select the commits of the page requested + let page = req.query_param("page").map(|p| p.parse::().unwrap()); + let per_page = req.query_param("per_page").map(|p| p.parse::().unwrap()); + let selected = if page.is_none() && per_page.is_none() { + &shas[shas.len().saturating_sub(MAX_COMMITS_WITHOUT_PAGINATION)..] + } else { + let page = page.unwrap_or(1).max(1); + let per_page = per_page.unwrap_or(30).min(100); + let start = ((page - 1) * per_page).min(shas.len()); + let end = (start + per_page).min(shas.len()); + &shas[start..end] + }; + + // Prepare comparison + let commit = |sha: &str| json!({"commit": {"message": "", "tree": {}, "url": ""}, "sha": sha}); + let comparison = json!({ + "base_commit": commit("base_sha"), + "commits": selected.iter().map(|sha| commit(sha)).collect::>(), + "merge_base_commit": commit("base_sha"), + "status": "ahead", + "total_commits": total_commits, + }); + axum::Json(comparison).into_response() +} + +/// Build a configuration with the label provided. +fn config_with_label(label: &str) -> Config { + Config { + label: Some(label.to_string()), + ..Default::default() + } +} + +/// Configuration file content response with the base64 content provided. +fn content_file(content: &str) -> Response { + let body = json!({"_links": {}, "content": content, "encoding": "base64"}); + axum::Json(body).into_response() +} + +/// Build a context for the repository provided (installation 1). +fn ctx(owner: &str, repo: &str) -> Ctx { + Ctx { + inst_id: 1, + owner: owner.to_string(), + repo: repo.to_string(), + } +} + +/// Build a GitHub client using the test private key and the API host +/// provided. +fn gh_client(api_host: Option<&str>) -> GHClientOctorust { + GHClientOctorust::new(&AppConfig { + api_host: api_host.map(ToString::to_string), + app_id: 1, + private_key: TEST_APP_PRIVATE_KEY.to_string(), + webhook_secret: "secret".to_string(), + }) + .unwrap() +} + +/// Build an HTTP error with the status and error message provided. +fn http_error(status: StatusCode, error: &str) -> octorust::ClientError { + octorust::ClientError::HttpError { + status, + headers: http::HeaderMap::new(), + error: error.to_string(), + } +} + +/// Build an HTTP error with the status and header provided. +fn http_error_with_header( + status: StatusCode, + name: &'static str, + value: &'static str, +) -> octorust::ClientError { + let mut headers = http::HeaderMap::new(); + headers.insert(name, http::HeaderValue::from_static(value)); + octorust::ClientError::HttpError { + status, + headers, + error: String::new(), + } +} + +/// Label JSON representation returned by GitHub. +fn label_json(name: &str) -> Value { + json!({"name": name}) +} + +/// Build the input of a check run with the actions and summary provided. +fn new_check_run_input(actions: Vec, summary: &str) -> NewCheckRunInput { + NewCheckRunInput { + actions, + completed_at: timestamp(0), + conclusion: CheckRunConclusion::Success, + external_id: None, + head_sha: "head_sha".to_string(), + name: "DCO".to_string(), + started_at: timestamp(0), + status: CheckRunStatus::Completed, + summary: summary.to_string(), + title: "title".to_string(), + } +} + +/// Not found response returned by GitHub. +fn not_found() -> Response { + let body = json!({"message": "Not Found"}); + (StatusCode::NOT_FOUND, axum::Json(body)).into_response() +} + +/// Summarize the requests provided as `METHOD path` lines. +fn request_lines(requests: &[MockRequest]) -> Vec { + requests.iter().map(|req| format!("{} {}", req.method, req.path)).collect() +} + +/// Build an HTTP response with the status provided. +fn response(status: StatusCode) -> reqwest::Response { + http::Response::builder().status(status).body("").unwrap().into() +} + +/// Build a timestamp the seconds provided after the Unix epoch. +fn timestamp(secs: i64) -> DateTime { + Utc.timestamp_opt(secs, 0).unwrap() +} + +/// Response returned by the mock server for requests not expected by a test. +fn unexpected(req: &MockRequest) -> Response { + let body = format!("unexpected request: {} {}", req.method, req.path); + (StatusCode::IM_A_TEAPOT, body).into_response() +} diff --git a/dco2/src/github/event.rs b/dco2/src/github/event.rs index 48dd46b..404932e 100644 --- a/dco2/src/github/event.rs +++ b/dco2/src/github/event.rs @@ -8,6 +8,9 @@ use thiserror::Error; use crate::github::client::Ctx; +#[cfg(test)] +mod tests; + /// Header representing the event unique identifier. pub const EVENT_ID_HEADER: &str = "X-GitHub-Delivery"; @@ -257,113 +260,3 @@ pub struct RepositoryOwner { pub struct RequestedAction { pub identifier: String, } - -#[cfg(test)] -mod tests { - use http::HeaderValue; - - use super::*; - - #[test] - fn check_run_event_with_external_id_and_pull_requests() { - let body = r#"{ - "action": "requested_action", - "check_run": { - "external_id": "123", - "head_sha": "head_sha", - "pull_requests": [{"base": {"repo": {"id": 1}}, "id": 1, "number": 123}] - }, - "installation": {"id": 1}, - "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}}, - "requested_action": {"identifier": "override"} - }"#; - - let Event::CheckRun(event) = parse_event("check_run", body) else { - panic!("unexpected event type"); - }; - - assert_eq!(event.check_run.external_id.as_deref(), Some("123")); - assert_eq!( - event.check_run.pull_requests, - vec![CheckRunEventPullRequest { - base: CheckRunEventPullRequestBase { - repo: CheckRunEventPullRequestRepository { id: 1 }, - }, - number: 123, - }] - ); - } - - #[test] - fn check_run_event_without_external_id_and_pull_requests() { - let body = r#"{ - "action": "requested_action", - "check_run": {"external_id": "", "head_sha": "head_sha"}, - "installation": {"id": 1}, - "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}}, - "requested_action": {"identifier": "override"} - }"#; - - let Event::CheckRun(event) = parse_event("check_run", body) else { - panic!("unexpected event type"); - }; - - assert_eq!(event.check_run.external_id.as_deref(), Some("")); - assert!(event.check_run.pull_requests.is_empty()); - } - - #[test] - fn pull_request_event_with_labels() { - let body = r#"{ - "action": "opened", - "installation": {"id": 1}, - "number": 123, - "pull_request": { - "base": {"ref": "main", "sha": "base_sha"}, - "head": {"ref": "feature", "sha": "head_sha"}, - "html_url": "url", - "labels": [{"id": 1, "name": "needs-dco", "color": "d73a4a"}] - }, - "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}} - }"#; - - let Event::PullRequest(event) = parse_event("pull_request", body) else { - panic!("unexpected event type"); - }; - - assert_eq!( - event.pull_request.labels, - vec![PullRequestLabel { - name: "needs-dco".to_string() - }] - ); - } - - #[test] - fn pull_request_event_with_number() { - let body = r#"{ - "action": "opened", - "installation": {"id": 1}, - "number": 123, - "pull_request": { - "base": {"ref": "main", "sha": "base_sha"}, - "head": {"ref": "feature", "sha": "head_sha"}, - "html_url": "url" - }, - "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}} - }"#; - - let Event::PullRequest(event) = parse_event("pull_request", body) else { - panic!("unexpected event type"); - }; - - assert_eq!(event.number, 123); - assert!(event.pull_request.labels.is_empty()); - } - - fn parse_event(name: &'static str, body: &str) -> Event { - let mut headers = HeaderMap::new(); - headers.insert(EVENT_NAME_HEADER, HeaderValue::from_static(name)); - Event::try_from((&headers, &Bytes::from(body.to_string()))).unwrap() - } -} diff --git a/dco2/src/github/event/tests.rs b/dco2/src/github/event/tests.rs new file mode 100644 index 0000000..048ace8 --- /dev/null +++ b/dco2/src/github/event/tests.rs @@ -0,0 +1,326 @@ +use http::HeaderValue; + +use super::*; + +#[test] +fn check_run_event_actions_map_known_and_unknown_values() { + let cases = [ + ("completed", CheckRunEventAction::Other), + ("created", CheckRunEventAction::Other), + ("requested_action", CheckRunEventAction::RequestedAction), + ("rerequested", CheckRunEventAction::Rerequested), + ("unknown", CheckRunEventAction::Other), + ]; + + for (value, expected_action) in cases { + assert_eq!( + parse_action::(value), + expected_action, + "{value}" + ); + } +} + +#[test] +fn check_run_event_with_empty_external_id_and_without_pull_requests() { + let body = r#"{ + "action": "requested_action", + "check_run": {"external_id": "", "head_sha": "head_sha"}, + "installation": {"id": 1}, + "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}}, + "requested_action": {"identifier": "override"} + }"#; + + let Event::CheckRun(event) = parse_event("check_run", body) else { + panic!("unexpected event type"); + }; + + assert_eq!(event.check_run.external_id.as_deref(), Some("")); + assert!(event.check_run.pull_requests.is_empty()); +} + +#[test] +fn check_run_event_with_external_id_and_pull_requests() { + let body = r#"{ + "action": "requested_action", + "check_run": { + "external_id": "123", + "head_sha": "head_sha", + "pull_requests": [{"base": {"repo": {"id": 1}}, "id": 1, "number": 123}] + }, + "installation": {"id": 1}, + "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}}, + "requested_action": {"identifier": "override"} + }"#; + + let Event::CheckRun(event) = parse_event("check_run", body) else { + panic!("unexpected event type"); + }; + + assert_eq!(event.action, CheckRunEventAction::RequestedAction); + assert_eq!(event.check_run.external_id.as_deref(), Some("123")); + assert_eq!( + event.check_run.pull_requests, + vec![CheckRunEventPullRequest { + base: CheckRunEventPullRequestBase { + repo: CheckRunEventPullRequestRepository { id: 1 }, + }, + number: 123, + }] + ); +} + +#[test] +fn check_run_event_without_external_id() { + let body = r#"{ + "action": "requested_action", + "check_run": {"head_sha": "head_sha"}, + "installation": {"id": 1}, + "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}}, + "requested_action": {"identifier": "override"} + }"#; + + let Event::CheckRun(event) = parse_event("check_run", body) else { + panic!("unexpected event type"); + }; + + assert_eq!(event.check_run.external_id, None); +} + +#[test] +fn merge_group_event_actions_map_known_and_unknown_values() { + let cases = [ + ("checks_requested", MergeGroupEventAction::ChecksRequested), + ("destroyed", MergeGroupEventAction::Other), + ("unknown", MergeGroupEventAction::Other), + ]; + + for (value, expected_action) in cases { + assert_eq!( + parse_action::(value), + expected_action, + "{value}" + ); + } +} + +#[test] +fn merge_group_event_checks_requested() { + let body = r#"{ + "action": "checks_requested", + "installation": {"id": 3, "node_id": "I_3"}, + "merge_group": { + "base_ref": "refs/heads/main", + "base_sha": "base_sha", + "head_commit": { + "author": {"email": "octocat@github.com", "name": "Octocat"}, + "committer": {"email": "noreply@github.com", "name": "GitHub"}, + "id": "head_sha", + "message": "Merge pull request #123 from owner/feature", + "timestamp": "2024-01-01T00:00:00Z", + "tree_id": "tree_sha" + }, + "head_ref": "refs/heads/gh-readonly-queue/main/pr-123-base_sha", + "head_sha": "head_sha" + }, + "organization": {"id": 2, "login": "owner"}, + "repository": { + "full_name": "owner/repo", + "id": 1, + "name": "repo", + "node_id": "R_1", + "owner": {"id": 2, "login": "owner", "type": "Organization"}, + "private": false + }, + "sender": {"id": 4, "login": "octocat", "type": "User"} + }"#; + + let Event::MergeGroup(event) = parse_event("merge_group", body) else { + panic!("unexpected event type"); + }; + + assert_eq!(event.action, MergeGroupEventAction::ChecksRequested); + assert_eq!(event.installation.id, 3); + assert_eq!(event.merge_group.head_commit.id, "head_sha"); + assert_eq!(event.repository.name, "repo"); + assert_eq!(event.repository.owner.login, "owner"); +} + +#[test] +fn missing_event_header_is_rejected() { + let body = r#"{ + "action": "requested_action", + "check_run": {"external_id": "123", "head_sha": "head_sha"}, + "installation": {"id": 1}, + "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}}, + "requested_action": {"identifier": "override"} + }"#; + + assert_eq!(try_parse_event(None, body), Err(EventError::MissingHeader)); +} + +#[test] +fn pull_request_event_actions_map_known_and_unknown_values() { + let cases = [ + ("closed", PullRequestEventAction::Other), + ("edited", PullRequestEventAction::Other), + ("opened", PullRequestEventAction::Opened), + ("reopened", PullRequestEventAction::Other), + ("synchronize", PullRequestEventAction::Synchronize), + ("unknown", PullRequestEventAction::Other), + ]; + + for (value, expected_action) in cases { + assert_eq!( + parse_action::(value), + expected_action, + "{value}" + ); + } +} + +#[test] +fn pull_request_event_with_labels() { + let body = r#"{ + "action": "opened", + "installation": {"id": 1}, + "number": 123, + "pull_request": { + "base": {"ref": "main", "sha": "base_sha"}, + "head": {"ref": "feature", "sha": "head_sha"}, + "html_url": "url", + "labels": [{"id": 1, "name": "needs-dco", "color": "d73a4a"}] + }, + "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}} + }"#; + + let Event::PullRequest(event) = parse_event("pull_request", body) else { + panic!("unexpected event type"); + }; + + assert_eq!(event.action, PullRequestEventAction::Opened); + assert_eq!( + event.pull_request.labels, + vec![PullRequestLabel { + name: "needs-dco".to_string() + }] + ); +} + +#[test] +fn pull_request_event_with_organization() { + let body = r#"{ + "action": "opened", + "installation": {"id": 1}, + "number": 123, + "organization": {"id": 1, "login": "org", "node_id": "O_1"}, + "pull_request": { + "base": {"ref": "main", "sha": "base_sha"}, + "head": {"ref": "feature", "sha": "head_sha"}, + "html_url": "url" + }, + "repository": {"id": 1, "name": "repo", "owner": {"login": "org"}} + }"#; + + let Event::PullRequest(event) = parse_event("pull_request", body) else { + panic!("unexpected event type"); + }; + + assert_eq!( + event.organization, + Some(Organization { + login: "org".to_string() + }) + ); +} + +#[test] +fn pull_request_event_without_labels() { + let body = r#"{ + "action": "opened", + "installation": {"id": 1}, + "number": 123, + "pull_request": { + "base": {"ref": "main", "sha": "base_sha"}, + "head": {"ref": "feature", "sha": "head_sha"}, + "html_url": "url" + }, + "repository": {"id": 1, "name": "repo", "owner": {"login": "owner"}} + }"#; + + let Event::PullRequest(event) = parse_event("pull_request", body) else { + panic!("unexpected event type"); + }; + + assert_eq!(event.number, 123); + assert!(event.pull_request.labels.is_empty()); +} + +#[test] +fn pull_request_event_without_organization() { + let cases = [ + r#"{ + "action": "opened", + "installation": {"id": 1}, + "number": 123, + "pull_request": { + "base": {"ref": "main", "sha": "base_sha"}, + "head": {"ref": "feature", "sha": "head_sha"}, + "html_url": "url" + }, + "repository": {"id": 1, "name": "repo", "owner": {"login": "user"}} + }"#, + r#"{ + "action": "opened", + "installation": {"id": 1}, + "number": 123, + "organization": null, + "pull_request": { + "base": {"ref": "main", "sha": "base_sha"}, + "head": {"ref": "feature", "sha": "head_sha"}, + "html_url": "url" + }, + "repository": {"id": 1, "name": "repo", "owner": {"login": "user"}} + }"#, + ]; + + for body in cases { + let Event::PullRequest(event) = parse_event("pull_request", body) else { + panic!("unexpected event type"); + }; + + assert_eq!(event.organization, None); + } +} + +#[test] +fn unsupported_event_is_rejected_without_parsing_payload() { + for name in ["ping", "push"] { + assert_eq!( + try_parse_event(Some(name), "not json"), + Err(EventError::UnsupportedEvent), + "{name}" + ); + } +} + +// Helpers. + +/// Deserialize an event action enum from its webhook string value. +fn parse_action Deserialize<'de>>(value: &str) -> T { + serde_json::from_value(serde_json::Value::String(value.to_string())).unwrap() +} + +/// Parse a webhook event that is expected to be valid. +fn parse_event(name: &str, body: &str) -> Event { + try_parse_event(Some(name), body).unwrap() +} + +/// Parse a webhook event, setting the event name header only when provided. +fn try_parse_event(name: Option<&str>, body: &str) -> Result { + let mut headers = HeaderMap::new(); + if let Some(name) = name { + headers.insert(EVENT_NAME_HEADER, HeaderValue::from_str(name).unwrap()); + } + Event::try_from((&headers, &Bytes::from(body.to_string()))) +} diff --git a/dco2/src/github/testdata/test-app-private-key.pem b/dco2/src/github/testdata/test-app-private-key.pem new file mode 100644 index 0000000..74529b2 --- /dev/null +++ b/dco2/src/github/testdata/test-app-private-key.pem @@ -0,0 +1,30 @@ +Test-only RSA private key (PKCS#1) used by the GitHub client tests. It does +not belong to any GitHub App. Generated with: openssl genrsa -traditional 2048 + +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAo1+60Jp52hpk4ndPblZsGk5X/ew5K6SrDxmoBxJsjy3bMJVH +AbVTiHO9zdIkTaG2vR/3sZ2WO+BGY2OqG/zGk6+3FC97AYMCZpzYVJJagLwOhz7T +VHghKkyZPsWnqFSb1MMpndKgjpmvhwn42651NsKVmmxr9L9g4Tf/ShAiWARsHof9 +uN2pjWS2tKZ8Q7LnlJKNhbJfXuQ57RUu0visGrSXJE4twq9iuOUjSX8VK/MWBuiq +06QYSBaZj5np2B1Pe9Cu9rbjSxBeTMpWGibm6a2Yev8aSIgeyXg2D9+OnQJAm99y +vRH0Tn0eDRRuh19Sia1gH9m9iccrCGIAoCV4LQIDAQABAoIBAC0MC9BSD9A2H+Qb +3sB/Pt6ABJ4kwNzKUkpfGigdCebuz3XVa1dKvqYst8SlMVJgiSkbw+nrGE4ZOH9W +L0T5TW3ScQo1T1bq30IY9ENZeW/uqpjbF10+pHJr3YNj76cn8THYwERem9vF/5Ke +CsrUD0jSnXqPc7LwBBAFpzQuP7IB0OnM1FvggyPS92O2AHwWhhGfGcYJpEIojXqg +Q9r+tmLadEeHcsNPzX2aEQ8BBD+rv+KkxClaq7AXwWCpEwfx3/NxftdRYzI8ksJB +ff+/HdknHfIA26eycBVT/H5gJIKlSBPtN5CmAQfTtZmAFMT3LVZ0KwcX1FPM/gL1 +OScGHTcCgYEA3+iFgp1SFJuO/rkMDSCaBTB18GYk0s4+SsEse4seH2BmJ28dHt84 +WGZ28KLBDQHJnwpf7jKBJ/aHKveFalBxdElzGlGrjMlDMe72SOYTPPUe3rNBvkFl +0+JMQyoI/sx72YcqHEk51qYBaYLi+UBCR0dCTQeNMYA6a6WjBOslza8CgYEAusog +ZhacJkpljO9HnNSkRpVPeUz60evOhR+3DaHnUp1olEW5eszKSz/fCJxM5Iv/WnaX +sx1hkbzcJTKImVPLR4+Iqix3zFns5IeIGZ/QLeaEzr7L0kxPDjV90idCGJN9lnkG +ojYG1AAmkj8LDivvca0O65SHdeSR8T8K4xTsyuMCgYEAl/P5B1c0qP+Y3409fHsv +i24D3A2118pXw+utAHq9CpYlPYXOwXDDkFqZRV1uniEkb2ZfDAwCUtifiq1IQYou +NLjUAHyEa5r6mxyMz5Q0Yh4HwSLt7uv66vycvMf+Ks0jD9EG5wNa2Sz3sF8/IeBW +GoFloVkKnRlkjEFwjJn4ockCgYBnho2MZ22mH0fHY/s55fUilbCVl1/QpzQwPlKz +gI94D3wd6cMSV5yrNjxERnSrmxgtKFuNz3P7VURibW6eJH4fLGNfhgPjw9dzFdcN +9LBqMEBdYgwPg3Gxe14/8rhEbMKHeo59qxn/uBGorr5O3XT5eSQy14B4i/WDUyCS +mU9gZwKBgEWplQXd61YxMW2bs5QOFrVGwqsU8MK7Wn1MZPHQdt9ewKehm7VhUv6R +KaYNvdmWCaYkc8MjUNotMnbHNYIhgPgRUS5QiuqzaI4IKRG2CnqCleT5ervZmyJj +YfnnxhI9q5g9G+FFrukhY7REwgsUBqvo0q+Kh+LgN8gMjfWk3wi2 +-----END RSA PRIVATE KEY----- diff --git a/dco2/templates/summary.md b/dco2/templates/summary.md index 1440bf1..9a7fd4c 100644 --- a/dco2/templates/summary.md +++ b/dco2/templates/summary.md @@ -1,10 +1,11 @@ +{% let table = self.summary_table() %} ## Summary
| | Sha | Message | Pass or fail reason | | -- | ---- | :---- | :---- | -{%+ for entry in commits %} +{%+ for entry in table.commits %} {% let sha_truncated = entry.commit.sha.to_string()|truncate_no_dots(7) %} {% let subject = entry.commit.message.lines().next().unwrap_or_default() %} {% if entry.errors.is_empty() %} @@ -13,3 +14,7 @@ | :red_circle: | [{{ sha_truncated }}]({{ entry.commit.html_url }}) | {{ subject|truncate(50) }} |{% for error in entry.errors %}{% if !loop.first %}{{ " " +}}{% endif %}`{{ error|capitalize }}`{% endfor %} | {% endif +%} {%+ endfor +%} +{% if table.hidden_failing_commits > 0 || table.hidden_passing_commits > 0 ~%} + +Showing {{+ table.commits.len() +}} of {{+ commits.len() +}} commits (not displayed: {%+ if table.hidden_failing_commits > 0 %}{{ table.hidden_failing_commits +}} failing{% if table.hidden_passing_commits > 0 %}, {%+ endif %}{% endif %}{% if table.hidden_passing_commits > 0 %}{{ table.hidden_passing_commits +}} passing{% endif %}). +{%+ endif +%}