# Buggy code
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None):
    n_filename = to_native(filename, errors="surrogate_or_strict")
    try:
        member = tar.getmember(n_filename)
    except KeyError:
        raise AnsibleError(
            "Collection tar at '%s' does not contain the expected file '%s'."
            % (to_native(tar.name), n_filename)
        )

    with tempfile.NamedTemporaryFile(dir=b_temp_path, delete=False) as tmpfile_obj:
        bufsize = 65536
        sha256_digest = sha256()
        with _tarfile_extract(tar, member) as tar_obj:
            data = tar_obj.read(bufsize)
            while data:
                tmpfile_obj.write(data)
                tmpfile_obj.flush()
                sha256_digest.update(data)
                data = tar_obj.read(bufsize)

        actual_hash = sha256_digest.hexdigest()

        if expected_hash and actual_hash != expected_hash:
            raise AnsibleError(
                "Checksum mismatch for '%s' inside collection at '%s'"
                % (n_filename, to_native(tar.name))
            )

        b_dest_filepath = os.path.abspath(
            os.path.join(b_dest, to_bytes(filename, errors="surrogate_or_strict"))
        )
        b_parent_dir = os.path.dirname(b_dest_filepath)
        if b_parent_dir != b_dest and not b_parent_dir.startswith(
            b_dest + to_bytes(os.path.sep)
        ):
            raise AnsibleError(
                "Cannot extract tar entry '%s' as it will be placed outside the collection directory"
                % to_native(filename, errors="surrogate_or_strict")
            )

        if not os.path.exists(b_parent_dir):
            # Seems like Galaxy does not validate if all file entries have a corresponding dir ftype entry. This check
            # makes sure we create the parent directory even if it wasn't set in the metadata.
            os.makedirs(b_parent_dir, mode=0o0755)

        shutil.move(
            to_bytes(tmpfile_obj.name, errors="surrogate_or_strict"), b_dest_filepath
        )

        # Default to rw-r--r-- and only add execute if the tar file has execute.
        new_mode = 0o644
        if stat.S_IMODE(member.mode) & stat.S_IXUSR:
            new_mode |= 0o0111

        os.chmod(b_dest_filepath, new_mode)


# Traceback (KeyError)
Exception, this is probably a bug: "filename 'tests/unit/modules/placebo_recordings/aws_direct_connect_link_aggregation_group/nonexistent_lag_status' not found"
the full traceback was:
Traceback (most recent call last):
File "/home/bcoca/work/ansible/bin/ansible-galaxy", line 123, in <module>
exit_code = cli.run()
File "/home/bcoca/work/ansible/lib/ansible/cli/galaxy.py", line 490, in run
context.CLIARGS['func']()
File "/home/bcoca/work/ansible/lib/ansible/cli/galaxy.py", line 1057, in execute_install
self._execute_install_collection(collection_requirements, collection_path)
File "/home/bcoca/work/ansible/lib/ansible/cli/galaxy.py", line 1079, in _execute_install_collection
no_deps, force, force_with_deps, allow_pre_release=allow_pre_release)
File "/home/bcoca/work/ansible/lib/ansible/galaxy/collection.py", line 675, in install_collections
collection.install(output_path, b_temp_path)
File "/home/bcoca/work/ansible/lib/ansible/galaxy/collection.py", line 250, in install
self.install_artifact(b_collection_path, b_temp_path)
File "/home/bcoca/work/ansible/lib/ansible/galaxy/collection.py", line 275, in install_artifact
_extract_tar_dir(collection_tar, file_name, b_collection_path)
File "/home/bcoca/work/ansible/lib/ansible/galaxy/collection.py", line 1387, in _extract_tar_dir
tar_member = tar.getmember(to_native(dirname, errors='surrogate_or_strict'))
File "/usr/lib/python3.7/tarfile.py", line 1752, in getmember
raise KeyError("filename %r not found" % name)
KeyError: "filename 'tests/unit/modules/placebo_recordings/aws_direct_connect_link_aggregation_group/nonexistent_lag_status' not found"

# Fixed code
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None):
    """Extracts a file from a collection tar."""
    n_filename = to_native(filename, errors="surrogate_or_strict")
    with _get_tar_file_member(tar, filename) as (tar_member, tar_obj):
        if tar_member.type == tarfile.SYMTYPE:
            actual_hash = _consume_file(tar_obj)

        else:
            with tempfile.NamedTemporaryFile(
                dir=b_temp_path, delete=False
            ) as tmpfile_obj:
                actual_hash = _consume_file(tar_obj, tmpfile_obj)

        if expected_hash and actual_hash != expected_hash:
            raise AnsibleError(
                "Checksum mismatch for '%s' inside collection at '%s'"
                % (n_filename, to_native(tar.name))
            )

        b_dest_filepath = os.path.abspath(
            os.path.join(b_dest, to_bytes(filename, errors="surrogate_or_strict"))
        )
        b_parent_dir = os.path.dirname(b_dest_filepath)
        if not _is_child_path(b_parent_dir, b_dest):
            raise AnsibleError(
                "Cannot extract tar entry '%s' as it will be placed outside the collection directory"
                % to_native(filename, errors="surrogate_or_strict")
            )

        if not os.path.exists(b_parent_dir):
            # Seems like Galaxy does not validate if all file entries have a corresponding dir ftype entry. This check
            # makes sure we create the parent directory even if it wasn't set in the metadata.
            os.makedirs(b_parent_dir, mode=0o0755)

        if tar_member.type == tarfile.SYMTYPE:
            b_link_path = to_bytes(tar_member.linkname, errors="surrogate_or_strict")
            if not _is_child_path(b_link_path, b_dest, link_name=b_dest_filepath):
                raise AnsibleError(
                    "Cannot extract symlink '%s' in collection: path points to location outside of "
                    "collection '%s'" % (to_native(filename), b_link_path)
                )

            os.symlink(b_link_path, b_dest_filepath)

        else:
            shutil.move(
                to_bytes(tmpfile_obj.name, errors="surrogate_or_strict"),
                b_dest_filepath,
            )

            # Default to rw-r--r-- and only add execute if the tar file has execute.
            tar_member = tar.getmember(
                to_native(filename, errors="surrogate_or_strict")
            )
            new_mode = 0o644
            if stat.S_IMODE(tar_member.mode) & stat.S_IXUSR:
                new_mode |= 0o0111

            os.chmod(b_dest_filepath, new_mode)