Ejemplo n.º 1
0
    async def verify(self, data: bytes, signature: str) -> Verify:
        # Write the data and signature to temporary files and invoke GnuPG to verify they match ...
        async with aiotempfile(mode="w+b") as datafile:
            await datafile.write(data)
            await datafile.flush()
            async with aiotempfile(mode="w+b") as signaturefile:
                await signaturefile.write(signature.encode("utf-8"))
                await signaturefile.flush()

                args = [
                    "gpg",
                    "--no-options",
                    "--no-emit-version",
                    "--no-tty",
                    "--status-fd",
                    "2",
                    "--homedir",
                    str(self.homedir),
                    "--batch",
                    "--verify",
                    signaturefile.name,
                    datafile.name,
                ]

                process = await asyncio.create_subprocess_exec(
                    *args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                _, stderr = await process.communicate()
                result = await GPGSigner._parse_status(stderr)

                # Assign metadata ...
                result.signer_long = "Signature parsing failed!"
                result.signer_short = "Signature parsing failed!"
                try:
                    result.signer_short = (
                        f"keyid={result.key_id} status={result.status}")
                    # Note: result.* values may be undefined below ...
                    timestamp = time.strftime(
                        "%Y-%m-%d %H:%M:%S",
                        time.gmtime(float(result.sig_timestamp)))
                    result.signer_long = "\n".join([
                        f"{''.ljust(8)}Signature made {timestamp} using key ID {result.key_id}",
                        "".ljust(12) + result.username,
                    ])
                except:  # pylint: disable=bare-except
                    ...

                return result
Ejemplo n.º 2
0
async def test_open_async_with():
    """Test that temporary files can be opened."""
    content_expected = b"This is test content."

    _file = None
    path = None
    async with aiotempfile() as file:
        _file = file
        path = await write_to_file(file, content_expected)
        assert await read_file(file) == content_expected
    assert_closed_and_clean(_file, path)
Ejemplo n.º 3
0
async def test_open_context_manager__anext__():
    """Test that temporary files can be opened."""
    content_expected = b"This is test content."

    aiofiles_context_manager = aiotempfile()
    assert isinstance(aiofiles_context_manager, AiofilesContextManager)

    file = await aiofiles_context_manager.__anext__()
    path = await write_to_file(file, content_expected)
    assert await read_file(file) == content_expected
    await file.close()

    aiofiles_context_manager.close()
    assert_closed_and_clean(file, path)
Ejemplo n.º 4
0
async def test_get_image_layer_to_disk(
    registry_v2_image_source: RegistryV2ImageSource,
    known_good_image: TypingKnownGoodImage,
    **kwargs,
):
    """Test layer retrieval to disk."""
    LOGGER.debug("Retrieving manifest for: %s ...",
                 known_good_image["image_name"])
    manifest = await registry_v2_image_source.get_manifest(
        known_good_image["image_name"], **kwargs)
    config_digest = manifest.get_config_digest()

    LOGGER.debug("Retrieving blob: %s/%s ...", known_good_image["image_name"],
                 config_digest)
    async with aiotempfile(
            mode="w+b",
            prefix=f"tmp{test_get_image_layer_to_disk.__name__}") as file:
        result = await registry_v2_image_source.get_image_layer_to_disk(
            known_good_image["image_name"], config_digest, file, **kwargs)
        LOGGER.debug("Verifying digest of written file ...")
        assert await hash_file(file.name) == config_digest
    assert result.digest == config_digest
Ejemplo n.º 5
0
def test_open_context_manager__await__():
    # pylint: disable=not-an-iterable
    """Test that temporary files can be opened."""
    content_expected = b"This is test content."

    aiofiles_context_manager = aiotempfile()
    assert isinstance(aiofiles_context_manager, AiofilesContextManager)

    # https://stackoverflow.com/a/56114311/1201075
    @coroutine
    def do_test() -> Path:
        file = yield from aiofiles_context_manager.__await__()
        path = yield from write_to_file(file, content_expected)
        content_acutal = yield from read_file(file)
        file.close()
        assert content_acutal == content_expected
        return path

    path = yield from do_test()

    aiofiles_context_manager.close()
    assert_closed_and_clean(aiofiles_context_manager._obj, path)
Ejemplo n.º 6
0
    async def sign(self, data: bytes) -> str:
        if not self.keyid:
            raise RuntimeError("Cannot sign without keyid!")
        if not self.passphrase or len(self.passphrase) < 1:
            raise RuntimeError("Refusing to use an unprotected key!")

        # Write the data to a temporary file and invoke GnuPG to create a detached signature ...
        signaturefile = None
        async with aiotempfile(mode="w+b") as datafile:
            signaturefile = Path(f"{datafile.name}.asc")

            # Write the data to a temporary file
            await datafile.write(data)
            await datafile.flush()

            args = [
                "gpg",
                "--no-options",
                "--no-emit-version",
                "--no-tty",
                "--status-fd",
                "2",
                "--homedir",
                str(self.homedir),
                "--batch",
                "--passphrase-fd",
                "0",
                "--sign",
                "--armor",
                "--detach-sign",
                "--default-key",
                str(self.keyid),
                "--digest-algo",
                "SHA512",
                "--pinentry-mode",
                "loopback",
                datafile.name,
            ]

            process = await asyncio.create_subprocess_exec(
                *args,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            stdout, stderr = await process.communicate(
                self.passphrase.encode("utf-8"))
            if process.returncode:
                LOGGER.debug(
                    "Command Failed:\nArgs: %s\n---stdout---\n%s\n---stderr---\n%s",
                    " ".join(args),
                    stdout.decode("utf-8"),
                    stderr.decode("utf-8"),
                )
                return ""

        # Retrieve the detached signature and cleanup ...
        try:
            async with aiofiles.open(signaturefile) as tmpfile:
                return await tmpfile.read()
        finally:
            signaturefile.unlink(missing_ok=True)