diff --git a/CHANGELOG.md b/CHANGELOG.md index cf2f3aa..9a3c0b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 2.16.0 + +### Added + +- `--no-default-branch` prevents the scan from changing the repository's default + branch or updating a branch head, whatever git or the CI environment detects. + It is mutually exclusive with `--default-branch`. + +### Fixed + +- Automatic default-branch detection honors an explicitly scanned ref. When + `--branch` or `--commit-sha` names a different ref than the CI environment, + the scan is marked as the default branch only if that branch is the default + branch and that commit is on it. This applies to git detection and to the + `DEFAULT_BRANCH` variable with `--scm github`. With `--commit-sha`, the commit + message and committer fallback come from that commit when the checkout has it; + CI actor values still take precedence for the committer. + ## 2.15.7 ### Changed: bump pinned Coana CLI to 15.15.9 diff --git a/README.md b/README.md index a143c62..7e839ea 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,8 @@ Prebuilt workflow examples: - [GitLab CI](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/gitlab-ci.yml) - [Bitbucket Pipelines](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/bitbucket-pipelines.yml) +When a job scans a different ref than the one that triggered it, such as a release tag, pass `--branch` and `--commit-sha` for that ref. [Default Branch Detection](https://github.com/SocketDev/socket-python-cli/blob/main/docs/cli-reference.md#default-branch-detection) covers when to add `--no-default-branch`. + Minimal pattern: ```yaml diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 5aaf923..ace1aa5 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -212,7 +212,7 @@ socketcli [-h] [--api-token API_TOKEN] [--repo REPO] [--workspace WORKSPACE] [-- [--base-scan-id BASE_SCAN_ID | --base-commit-sha BASE_COMMIT_SHA] [--target-path TARGET_PATH] [--sbom-file SBOM_FILE] [--license-file-name LICENSE_FILE_NAME] [--save-submitted-files-list SAVE_SUBMITTED_FILES_LIST] [--save-manifest-tar SAVE_MANIFEST_TAR] [--files FILES] [--sub-path SUB_PATH] [--workspace-name WORKSPACE_NAME] - [--excluded-ecosystems EXCLUDED_ECOSYSTEMS] [--exclude-paths EXCLUDE_PATHS] [--include-dirs INCLUDE_DIRS] [--default-branch] [--generate-license] [--enable-debug] + [--excluded-ecosystems EXCLUDED_ECOSYSTEMS] [--exclude-paths EXCLUDE_PATHS] [--include-dirs INCLUDE_DIRS] [--default-branch | --no-default-branch] [--generate-license] [--enable-debug] [--enable-json] [--enable-sarif] [--sarif-file ] [--sarif-scope {diff,full}] [--sarif-grouping {instance,alert}] [--sarif-reachability {all,reachable,potentially,reachable-or-potentially}] [--enable-gitlab-security] [--gitlab-security-file ] [--disable-overview] [--exclude-license-details] [--allow-unverified] [--disable-security-issue] [--ignore-commit-files] [--disable-blocking] [--disable-ignore] [--enable-diff] [--scm SCM] [--timeout TIMEOUT] [--include-module-folders] @@ -324,6 +324,7 @@ docs.socket.dev use `SOCKET_SECURITY_API_KEY`. Either works. If both are set, | Parameter | Required | Default | Description | |:-------------------------|:---------|:--------|:------------------------------------------------------------------------------------------------------| | `--default-branch` | False | *auto* | Make this branch the default branch (auto-detected from git and CI environment when not specified) | +| `--no-default-branch` | False | False | Prevent the scan from changing the repository's default branch or updating a branch head, whatever git or the CI environment detects. Mutually exclusive with `--default-branch`. See [Default Branch Detection](#default-branch-detection) | | `--include-module-folders` | False | False | Includes supported manifests found under `node_modules`, `bower_components`, and `jspm_packages` in manifest discovery. Equivalent to `--include-dirs node_modules,bower_components,jspm_packages`. Other discovery exclusions still apply. For an inventory of installed packages, see [Packages installed outside the lockfile](troubleshooting.md#packages-installed-outside-the-lockfile). | #### Output Configuration @@ -719,12 +720,32 @@ The CLI now automatically detects repository information from your git environme > For *octopus merges* (three or more parents), Git only reports changes relative to the first parent. This can lead to incomplete or empty file lists if changes only exist relative to other parents. In these cases, differential scanning may be skipped. To ensure coverage, use `--ignore-commit-files` to compare regardless of the detected changes, or specify files explicitly with `--files`. ### Default Branch Detection -The CLI uses intelligent default branch detection with the following priority: +`--default-branch` always marks the scan as the repository's default branch. `--no-default-branch` never does, and the scan does not update a branch head. The two flags are mutually exclusive, on the command line and in a `--config` file. -1. **Explicit `--default-branch` flag**: Takes highest priority when specified -2. **CI environment detection**: Uses CI platform variables (GitHub Actions, GitLab CI, and Bitbucket Pipelines) -3. **Git repository analysis**: Compares current branch with repository's default branch -4. **Fallback**: Defaults to `false` if none of the above methods succeed +Without either flag, the CLI marks the scan when automatic detection finds the default branch: CI platform variables (GitHub Actions, GitLab CI, Bitbucket Pipelines and Buildkite), the `DEFAULT_BRANCH` variable with `--scm github`, or, outside CI, the local checkout. Otherwise the scan is not marked. + +#### Scanning a different ref than the CI run + +When `--branch` or `--commit-sha` names a different ref than the CI variables, automatic detection also checks the ref you passed. The scan is marked only when that branch is the default branch and that commit is in the checkout and reachable from the default branch. These flags never turn detection on. + +The commit check is reachability, so an older commit already in the default branch's history can still qualify: for example, a release tag that was merged back into the default branch, scanned with `--commit-sha` and no `--branch`. Pass `--no-default-branch` when a scan of such a ref must not change the default branch. + +With `--commit-sha`, that commit supplies the commit message (unless `--commit-message` is set) and the git fallback for the committer, when the checkout has it. `--committers` and CI actor values (`GITHUB_ACTOR`, `GITLAB_USER_LOGIN`, `BITBUCKET_STEP_TRIGGERER_UUID`) still take precedence over the commit's committer. + +Example: a GitHub Actions job that runs on `develop`, the default branch, after a release and scans the release tag on `main`: + +```yaml +- uses: actions/checkout@v4 + with: + ref: v1.2.0 + fetch-depth: 0 +- name: Scan the release tag + run: socketcli --target-path . --branch main --commit-sha "$(git rev-parse HEAD)" + env: + SOCKET_SECURITY_API_TOKEN: ${{ secrets.SOCKET_SECURITY_API_TOKEN }} +``` + +`GITHUB_REF` and `GITHUB_SHA` describe `develop`, so without `--branch` and `--commit-sha` the scan would be marked as the default branch with `develop`'s commit message. With them, the scan is recorded on `main` with the tag's commit message and is not marked, because `main` is not the default branch. A job that passes only `--commit-sha` gets the reachability check alone; if the tag commit is also in `develop`'s history, that scan still qualifies, so add `--no-default-branch`. A scan on the default branch also becomes that branch's head scan. `--pending-head` is deprecated and has no effect: it is still accepted so existing pipelines keep working, but it logs a warning. Use `--default-branch` instead. diff --git a/pyproject.toml b/pyproject.toml index 7452ff6..c15612d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.15.7" +version = "2.16.0" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 22abed1..b81e67e 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.15.7' +__version__ = '2.16.0' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/socketsecurity/config.py b/socketsecurity/config.py index 7edb65e..c33306b 100644 --- a/socketsecurity/config.py +++ b/socketsecurity/config.py @@ -167,6 +167,7 @@ class CliConfig: pr_number_explicit: bool = False commit_message: Optional[str] = None default_branch: bool = False + no_default_branch: bool = False target_path: str = "./" scm: str = "api" sbom_file: Optional[str] = None @@ -345,6 +346,7 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': 'pr_number_explicit': pr_number_explicit, 'commit_message': commit_message, 'default_branch': args.default_branch, + 'no_default_branch': args.no_default_branch, 'target_path': os.path.expanduser(args.target_path), 'scm': args.scm, 'sbom_file': args.sbom_file, @@ -510,6 +512,8 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': # this also catches both values arriving via a --config file. if args.base_scan_id and args.base_commit_sha: _usage_error("--base-scan-id and --base-commit-sha are mutually exclusive") + if args.default_branch and args.no_default_branch: + _usage_error("--default-branch and --no-default-branch are mutually exclusive") if args.sarif_scope == "full" and not args.reach: _usage_error("--sarif-scope full requires --reach to be specified") @@ -785,18 +789,27 @@ def create_argument_parser() -> argparse.ArgumentParser: # Branch and Scan Configuration config_group = parser.add_argument_group('Branch and Scan Configuration') - config_group.add_argument( + default_branch_group = config_group.add_mutually_exclusive_group() + default_branch_group.add_argument( "--default-branch", dest="default_branch", action="store_true", help="Make this branch the default branch" ) - config_group.add_argument( + default_branch_group.add_argument( "--default_branch", dest="default_branch", action="store_true", help=argparse.SUPPRESS ) + default_branch_group.add_argument( + "--no-default-branch", + dest="no_default_branch", + action="store_true", + help="Prevent the scan from changing the repository's default branch or updating a " + "branch head, whatever git or the CI environment detects. Mutually exclusive " + "with --default-branch." + ) # Deprecated no-op, still accepted so existing pipelines don't fail to parse. config_group.add_argument( "--pending-head", diff --git a/socketsecurity/core/git_interface.py b/socketsecurity/core/git_interface.py index 98dc412..909a6b9 100644 --- a/socketsecurity/core/git_interface.py +++ b/socketsecurity/core/git_interface.py @@ -34,6 +34,9 @@ def __init__(self, path: str, base_commit_sha: str | None = None): self.base_commit_sha = base_commit_sha self._fetched_ref_commits = {} self._default_branch_name: str | None = None + self._explicit_branch: str | None = None + self._explicit_commit_sha: str | None = None + self._explicit_commit_found = False self.ensure_safe_directory(path) self.repo = Repo(path) assert self.repo @@ -54,6 +57,7 @@ def __init__(self, path: str, base_commit_sha: str | None = None): ((source, sha) for source, sha in ci_commits if sha), (None, None), ) + self._ci_sha = ci_sha if ci_sha: try: @@ -507,6 +511,63 @@ def _is_commit_and_branch_default(self) -> bool: log.debug(f"Error determining if commit and branch are default: {error}") return False + def apply_explicit_ref(self, branch: str | None, commit_sha: str | None) -> None: + """ + Record a --branch or --commit-sha that names a different ref than the CI + variables describe (a workflow_run job that checks out a release tag, for + example). When the checkout has the named commit, it supplies the commit + message, author and committer. Changed-file detection is left as is. + """ + self._explicit_branch = branch if branch and branch != self.branch else None + self._explicit_commit_sha = None + self._explicit_commit_found = False + # Compare with the commit CI names, even when the clone lacks it and + # self.commit fell back to HEAD. + ci_commit = (self._ci_sha or self.commit.hexsha).lower() + if commit_sha and not ci_commit.startswith(commit_sha.lower()): + self._explicit_commit_sha = commit_sha + try: + commit = self.repo.commit( + self.repo.git.rev_parse("--verify", f"{commit_sha}^{{commit}}") + ) + except Exception as error: + log.debug(f"--commit-sha {commit_sha} is not in the local checkout: {error}") + return + self._explicit_commit_found = True + self.commit = commit + self.author = commit.author + self.commit_sha = commit.binsha + self.commit_message = commit.message + self.committer = commit.committer + + def explicit_ref_allows_default_branch(self) -> bool: + """ + Whether the ref recorded by apply_explicit_ref can be the default branch: + the named branch must be the default branch and the named commit must be + in the checkout and on the default branch. + """ + commit_sha = self._explicit_commit_sha + if commit_sha and not self._explicit_commit_found: + log.info( + f"--commit-sha {commit_sha} is not in the local checkout, so the scan " + "is not treated as the default branch. Pass --default-branch to mark it." + ) + return False + if commit_sha and not self.is_commit_on_default_branch(): + log.info( + f"--commit-sha {commit_sha} is not on the default branch, so the scan " + "is not treated as the default branch" + ) + return False + branch = self._explicit_branch + if branch and branch != self.get_default_branch_name(): + log.info( + f"--branch {branch} is not the default branch " + f"{self.get_default_branch_name()}, so the scan is not treated as the default branch" + ) + return False + return True + @property def commit_str(self) -> str: """Return commit SHA as a string""" diff --git a/socketsecurity/socketcli.py b/socketsecurity/socketcli.py index 586d1c0..3f2bd21 100644 --- a/socketsecurity/socketcli.py +++ b/socketsecurity/socketcli.py @@ -228,6 +228,7 @@ def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]: except NoSuchPathError: raise Exception(f"Unable to find path {config.target_path}") + git_repo.apply_explicit_ref(config.branch, config.commit_sha) if not config.repo: config.repo = git_repo.repo_name if not config.commit_sha: @@ -242,6 +243,26 @@ def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]: return True, git_repo +def resolve_default_branch(config: CliConfig, scm, git_repo: Optional[Git]) -> bool: + """ + Whether the scan should become the repository's default branch and head scan. + + --no-default-branch and --default-branch decide on their own. Otherwise the + scan qualifies when the SCM adapter or git detects the default branch, and a + --branch or --commit-sha that names a different ref than CI must also be the + default branch. + """ + if config.no_default_branch: + return False + if config.default_branch: + return True + detected = bool(scm is not None and getattr(scm.config, "is_default_branch", False)) + if git_repo is None: + return detected + detected = detected or bool(git_repo.is_default_branch) + return detected and git_repo.explicit_ref_allows_default_branch() + + def build_socket_sdk(config: CliConfig) -> socketdev: cli_user_agent_string = f"{USER_AGENT_NAME}/{config.version}" return socketdev( @@ -584,11 +605,6 @@ def main_code(config: Optional[CliConfig] = None): os.environ, remote_url=getattr(git_repo, "remote_url", None) if is_repo else None, ) - # Don't override config.default_branch if it was explicitly set via --default-branch flag - # Only use SCM detection if --default-branch wasn't provided - if scm is not None and not config.default_branch: - config.default_branch = scm.config.is_default_branch - # Override files if only-facts-file mode is active if facts_file_to_submit: specified_files = [facts_file_to_submit] @@ -702,20 +718,7 @@ def main_code(config: Optional[CliConfig] = None): f"number={pr_number}, url={pr_context.url or 'unavailable'}" ) - # Determine if this should be treated as default branch - # Priority order: - # 1. If --default-branch flag is explicitly set to True, use that - # 2. If SCM detected it's the default branch, use that - # 3. If it's a git repo, use git_repo.is_default_branch - # 4. Otherwise, default to False - if config.default_branch: - is_default_branch = True - elif scm is not None and hasattr(scm.config, 'is_default_branch') and scm.config.is_default_branch: - is_default_branch = True - elif is_repo and git_repo.is_default_branch: - is_default_branch = True - else: - is_default_branch = False + is_default_branch = resolve_default_branch(config, scm, git_repo if is_repo else None) params = FullScanParams( org_slug=org_slug, diff --git a/tests/core/test_default_branch_flags.py b/tests/core/test_default_branch_flags.py new file mode 100644 index 0000000..19852f7 --- /dev/null +++ b/tests/core/test_default_branch_flags.py @@ -0,0 +1,151 @@ +"""Which default-branch and head-scan parameters a full scan is created with.""" + +import pytest + +from socketsecurity import socketcli +from socketsecurity.core import Core +from socketsecurity.core.git_interface import Git +from tests.core.test_strict_blocking_no_manifest_change import cli_runtime # noqa: F401 +from tests.unit.test_git_interface import ( # noqa: F401 + CI_ENVIRONMENT_VARIABLES, + release_tag_checkout, +) + +REAL_APPLY_GIT_CONTEXT = socketcli.apply_git_context + + +def _scan_params(runtime): + runtime.full_scan.assert_called_once() + return runtime.full_scan.call_args.args[1] + + +def _flags(params): + return params.make_default_branch, params.set_as_pending_head + + +def test_detected_default_branch_makes_the_scan_the_head(cli_runtime): # noqa: F811 + cli_runtime.git_repo.is_default_branch = True + + assert cli_runtime.run() == 0 + + assert _flags(_scan_params(cli_runtime)) == (True, True) + + +@pytest.mark.parametrize("ci_says_default", [True, False]) +def test_no_default_branch_wins_over_detection(cli_runtime, ci_says_default): # noqa: F811 + cli_runtime.git_repo.is_default_branch = ci_says_default + + assert cli_runtime.run(["--no-default-branch"]) == 0 + + assert _flags(_scan_params(cli_runtime)) == (False, False) + + +@pytest.fixture +def github_dispatch_on_develop(cli_runtime, release_tag_checkout, monkeypatch, mocker): # noqa: F811 + """ + A --scm github run with DEFAULT_BRANCH=true, dispatched on develop (the default + branch) while the checkout is the v1.0 release tag on main. Git and the SCM + adapter both detect the default branch from the CI variables. + """ + for name in CI_ENVIRONMENT_VARIABLES: + monkeypatch.delenv(name, raising=False) + for name in ("PR_NUMBER", "EVENT_ACTION", "COMMIT_MESSAGE"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("GITHUB_EVENT_NAME", "workflow_dispatch") + monkeypatch.setenv("GITHUB_REF", "refs/heads/develop") + monkeypatch.setenv("GITHUB_SHA", release_tag_checkout.develop_sha) + monkeypatch.setenv("GITHUB_REPOSITORY", "example/widgets") + monkeypatch.setenv("DEFAULT_BRANCH", "true") + monkeypatch.setenv("GH_API_TOKEN", "test") + mocker.patch.object(Git, "ensure_safe_directory") + monkeypatch.setattr(socketcli, "apply_git_context", REAL_APPLY_GIT_CONTEXT) + # A manifest change keeps the run on the SCM full-scan path. + monkeypatch.setattr(Core, "has_manifest_files", lambda self, files: True) + + def run(flags=()): + return cli_runtime.run( + [ + "--scm", "github", + "--target-path", str(release_tag_checkout.path), + "--branch", "develop", + *flags, + ] + ) + + return run + + +@pytest.mark.parametrize( + "explicit_ref", + [ + pytest.param(["--branch", "main", "--commit-sha", "RELEASE"], id="branch-and-commit"), + pytest.param(["--branch", "main"], id="branch-only"), + pytest.param(["--branch", "develop", "--commit-sha", "RELEASE"], id="commit-off-default"), + ], +) +def test_scm_detection_honors_an_explicit_ref_off_the_default_branch( + cli_runtime, github_dispatch_on_develop, release_tag_checkout, explicit_ref # noqa: F811 +): + flags = [release_tag_checkout.release_sha if f == "RELEASE" else f for f in explicit_ref] + + assert github_dispatch_on_develop(flags) == 0 + + assert _flags(_scan_params(cli_runtime)) == (False, False) + + +def test_scm_detection_honors_an_explicit_commit_when_the_ci_commit_is_not_cloned( + cli_runtime, github_dispatch_on_develop, release_tag_checkout, monkeypatch # noqa: F811 +): + monkeypatch.setenv("GITHUB_SHA", "f" * 40) + + assert github_dispatch_on_develop(["--commit-sha", release_tag_checkout.release_sha]) == 0 + + assert _flags(_scan_params(cli_runtime)) == (False, False) + + +def test_scm_detection_still_marks_the_default_branch_run( + cli_runtime, github_dispatch_on_develop # noqa: F811 +): + assert github_dispatch_on_develop() == 0 + + params = _scan_params(cli_runtime) + assert _flags(params) == (True, True) + assert params.commit_message.strip() == "dev work" + + +def test_explicit_default_branch_overrides_the_explicit_ref_check( + cli_runtime, github_dispatch_on_develop, release_tag_checkout # noqa: F811 +): + assert github_dispatch_on_develop( + ["--branch", "main", "--commit-sha", release_tag_checkout.release_sha, "--default-branch"] + ) == 0 + + assert _flags(_scan_params(cli_runtime)) == (True, True) + + +def test_no_default_branch_overrides_scm_and_git_detection( + cli_runtime, github_dispatch_on_develop # noqa: F811 +): + assert github_dispatch_on_develop(["--no-default-branch"]) == 0 + + assert _flags(_scan_params(cli_runtime)) == (False, False) + + +@pytest.mark.parametrize( + "actor, committer", + [(None, "release@example.com"), ("ci-actor", "ci-actor")], +) +def test_explicit_commit_supplies_message_and_committer_fallback( + cli_runtime, github_dispatch_on_develop, release_tag_checkout, # noqa: F811 + monkeypatch, actor, committer, +): + if actor: + monkeypatch.setenv("GITHUB_ACTOR", actor) + + assert github_dispatch_on_develop( + ["--branch", "main", "--commit-sha", release_tag_checkout.release_sha] + ) == 0 + + params = _scan_params(cli_runtime) + assert params.commit_message.strip() == "release 1.0" + assert params.committers == [committer] diff --git a/tests/core/test_strict_blocking_no_manifest_change.py b/tests/core/test_strict_blocking_no_manifest_change.py index d2ab41b..b48337e 100644 --- a/tests/core/test_strict_blocking_no_manifest_change.py +++ b/tests/core/test_strict_blocking_no_manifest_change.py @@ -80,7 +80,10 @@ def cli_runtime(monkeypatch): socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()) ) git_repo = SimpleNamespace( - changed_files=["README.md"], is_default_branch=False, remote_url=None + changed_files=["README.md"], + is_default_branch=False, + remote_url=None, + explicit_ref_allows_default_branch=lambda: True, ) in_git_repo = {"value": True} diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 27d8d85..5d1fde3 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -196,6 +196,38 @@ def test_help_hides_pending_head_and_shows_repo_slug(self, capsys): assert "--repo " in help_text +class TestDefaultBranchFlags: + """--no-default-branch is the explicit off switch for --default-branch""" + + BASE_ARGS = ["--api-token", "test-token", "--repo", "test-repo"] + + def test_defaults_are_off(self): + config = CliConfig.from_args(self.BASE_ARGS) + assert config.default_branch is False + assert config.no_default_branch is False + + def test_no_default_branch_parses(self): + config = CliConfig.from_args(self.BASE_ARGS + ["--no-default-branch"]) + assert config.no_default_branch is True + assert config.default_branch is False + + @pytest.mark.parametrize("flag", ["--default-branch", "--default_branch"]) + def test_flags_are_mutually_exclusive(self, flag): + with pytest.raises(SystemExit) as exc_info: + CliConfig.from_args(self.BASE_ARGS + [flag, "--no-default-branch"]) + assert exc_info.value.code == 2 + + def test_config_file_values_are_mutually_exclusive(self, tmp_path): + config_path = tmp_path / "socketcli.toml" + config_path.write_text( + "[socketcli]\ndefault_branch = true\nno_default_branch = true\n", + encoding="utf-8", + ) + with pytest.raises(SystemExit) as exc_info: + CliConfig.from_args(self.BASE_ARGS + ["--config", str(config_path)]) + assert exc_info.value.code == 2 + + class TestBaseScanFlags: """Tests for the --base-scan-id / --base-commit-sha diff baseline overrides.""" diff --git a/tests/unit/test_git_interface.py b/tests/unit/test_git_interface.py index b86a4db..4f16365 100644 --- a/tests/unit/test_git_interface.py +++ b/tests/unit/test_git_interface.py @@ -34,6 +34,11 @@ "BITBUCKET_COMMIT", "BITBUCKET_PR_DESTINATION_BRANCH", "BITBUCKET_PR_ID", + # get_formatted_committer prefers these CI usernames over the commit's + # committer, and GitHub Actions sets GITHUB_ACTOR on every run. + "GITHUB_ACTOR", + "GITLAB_USER_LOGIN", + "BITBUCKET_STEP_TRIGGERER_UUID", ) @@ -529,3 +534,124 @@ def test_windows_timeout_kills_the_whole_process_tree(monkeypatch, mocker): assert run.call_args.args[0] == ["taskkill", "/F", "/T", "/PID", "4321"] process.wait.assert_called_once() + + +@pytest.fixture +def release_tag_checkout(tmp_path): + """A repo whose default branch is develop, checked out at a release commit on main.""" + source = tmp_path / "source" + source.mkdir() + _git(source, "init", "-b", "develop") + _git(source, "config", "user.name", "Socket Test") + _git(source, "config", "user.email", "socket@example.com") + (source / "package.json").write_text("{}\n", encoding="utf-8") + _git(source, "add", "package.json") + _git(source, "commit", "-m", "base") + _git(source, "checkout", "-b", "main") + (source / "package.json").write_text('{"version": "1.0.0"}\n', encoding="utf-8") + _git(source, "commit", "-am", "release 1.0", "--author", "Release Bot ") + _git(source, "tag", "v1.0") + _git(source, "checkout", "develop") + (source / "README.md").write_text("dev\n", encoding="utf-8") + _git(source, "add", "README.md") + _git(source, "commit", "-m", "dev work") + checkout = tmp_path / "checkout" + _git(tmp_path, "clone", str(source), str(checkout)) + _git(checkout, "checkout", "v1.0") + return SimpleNamespace( + path=checkout, + base_sha=_git(source, "rev-parse", "develop~1"), + develop_sha=_git(source, "rev-parse", "develop"), + release_sha=_git(source, "rev-parse", "v1.0"), + ) + + +@pytest.fixture +def workflow_run_on_develop(release_tag_checkout, monkeypatch, mocker): + """GITHUB_REF and GITHUB_SHA describe develop while the checkout is the release tag.""" + monkeypatch.setenv("GITHUB_REF", "refs/heads/develop") + monkeypatch.setenv("GITHUB_SHA", release_tag_checkout.develop_sha) + mocker.patch.object(Git, "ensure_safe_directory") + repository = Git(str(release_tag_checkout.path)) + assert repository.is_default_branch is True + return repository + + +def test_explicit_branch_that_is_not_the_default_branch_is_not_default(workflow_run_on_develop): + workflow_run_on_develop.apply_explicit_ref("main", None) + + assert workflow_run_on_develop.explicit_ref_allows_default_branch() is False + + +def test_explicit_commit_off_the_default_branch_is_not_default_and_supplies_details( + release_tag_checkout, workflow_run_on_develop +): + workflow_run_on_develop.apply_explicit_ref(None, release_tag_checkout.release_sha) + + assert workflow_run_on_develop.explicit_ref_allows_default_branch() is False + assert workflow_run_on_develop.commit_str == release_tag_checkout.release_sha + assert workflow_run_on_develop.commit_message.strip() == "release 1.0" + assert workflow_run_on_develop.get_formatted_committer() == "release@example.com" + + +def test_ci_actor_still_wins_over_the_explicit_commit_committer( + release_tag_checkout, workflow_run_on_develop, monkeypatch +): + monkeypatch.setenv("GITHUB_ACTOR", "ci-actor") + + workflow_run_on_develop.apply_explicit_ref(None, release_tag_checkout.release_sha) + + assert workflow_run_on_develop.get_formatted_committer() == "ci-actor" + assert workflow_run_on_develop.commit_message.strip() == "release 1.0" + + +def test_explicit_ref_naming_the_default_branch_keeps_detection( + release_tag_checkout, workflow_run_on_develop +): + workflow_run_on_develop.apply_explicit_ref("develop", release_tag_checkout.develop_sha[:12]) + + assert workflow_run_on_develop.explicit_ref_allows_default_branch() is True + assert workflow_run_on_develop.commit_message.strip() == "dev work" + + +def test_older_commit_in_default_branch_history_still_qualifies( + release_tag_checkout, workflow_run_on_develop +): + workflow_run_on_develop.apply_explicit_ref(None, release_tag_checkout.base_sha) + + assert workflow_run_on_develop.explicit_ref_allows_default_branch() is True + assert workflow_run_on_develop.commit_message.strip() == "base" + + +def test_explicit_commit_is_checked_when_the_ci_commit_is_missing_from_the_clone( + release_tag_checkout, monkeypatch, mocker +): + # The clone lacks GITHUB_SHA, so the commit falls back to HEAD: the release tag. + monkeypatch.setenv("GITHUB_REF", "refs/heads/develop") + monkeypatch.setenv("GITHUB_SHA", "f" * 40) + mocker.patch.object(Git, "ensure_safe_directory") + repository = Git(str(release_tag_checkout.path)) + + repository.apply_explicit_ref(None, release_tag_checkout.release_sha) + + assert repository.explicit_ref_allows_default_branch() is False + + +def test_explicit_commit_missing_from_the_checkout_is_not_default(workflow_run_on_develop): + workflow_run_on_develop.apply_explicit_ref(None, "0" * 40) + + assert workflow_run_on_develop.explicit_ref_allows_default_branch() is False + assert workflow_run_on_develop.commit_message.strip() == "dev work" + + +def test_explicit_ref_never_turns_default_branch_detection_on( + release_tag_checkout, monkeypatch, mocker +): + monkeypatch.setenv("GITHUB_REF", "refs/tags/v1.0") + monkeypatch.setenv("GITHUB_SHA", release_tag_checkout.release_sha) + mocker.patch.object(Git, "ensure_safe_directory") + repository = Git(str(release_tag_checkout.path)) + + repository.apply_explicit_ref("develop", release_tag_checkout.develop_sha) + + assert repository.is_default_branch is False diff --git a/uv.lock b/uv.lock index 1d555ee..4fb3954 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.15.7" +version = "2.16.0" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" },