App-FuguVM

 view release on metacpan or  search on metacpan

lib/App/FuguVM/Autoinstall.pm  view on Meta::CPAN

# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

use v5.36;

# App::FuguVM::Autoinstall - serve one autoinstall(8) response file.
#
# The module holds the response file and the responder: a small HTTP
# child that answers that one file to one guest. The child binds the
# loopback address only, because a response file can hold the root
# password, and the guest reaches a loopback listener through the QEMU
# gateway. The module is FuguVM policy over generic parts: the file it
# serves is an installer artifact, and the address it serves to is a
# QEMU gateway. Fugu::Proxy stays a proxy, and it gains no
# origin-server mode here.

package App::FuguVM::Autoinstall;
our $VERSION = '0.3.1';

use IO::Socket::INET;
use Fugu::File;

lib/App/FuguVM/Autoinstall.pod  view on Meta::CPAN

    $responder->stop;

=head1 DESCRIPTION

The module holds the response file of an autoinstall(8) run and the
responder: a small HTTP child that answers that one file to one
guest. The OpenBSD installer fetches the file once, at the start of
the install, and the file answers every installer question.

The child binds C<127.0.0.1> only, because a response file can hold
the root password. The guest still reaches it: QEMU user-mode
networking routes a request to the gateway address C<10.0.2.2> to
the host, so no port forward is needed. The child takes a free port
from 8181 to 8280, one range above the mirror proxy.

The child answers one path:

    GET /install.conf     200, the rendered bytes, text/plain
    HEAD /install.conf    200, the headers only
    any other path        404
    any other method      405

lib/App/FuguVM/Autoinstall.pod  view on Meta::CPAN

=head2 render

    App::FuguVM::Autoinstall->render($bytes, $proxy_url)

Return the bytes with every C<@PROXY_URL@> token replaced. The
method is pure, so a test proves it with no socket. With an
undefined or empty proxy URL the bytes return unchanged.

=head1 SECURITY

A response file answers the root password question of the installer.
The child therefore binds the loopback address only, and the tool
never copies the file into the cache or into the state directory.
The image-cache key hashes the file content, and the key is a
truncated digest, not the content.

=head1 SEE ALSO

L<Fugu::Pidfile>, L<Fugu::Process>, L<Fugu::StateFile>,
L<App::FuguVM::Guest>, L<App::FuguVM::Proxy>, L<fuguvm(1)>

lib/App/FuguVM/CLI.pm  view on Meta::CPAN

	    $disk->create( $vm_config->{name}, undef, $found->{path} );
	if ( !defined $created ) {
		$self->{log}->error("Failed to overlay snapshot '$name'");
		return EXIT_ERROR;
	}

	# Reseed what the disk embodies. The next 'fuguvm up' reconciles
	# a checkout whose SSH key differs from the saved one.
	my $meta = $found->{meta};
	$state->mark_installed( $vm_config->{arch} );
	$state->set_root_password( $meta->{root_password} )
	    if defined $meta->{root_password};
	$state->mark_ssh_key_installed( $meta->{installed_ssh_pubkey} )
	    if defined $meta->{installed_ssh_pubkey};
	$state->data->{cached_from} = "$key/$name";
	$state->save;

	$self->{log}->info("Restored snapshot '$name' of $key");
	return EXIT_SUCCESS;
}

sub _snapshot_list ( $self, $cli, $cache, @args )

lib/App/FuguVM/Config.pm  view on Meta::CPAN

			"VM '%s': autoinstall and base_disk contradict each"
			    . " other; one guest has one origin",
			$name
		);
		return 0;
	}

	# Each path directive resolves against the project root, and the
	# file must be readable now. A path that fails at 'up' time, deep
	# inside an install, is a path that failed too late.
	for my $directive (qw(autoinstall base_disk root_password_file)) {
		next if !defined $vm->{$directive};
		my $path = $self->_resolve_path( $vm->{$directive} );
		if ( !-f $path || !-r $path ) {
			$self->{error} =
			    sprintf( "VM '%s': %s file is not readable: %s",
				$name, $directive, $path );
			return 0;
		}
		$vm->{$directive} = $path;
	}

lib/App/FuguVM/Config.pm  view on Meta::CPAN

	if ( $vm->{install_mode} eq 'import' && !$vm->{image_cache} ) {
		$self->{error} = sprintf(
			"VM '%s': base_disk needs the image cache;"
			    . " remove 'image_cache no'",
			$name
		);
		return 0;
	}

	# Outside the expect mode the tool does not know the root
	# password of the image, and it cannot install a key without
	# one.
	if (       $vm->{install_mode} ne 'expect'
		&& defined $vm->{ssh_pubkey}
		&& $vm->{ssh_pubkey} ne ''
		&& !defined $vm->{root_password_file} )
	{
		$self->{error} = sprintf(
			"VM '%s': ssh_pubkey needs root_password_file in the"
			    . " %s mode; add the directive, or unset"
			    . " ssh_pubkey and bake the key into the image",
			$name, $vm->{install_mode} );
		return 0;
	}

	return 1;
}

# $self->_resolve_path($value):

lib/App/FuguVM/Config.pod  view on Meta::CPAN

The loader derives C<install_mode> from the directives, and there is
no C<install_mode> directive. Every module downstream reads that one
field, and no module compares the directives again.

    neither directive     expect       install with install.exp
    autoinstall <file>    autoinstall  install from the response file
    base_disk <path>      import       overlay an existing image

C<autoinstall> names an autoinstall(8) response file. C<base_disk>
names an existing full-disk image; C<qemu-img> reads a qcow2 file and
a raw file. C<root_password_file> names a file whose first line is
the root password of the image. Each of the three values is a path: a
leading tilde expands, and a relative path resolves against the
project root. The loader validates each path one time, and the file
must be readable.

The loader refuses these configurations, and C<error> names the
cause:

=over 4

=item * An absent or unreadable C<autoinstall>, C<base_disk> or
C<root_password_file> file. The message names the resolved path.

=item * C<autoinstall> together with C<base_disk>. One guest has one
origin.

=item * C<base_disk> with C<image_cache no>. An imported base lives
in the cache.

=item * C<ssh_pubkey> without C<root_password_file>, outside the
expect mode. The tool cannot install a key without a password, and
the message names both remedies: add C<root_password_file>, or unset
C<ssh_pubkey> and bake the key into the image.

=back

=head2 error

Return the reason of the last failed C<load_vm>, or C<undef>.

=head2 cache_dir, state_dir, default_vm, ssh_pubkey, bind_address, qemu_version

lib/App/FuguVM/Console.pm  view on Meta::CPAN

		Fugu::Log->default->error( 'Expect script not executable: %s',
			$path );
		return 0;
	}

	return $self->_expect( $path, @args );
}

# $self->run_install($config):
#	Drive a complete OpenBSD installation. The script reads its
#	arguments by position: the root password, the proxy URL, the
#	architecture, and the verify word.
sub run_install ( $self, $config )
{
	my $script = $self->script_path('install.exp');
	unless ( defined $script ) {
		Fugu::Log->default->error('Install script not found');
		return 0;
	}

	return $self->_expect(
		$script,
		$config->{root_password} // 'openbsd',
		$config->{proxy_url}     // 'none',
		$config->{arch},
		$config->{verify} // 'yes',
	);
}

# $self->run_autoinstall($config):
#	Start an autoinstall(8) over the serial console. The script
#	answers the install prompt and the response-file prompt, and
#	the response file answers everything else. The configuration

lib/App/FuguVM/Console.pod  view on Meta::CPAN

=head1 SYNOPSIS

    use App::FuguVM::Console;

    my $console = App::FuguVM::Console->new(
        host => '127.0.0.1',
        port => $console_port,
    );

    $console->run_install({
        root_password => $password,
        proxy_url     => $proxy->guest_url,
        arch          => 'arm64',
        verify        => 'yes',
    }) or die "installation failed\n";

    $console->run_script('reboot.exp');

=head1 DESCRIPTION

The console answers no protocol, so an L<expect(1)> script types at it.

lib/App/FuguVM/Console.pod  view on Meta::CPAN

Return the path of a shipped script, or C<undef>. The method also
works on the class: L<App::FuguVM::DiskCache> hashes the installer script
into its cache key, so it must resolve the script the same way
C<run_install> does.

=head2 run_install

    $console->run_install(\%config)

Drive a complete installation. The configuration gives the root
password, the proxy URL that the guest fetches its sets through, the
architecture, and the verify word (C<yes> or C<no>, default C<yes>).
The method passes them to F<install.exp> in that order, after the
host and the port. The script reads its arguments by position, so the
tool and the script land in one commit.

With C<verify> set to C<yes>, the script does not answer the
"Continue without verification?" prompt of the installer: the
installer of a numbered release verifies each set by itself, so the
prompt reports a broken mirror, and the script exits 1. With C<no>,
the script answers yes and writes a warning that the guest installs

lib/App/FuguVM/DiskCache.pm  view on Meta::CPAN

	};
}

# $self->store($key, $disk_path, $meta):
#	Publish $disk_path as the cached base image for $key. The
#	method builds the entry whole in a sibling temporary directory.
#	Then it publishes the entry with a rename of that directory.
#	Thus no reader sees the base image of one installation beside
#	the metadata of another installation. Such a mismatch would
#	look live. It would then wedge every later boot with a root
#	password that does not open the image.
#
#	Entries are write-once: a rename onto a populated directory
#	fails with ENOTEMPTY, and the existing entry wins. Return the
#	base image path, or undef on any failure.
sub store ( $self, $key, $disk_path, $meta = {} )
{
	return if !defined $key;

	if ( !-f $disk_path ) {
		warn "Cannot cache missing disk image: $disk_path\n";

lib/App/FuguVM/DiskCache.pm  view on Meta::CPAN

					$base, $! );
				return 0;
			};

			my %record = (
				%$meta,
				key        => $key,
				created_at => time,
			);

			# The record carries the guest root password, so
			# the file gets its mode before its content
			return Fugu::File->write_json( "$tmp/" . META_NAME,
				\%record, mode => 0600 ) ? 1 : 0;
		} );
	return if !defined $built;

	return "$target/" . BASE_NAME;
}

# $self->lock_entry($key, $timeout):

lib/App/FuguVM/DiskCache.pm  view on Meta::CPAN

		unlink $tmp_disk;
		return;
	}

	chmod 0400, $tmp_disk or do {
		warn "Cannot set permissions on $tmp_disk: $!\n";
		unlink $tmp_disk;
		return;
	};

	# The root password belongs to the base image. Thus the method
	# copies it from there and does not trust the caller.
	my %record = (
		%$meta,
		key           => $key,
		name          => $name,
		root_password => $entry->{meta}{root_password},
		created_at    => time,
	);

	# Metadata first, atomically, with the mode before the content.
	# To save a name again is normal. A reader that catches the
	# window sees the previous image with the new metadata. Those
	# fields describe the base, which did not change.
	if (
		!Fugu::File->write_json(
			"$dir/$name.json", \%record, mode => 0600

lib/App/FuguVM/DiskCache.pod  view on Meta::CPAN

=head1 SYNOPSIS

    use App::FuguVM::DiskCache;

    my $cache = App::FuguVM::DiskCache->new('~/.cache/fuguvm');
    my $key   = $cache->key($vm_config);

    # Boot from a previous installation
    if (my $hit = $cache->lookup($key)) {
        $disk->create($name, undef, $hit->{base});
        $state->set_root_password($hit->{meta}{root_password});
    }

    # Publish a freshly installed disk
    $cache->store($key, $disk_path, { root_password => $password });

    for my $entry (@{ $cache->list }) {
        printf "%s %d bytes\n", $entry->{key}, $entry->{size};
    }

=head1 DESCRIPTION

An installation of OpenBSD under TCG emulation takes tens of minutes.
This module keeps the result, thus later runs do not do the
installation again. The result is a clean, compacted copy of the

lib/App/FuguVM/DiskCache.pod  view on Meta::CPAN

    <cache_dir>/installed/<key>/base.qcow2              mode 0400
    <cache_dir>/installed/<key>/meta.json               mode 0600
    <cache_dir>/installed/<key>/snapshots/<name>.qcow2  mode 0400
    <cache_dir>/installed/<key>/snapshots/<name>.json   mode 0600

The entries are immutable and write-once. C<store> builds a full entry
in a sibling C<.tmp.*> directory, and then it publishes the entry with
a rename of that directory. Thus a reader never sees the base image of
one installation adjacent to the metadata of a different installation.
Such a mismatch looks live, but it then stops every later boot,
because the root password does not open the image.

=head2 Cache keys

C<key> returns C<< <version>-<arch>-<hash8> >>. C<hash8> is a
truncated SHA-256 over each input that shapes an installed disk, and
the record follows the C<install_mode> of the configuration, because
each mode shapes the disk with different inputs:

=over 4

lib/App/FuguVM/DiskCache.pod  view on Meta::CPAN

=item lookup($key)

The method returns C<< { key, dir, base, meta } >> for a complete
entry. In other cases, it returns C<undef>. A half-written entry is a
miss, not an error.

=item store($key, $disk_path, $meta)

The method compacts C<$disk_path> into the cache as the base image
for C<$key>, and writes C<$meta> adjacent to it. Put the guest
C<root_password> in C<$meta>. The method returns the path of the base
image. It returns C<undef> on a failure, and a try to overwrite a
populated key is one such failure. The caller then degrades to a
standalone disk.

=item lock_entry($key, $timeout)

The method returns an open handle with an exclusive C<flock(2)> on
the lock file of C<$key>:
C<< <cache_dir>/installed/.lock.<key> >>. The wait blocks, with a
deadline of C<$timeout> seconds (default 3600). The method returns

lib/App/FuguVM/DiskCache.pod  view on Meta::CPAN

alphanumeric character, it must hold only word characters, dots, and
dashes, and it must have a bounded length.

=item snapshot_store($key, $name, $disk_path, $meta)

The method flattens the stopped working disk at C<$disk_path> onto
the base image of C<$key>, and publishes the result as the named
layer. Put the state fields that the disk holds in C<$meta>:
C<installed> and the installed SSH public key. With these fields, a
restore can reseed L<App::FuguVM::State>. The method copies the root
password from the metadata of the base itself, and it does not trust
the caller for this value. The method returns the snapshot path, or
C<undef> on a failure.

When a caller saves the same name again, the method replaces the
snapshot. This is the normal second run of a provisioning script.

=item snapshot_lookup($key, $name)

The method returns C<< { key, name, path, base, meta } >> for a
snapshot whose image, metadata, and backing chain all resolve. In

lib/App/FuguVM/DiskCache.pod  view on Meta::CPAN


The method deletes a snapshot and its metadata. Deletion in any order
is safe, because each snapshot is a direct child of the base, never
of a different snapshot.

=back

=head1 SECURITY

F<meta.json> is mode 0600, and it holds the generated guest root
password, the same secret that the VM state directory keeps. The cache
makes the life of this secret longer: the password stays after
C<fuguvm destroy>, and it changes only when the base key changes.

The guest permits root login with a password. QEMU binds the
forwarded SSH port and the serial console port of the guest to the
configured C<bind_address>. The default is C<127.0.0.1>. With
C<bind_address 0.0.0.0>, the password is not a localhost-only secret.
See L<fuguvm(1)>.

=head1 SEE ALSO

L<App::FuguVM::Disk>, L<App::FuguVM::Console>, L<App::FuguVM::Miniroot>, L<App::FuguVM::Guest>,
L<fuguvm(1)>

=cut

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

		$log->error(  "base_disk needs the image cache;"
			    . " run 'fuguvm up' without --no-cache" );
		return EXIT_CONFIG_ERROR;
	}
	if ( $mode eq 'import' && !defined $cache_key ) {
		$log->error("Cannot derive the cache key of the imported base");
		return EXIT_ERROR;
	}

	# Outside the expect mode the operator owns the credential.
	# Seed the state from root_password_file, so the SSH key setup
	# can authenticate. The state then behaves as after an expect
	# install.
	if ( $mode ne 'expect' && defined $config->{root_password_file} ) {
		my $password = $self->_root_password;
		$state->set_root_password($password) if defined $password;
	}

	# Restore from the installed-image cache when there is no disk
	# yet. A miss can mean that a sibling run installs this entry
	# right now. The lock makes this run wait, and the second lookup
	# then uses the entry that the sibling published. A run without
	# the lock still installs correctly, because store() is
	# write-once: it wastes an install, never the cache.
	my $cache_lock;
	if ( !$state->disk_exists && defined $cache_key ) {

lib/App/FuguVM/Guest.pm  view on Meta::CPAN


		# The proxy already runs. The code above started it for the
		# image download. Use the VM-accessible URL for the
		# installation. The VM connects to the host through the
		# gateway.
		my $install_proxy_url = $proxy_vm_url // 'none';

		# The tool owns the credential in the expect mode only.
		# In the autoinstall mode the response file owns it, and
		# the seeding above stored the operator's copy.
		my $root_password;
		if ( $mode eq 'expect' ) {
			$root_password = $self->_root_password;
			$state->set_root_password($root_password);
		}
		else {
			$root_password = $state->get_root_password;
		}

		$log->info("Installing OpenBSD...");
		my $expect = App::FuguVM::Console->new(
			host => $self->connect_address,
			port => $self->console_port,
		);

		if ( $mode eq 'autoinstall' ) {
			my $failure =
			    $self->_run_autoinstall( $expect, $proxy_vm_url );
			return $failure if defined $failure;
		}
		else {
			# Use the generated password for the installation
			my $ok = $expect->run_install(
				$self->_install_config(
					$root_password, $install_proxy_url
				) );
			if ( !$ok ) {
				$log->error("Installation failed");
				return EXIT_EXPECT_FAILED;
			}
		}

		$state->mark_installed( $config->{arch} );
		$log->info("Installation complete");

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

		# The runtime record stays: the restart below uses the
		# same ports, and a sibling that resolves ports in this
		# window must still skip them.

		# Publish the installed disk as a cached base image. A VM
		# that was force stopped can leave the disk mid-write. Thus
		# the code skips that capture and does not publish it.
		if ( defined $cache_key ) {
			if ($clean_exit) {
				$self->_cache_store( $cache, $cache_key,
					$root_password );
			}
			else {
				$log->warning(
"Skipping image cache: installation VM was force stopped"
				);
			}
		}

		# The entry is published, or this run cannot publish it.
		# Either way a waiting sibling can proceed now.

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

		if ( $mode eq 'expect' || $self->_needs_ssh_key_update ) {
			return $self->_complete_ssh_setup;
		}
	}

	# The VM is installed. Check if the SSH key must be installed or
	# updated.
	if ( $self->_needs_ssh_key_update ) {

		# The SSH key is not installed, or it changed in the
		# configuration. Use password authentication to wait for
		# SSH. Then install the key.
		return $self->_complete_ssh_setup;
	}

	# Wait for SSH. An installed VM uses key-based authentication.
	$log->info("Waiting for SSH...");
	if ( !$self->wait_ssh(120) ) {
		$log->error("Timeout waiting for SSH");
		return EXIT_TIMEOUT;
	}

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

	    $disk->create( $config->{name}, undef, $hit->{base} );
	if ( !defined $path ) {
		$log->warning(
			"Cannot overlay cached image $key, installing instead");
		return 0;
	}

	# The base was captured from an installed system. Thus the state
	# that the installer would have written comes from the metadata
	# of the base. The later SSH key install authenticates with the
	# root password. That password is baked into the image.
	$state->mark_installed( $config->{arch} );
	my $password = $hit->{meta}{root_password};
	$state->set_root_password($password) if defined $password;
	$state->data->{cached_from} = $key;
	$state->save;

	$log->info("Using cached image $key");
	return 1;
}

# $self->_cache_store($cache, $key, $root_password):
#	Publish the freshly installed disk as a cached base image. Then
#	replace the working disk with an overlay on that image. The
#	operation is best effort. On any failure it keeps the
#	standalone disk in place and warns. 'up' must never fail
#	because caching failed.
sub _cache_store ( $self, $cache, $key, $root_password )
{
	my $config = $self->{config};
	my $state  = $self->{state};
	my $log    = $self->{log};

	$log->info("Caching installed image as $key...");

	my $base = $cache->store(
		$key,
		$state->disk_path,
		{
			root_password => $root_password,
			version       => $config->{version},
			disk_size     => $config->{disk_size},
		} );
	if ( !defined $base ) {
		$log->warning("Could not cache installed image, continuing");
		return 0;
	}

	if ( !$self->_reparent_disk($base) ) {
		$log->warning(

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

	unlink $saved or $log->warning("Cannot remove $saved: $!");
	return 1;
}

# $self->_import_base($cache, $key):
#	Publish the configured base_disk as the cache entry of $key.
#	The publication costs one conversion of the whole image, and
#	it happens one time for each host: the entry is write-once,
#	and every guest of the project derives the same key. The tool
#	only reads the source file. The metadata holds no root
#	password, because the tool must not invent a credential for an
#	image that it did not install. Return 1 on success.
sub _import_base ( $self, $cache, $key )
{
	my $config = $self->{config};
	my $log    = $self->{log};
	my $source = $config->{base_disk};

	if ( !-f $source ) {
		$log->error(  "The base_disk file is gone: $source"
			    . " (cache miss for $key)" );

lib/App/FuguVM/Guest.pm  view on Meta::CPAN


		# store is write-once, so a sibling can have published
		# the entry inside the window. A lookup decides.
		return defined $cache->lookup($key) ? 1 : 0;
	}

	$log->info("Published imported base: $base");
	return 1;
}

# $self->_install_config($root_password, $proxy_url):
#	Return the configuration of one expect install. The verify
#	flag rides along as the word that the script reads: 'yes' or
#	'no'.
sub _install_config ( $self, $root_password, $proxy_url )
{
	return {
		%{ $self->{config} },
		root_password => $root_password,
		proxy_url     => $proxy_url // 'none',
		verify => ( $self->{config}{verify} // 1 ) ? 'yes' : 'no',
	};
}

# $self->_mirror($proxy):
#	Build the mirror of this guest over the cache of the proxy. A
#	run without a proxy still verifies: the mirror then builds a
#	cache over the same directory.
sub _mirror ( $self, $proxy = undef )

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

	$responder->stop;

	if ( !$ok ) {
		$log->error("Autoinstall failed");
		return EXIT_EXPECT_FAILED;
	}

	return;
}

# $self->_root_password:
#	Return the root password of this guest. The tool owns the
#	credential in the expect mode, so the method generates one
#	there. In every other mode the operator owns it, and the
#	method returns the first line of root_password_file, with no
#	trailing newline, or undef without the directive. Thus the
#	secret has a short life in the process, and no configuration
#	hash carries it.
sub _root_password ($self)
{
	my $config = $self->{config};
	my $mode   = $config->{install_mode} // 'expect';

	if ( $mode eq 'expect' ) {
		$self->{log}->info("Generated secure root password");
		return Fugu::Random->random_password(32);
	}

	my $file = $config->{root_password_file};
	return if !defined $file;

	my $bits = ( stat $file )[2];
	$self->{log}->warning("The group or other users can read $file")
	    if defined $bits && $bits & 0044;

	open my $fh, '<', $file or do {
		$self->{log}->error("Cannot read $file: $!");
		return;
	};

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

	# The answer is one scalar, undef included: a caller builds a
	# hash with it, and a bare return would collapse the pair.
	my $configured = $self->{config}{$directive};
	$configured = undef
	    if defined $configured
	    && $configured eq App::FuguVM::Config::AUTO_PORT();

	return $configured;
}

# $self->wait_ssh($timeout, $password):
#	Wait for SSH to become available. Without a password, the
#	connection uses the SSH agent for authentication. The initial
#	installation gives the root password, because the SSH key is
#	not in yet.
sub wait_ssh ( $self, $timeout = 120, $password = undef )
{
	my $ssh = Fugu::SSH->new(
		host => $self->connect_address,
		port => $self->ssh_port,
		user => 'root',
		( defined $password ? ( password => $password ) : () ),
	);

	return $ssh->wait_available($timeout);
}

# $self->_needs_ssh_key_update:
#	Check if the SSH key must be installed or updated. Return true
#	if no key is installed. Also return true if the configured key
#	differs from the installed key.
sub _needs_ssh_key_update ($self)

lib/App/FuguVM/Guest.pm  view on Meta::CPAN


	# Compare the keys. Normalize the whitespace for the comparison.
	my $configured_normalized = $configured_key =~ s/\s+/ /gr;
	my $installed_normalized  = $installed_key  =~ s/\s+/ /gr;

	return $configured_normalized ne $installed_normalized;
}

# $self->_complete_ssh_setup():
#	Install or update the SSH key on the VM. The method
#	authenticates with the stored root password. It runs to recover
#	from a failed first boot, or when the configured SSH key
#	changed.
sub _complete_ssh_setup ($self)
{
	my $state  = $self->{state};
	my $config = $self->{config};
	my $log    = $self->{log};

	my $root_password = $state->get_root_password;
	if ( !defined $root_password ) {
		$log->error(
			"No root password stored - cannot complete SSH setup");
		return EXIT_ERROR;
	}

	$log->info("Updating SSH key...");

	# Wait for SSH with password authentication
	$log->info("Waiting for SSH...");
	if ( !$self->wait_ssh( 120, $root_password ) ) {
		$log->error("Timeout waiting for SSH");
		return EXIT_TIMEOUT;
	}

	# Install the SSH authorized key
	if ( !$self->_install_ssh_key($root_password) ) {
		$log->error("Failed to install SSH key");
		return EXIT_ERROR;
	}
	$log->info("SSH key installed");

	$log->info("VM ready");
	return EXIT_SUCCESS;
}

# $self->_install_ssh_key($password):
#	Install the SSH public key from the configuration into
#	authorized_keys. The method uses password authentication,
#	because the key is not yet installed.
sub _install_ssh_key ( $self, $password )
{
	my $config = $self->{config};
	my $state  = $self->{state};
	my $log    = $self->{log};

	# Get the SSH public key from the configuration
	my $ssh_pubkey = $config->{ssh_pubkey};
	if ( !defined $ssh_pubkey || $ssh_pubkey eq '' ) {
		$log->error("No ssh_pubkey configured in ~/.fuguvmrc");
		return 0;
	}

	# Connect with the password
	my $ssh = Fugu::SSH->new(
		host     => $self->connect_address,
		port     => $self->ssh_port,
		user     => 'root',
		password => $password,
	);

	# Create the .ssh directory
	my $result =
	    $ssh->run_command('mkdir -p /root/.ssh && chmod 700 /root/.ssh');
	if ( $result->{exit_code} != 0 ) {
		return 0;
	}

	# Write the authorized_keys file

lib/App/FuguVM/Guest.pod  view on Meta::CPAN


=head1 DESCRIPTION

The module runs QEMU for an OpenBSD guest, installs the system on the
first run, and stops it again without corrupting its disk.

Everything that is not QEMU comes from Fugu. Processes and liveness
come from L<Fugu::Process>, which reaps: a QEMU that became a
zombie reads as stopped, and a caller that is about to start a second
one needs that answer. Bounded waits come from L<Fugu::Timeout>. The
random root password comes from L<Fugu::Random>. The guest
connection comes from L<Fugu::SSH>.

=head1 METHODS

=head2 new

    App::FuguVM::Guest->new(config => \%vm, state => $state, log => $log, ...)

Build a controller. C<emulate> forces TCG instead of hardware
acceleration; C<no_cache> ignores the installed-image cache.

lib/App/FuguVM/Guest.pod  view on Meta::CPAN

exit code 9. With C<verify no> the tool downloads without a proof,
logs one warning, and the script waives the installer check with a
warning of its own.

C<up> also exports the C<distfile_cache> byte count as
C<FUGUVM_DISTFILE_LIMIT> before it starts the proxy, so the proxy
child holds the distfile tree under the cap.

=head1 CREDENTIALS

The tool generates a root password only in the C<expect> mode. In the
C<autoinstall> mode the response file owns every credential, and in
the C<import> mode the publisher of the image owns them. Outside the
C<expect> mode, C<up> therefore behaves by configuration:

=over 4

=item * With C<ssh_pubkey> and C<root_password_file>: read the
password from the first line of the file, store it in the state, and
install the key over a password login, exactly as after an expect
install. The tool warns when the file mode lets the group or another
user read the file.

=item * With no C<ssh_pubkey>: wait for SSH with the key of the
operator. The image must trust that key already.

=item * With C<ssh_pubkey> and no C<root_password_file>: the
configuration loader refuses with exit code 3.

=back

A published image and a consuming host share one credential: the
response file of the build sets the root password, the stack keeps
the password in a file, and each consuming host names that file with
C<root_password_file>. The metadata of an imported cache entry holds
no root password, because the tool must not invent a credential for
an image that it did not install.

=head2 down, destroy, start, stop, status

C<down> stops the proxy and then the VM, gracefully, and records a
clean shutdown. C<destroy> stops it and deletes the disk. C<start> and
C<stop> are the narrow forms that do not touch the proxy. C<status>
reports the state, with C<proxy_url> from
C<< App::FuguVM::Proxy->guest_url >>: the proxy URL as the guest
reaches it, or C<undef> while the proxy does not run. The port
changes between runs, so a consumer reads the value from C<status>
and must not write it in a file.

=head2 wait_ssh, is_running

C<wait_ssh> polls until the guest takes an authenticated connection;
with a password argument it authenticates with that password instead
of the SSH agent.

=head2 accel, bind_address, connect_address, ssh_port, console_port

The facts of the guest that C<status> reports and that the guest
connections use.

C<accel> returns C<kvm>, C<hvf> or C<tcg>. While the guest runs, the
answer is the recorded value: a guest that started under
C<--emulate> runs TCG whatever the host can do now. In every other

lib/App/FuguVM/State.pm  view on Meta::CPAN


# $self->clear_runtime:
#	Delete the record, and save the store.
sub clear_runtime ($self)
{
	$self->{store}->delete('runtime');

	return $self;
}

# Root password management. The state stores the password for the
# initial setup. The store writes at mode 0600.
sub set_root_password ( $self, $password )
{
	$self->{store}->set( root_password => $password );
	return $self;
}

sub get_root_password ($self)
{
	return $self->{store}->get('root_password');
}

# SSH key installation state
# The state tracks which SSH key is installed. Thus the system can
# detect when the configured SSH key changed. Then it automatically
# installs the new key.
sub mark_ssh_key_installed ( $self, $ssh_pubkey = undef )
{
	my $data = $self->{store}->data;
	$data->{ssh_key_installed}    = 1;

lib/App/FuguVM/State.pod  view on Meta::CPAN


Whether OpenBSD is installed on the disk. An installed system boots
its own disk and never attaches the miniroot again.

C<mark_installed> takes the architecture of the installed disk. The
argument is required, so no path can forget it. C<get_installed_arch>
returns the recorded architecture, or C<undef>. L<App::FuguVM::Guest>
compares it with the configured value before it boots an existing
disk.

=head2 set_root_password, get_root_password

The password that the installer set. The store writes at mode 0600.

=head2 mark_ssh_key_installed, get_installed_ssh_pubkey

Which SSH public key the guest holds. The state records the key
itself, not only that there is one. Thus a key that changed in the
configuration is installed again on the next C<fuguvm up>.

=head2 mark_running, mark_clean_shutdown, mark_unclean_shutdown, was_unclean_shutdown, clear_shutdown_state

Whether the last stop was clean. C<was_unclean_shutdown> also reports

man/fuguvm/fuguvm.1  view on Meta::CPAN

The default is 0, which turns the distfile cache off.
See
.Sx MIRROR CACHE .
.El
.Pp
The settings of a
.Ic vm
block are as follows.
The first five also stand at the top level of either file, and the
block wins.
.Bl -tag -width "root_password_file" -offset indent
.It Ic bind_address
The host IPv4 address of every forwarded port, in dotted-decimal form.
The default is
.Li 127.0.0.1 .
See
.Sx ADDRESSES AND PORTS .
.It Ic image_cache Cm yes | no
Whether
.Cm up
uses the image cache.

man/fuguvm/fuguvm.1  view on Meta::CPAN

The forwarded SSH port and the serial console port: a number from 1 to
65535, or
.Cm auto .
The defaults are 2222 and 4444.
.It Ic autoinstall
An
.Xr autoinstall 8
response file.
.It Ic base_disk
An existing full-disk image, qcow2 or raw.
.It Ic root_password_file
A file whose first line is the root password of the guest.
.El
.Pp
Each path value expands a leading tilde and resolves a relative path
against the project root.
A
.Ic distfile_cache
line inside a block does not apply, and a
.Ic qemu_version
line there is an error.
A yes/no value that is neither gives a warning and the default.

man/fuguvm/fuguvm.1  view on Meta::CPAN

.Cm up .
.Pp
Without
.Ic autoinstall
and
.Ic base_disk ,
.Cm up
installs with the shipped
.Xr expect 1
script over the serial console.
It generates a random root password, stores it in the state, and
installs the
.Ic ssh_pubkey
over a password login.
A failed script exits with status 9.
.Pp
With
.Ic autoinstall ,
.Cm up
serves the response file to the guest from a loopback HTTP responder,
and the file answers every installer question.
The responder replaces each
.Ql @PROXY_URL@
token in the file with the guest URL of the mirror proxy.

man/fuguvm/fuguvm.1  view on Meta::CPAN

for each host, and overlays the working disk on it.
The tool never writes to the source file.
.Ic autoinstall
and
.Ic base_disk
contradict each other, and
.Ic base_disk
needs
.Ic image_cache yes .
.Pp
Outside the default mode the tool generates no password.
With
.Ic ssh_pubkey
and
.Ic root_password_file ,
.Cm up
reads the password from the file and installs the key over a password
login.
Without
.Ic ssh_pubkey ,
it waits for SSH with the key of the operator, which the image must
trust already.
.Ic ssh_pubkey
without
.Ic root_password_file
is a configuration error.
.Pp
Before the first boot the tool proves the release manifest under the
release key and verifies the miniroot image.
The installer of a numbered release verifies its own sets.
With
.Ic verify yes
the install script therefore stops on the
.Dq Continue without verification?
prompt with status 9, because the prompt reports a broken mirror.

man/fuguvm/fuguvm.1  view on Meta::CPAN

.Sh HISTORY
The
.Nm
utility was first available in 2025, to run the test suite of a daemon
against a real
.Ox
guest.
.Sh AUTHORS
.An Dick Olsson Aq Mt hi@senzilla.io
.Sh SECURITY CONSIDERATIONS
The guest permits root login with a password.
In the default install mode the tool generates that password and
stores it in the state directory and in the
.Pa meta.json
of the cache entry, both with mode 0600.
The cache makes the life of the secret longer: it survives
.Cm destroy
and changes only with the cache key.
.Pp
The console port carries no authentication of its own.
With the default
.Ic bind_address

man/fuguvm/fuguvm.1  view on Meta::CPAN

With
.Li 0.0.0.0
both ports listen on every host interface, so treat such a guest as
open to everyone who reaches the host, and treat a shared
.Ic cache_dir
the same way.
.Pp
An
.Xr autoinstall 8
response file and a
.Ic root_password_file
each hold a root password.
The responder binds the loopback address only, and the tool never
copies either file into the cache or the state directory.
The cache key holds a digest of the response file, not its content.
The tool warns when the group or others can read the password file.
.Pp
The shipped key under
.Pa share/fuguvm/signify/
is a trust anchor.
A human adds each key file, and the commit that adds one states the
comparison against
.Pa /etc/signify/
on a real
.Ox
host of that release.

share/fuguvm/expect/command.exp  view on Meta::CPAN

#!/usr/bin/expect -f
#
# Run a single command on the console and exit
#
# Usage: command.exp <host> <port> <command> [user] [password]
#

# Use the environment variable when it exists. Otherwise use 60.
if {[info exists env(FUGUVM_TIMEOUT)]} {
    set timeout $env(FUGUVM_TIMEOUT)
} else {
    set timeout 60
}

if {[llength $argv] < 3} {
    puts stderr "Usage: command.exp <host> <port> <command> \[user\] \[password\]"
    exit 1
}

set host [lindex $argv 0]
set port [lindex $argv 1]
set cmd [lindex $argv 2]
set user [lindex $argv 3]
set password [lindex $argv 4]

if {$user eq ""} {
    set user "root"
}
if {$password eq ""} {
    set password "openbsd"
}

# Connect to console
spawn telnet $host $port

# Send a newline to trigger login prompt
send "\r"

# Wait for login prompt or shell
expect {
    "login:" {
        send -- "$user\r"
        expect "Password:"
        send -- "$password\r"
    }
    "#" {
        # Already logged in
    }
    eof {
        puts stderr "telnet could not connect to the VM console"
        exit 1
    }
    timeout {
        puts stderr "Timeout waiting for prompt"

share/fuguvm/expect/install.exp  view on Meta::CPAN

#!/usr/bin/expect -f
#
# Automated OpenBSD installation over the serial console
#
# Usage: install.exp <host> <port> <root_password> <proxy_url> <arch> <verify>
#

# Use FUGUVM_TIMEOUT from the environment when it exceeds the
# script default. Slow hosts need this, for example under TCG
# emulation in CI.
proc env_timeout {default} {
    global env
    if {[info exists env(FUGUVM_TIMEOUT)] && $env(FUGUVM_TIMEOUT) > $default} {
        return $env(FUGUVM_TIMEOUT)
    }
    return $default
}

set timeout [env_timeout 300]

set usage "Usage: install.exp <host> <port> <root_password> <proxy_url> <arch> <verify>"

if {[llength $argv] != 6} {
    puts stderr $usage
    exit 1
}

set host [lindex $argv 0]
set port [lindex $argv 1]
set root_password [lindex $argv 2]
set proxy_url [lindex $argv 3]
set arch [lindex $argv 4]
set verify [lindex $argv 5]

if {$root_password eq ""} {
    set root_password "openbsd"
}

if {$proxy_url eq ""} {
    set proxy_url "none"
}

# The configuration loader of fuguvm validates the value, so this
# exit guards a manual run only.
if {$arch ne "amd64" && $arch ne "arm64"} {
    puts stderr $usage

share/fuguvm/expect/install.exp  view on Meta::CPAN


# IPv6 address
expect "IPv6 address" { respond "none" }

# Done with network interfaces
expect "Network interface to configure?" { respond "done" }

# Password for root. Wait for the actual prompt.
expect "Password for root account?" 
sleep 0.5
send -- "$root_password\r"

expect "Password for root account? (again)" 
sleep 0.5
send -- "$root_password\r"

# Start sshd
expect "Start sshd(8)" { respond "yes" }

# Only the amd64 machine has a display adapter, so only its installer
# asks about X. The guest is headless, so xenodm stays off. The
# installer then offers to keep the console on com0. Accept it, and
# accept the default speed.
if {$arch eq "amd64"} {
    expect "started by xenodm" { respond "no" }

share/fuguvm/expect/login.exp  view on Meta::CPAN

#!/usr/bin/expect -f
#
# Simple login automation for OpenBSD VM
#
# Usage: login.exp <host> <port> [user] [password]
#

# Use FUGUVM_TIMEOUT from the environment when it exceeds the
# script default. Slow hosts need this, for example under TCG
# emulation in CI.
proc env_timeout {default} {
    global env
    if {[info exists env(FUGUVM_TIMEOUT)] && $env(FUGUVM_TIMEOUT) > $default} {
        return $env(FUGUVM_TIMEOUT)
    }
    return $default
}

set timeout [env_timeout 30]

if {[llength $argv] < 2} {
    puts stderr "Usage: login.exp <host> <port> \[user\] \[password\]"
    exit 1
}

set host [lindex $argv 0]
set port [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]

if {$user eq ""} {
    set user "root"
}
if {$password eq ""} {
    set password "openbsd"
}

# Connect to console
spawn telnet $host $port

# Send a newline to trigger login prompt
send "\r"

# Wait for login prompt
expect {

share/fuguvm/expect/login.exp  view on Meta::CPAN

    eof {
        puts stderr "telnet could not connect to the VM console"
        exit 1
    }
    timeout {
        puts stderr "Timeout waiting for login prompt"
        exit 1
    }
}

# Enter password
expect "Password:" {
    send -- "$password\r"
}

# Wait for shell prompt
expect {
    "#" {
        puts "Login successful"
        exit 0
    }
    "$" {
        puts "Login successful"

share/fuguvm/fuguvm.conf.sample  view on Meta::CPAN

#     ssh_port     2222
#     console_port 4444
#     bind_address 127.0.0.1
#
#     # Optional: install from an autoinstall(8) response file, or
#     # overlay an existing image instead of an installation. The two
#     # directives contradict each other. See fuguvm(1).
#     # autoinstall  install.conf
#     # base_disk    ~/images/openbsd-78-amd64.qcow2
#
#     # Optional: the file whose first line is the root password of
#     # the image, for the SSH key setup outside the default install.
#     # root_password_file ~/images/openbsd-78.pass
# }

t/fuguvm/cli.t  view on Meta::CPAN

    my $has_qemu = `which qemu-img 2>/dev/null`;
    skip 'qemu-img not installed', 4 unless $has_qemu;

    my $project = _cache_project();
    my $cache = App::FuguVM::DiskCache->new("$project/cache");
    my $key = '7.8-arm64-cafebabe';

    my $source = "$project/source.qcow2";
    system('qemu-img', 'create', '-f', 'qcow2', $source, '16M') == 0
	or skip 'cannot create a test disk image', 4;
    my $base = $cache->store($key, $source, { root_password => 'pw' });

    # A working disk in this checkout, backed by the cached entry
    my $state_dir = "$project/.fuguvm/state";
    App::FuguVM::Disk->new($state_dir)->create('default', undef, $base);

    # This test process stands in for a live QEMU
    make_path("$state_dir/default");
    open my $pidfh, '>', "$state_dir/default/vm.pid" or die $!;
    print $pidfh "$$\n";
    close $pidfh;

t/fuguvm/cli.t  view on Meta::CPAN

    $disk->create('default', '16M');
    my $state = App::FuguVM::State->new($state_dir, 'default');
    $state->mark_installed('arm64');

    local $SIG{__WARN__} = sub {};
    is(App::FuguVM::CLI->run("--project=$project", '--quiet',
	    'snapshot', 'save', 'deps'),
	1, 'a standalone disk is a diagnosed error, not a crash');

    # Rebuild the disk as an overlay on a cached base
    my $base = $cache->store($key, $source, { root_password => 'pw' });
    unlink $disk->path('default');
    $disk->create('default', undef, $base);

    is(App::FuguVM::CLI->run("--project=$project", '--quiet',
	    'snapshot', 'save', 'deps'),
	0, 'save succeeds on a disk backed by a cached image');
    ok(defined $cache->snapshot_lookup($key, 'deps'), 'the snapshot exists');

    is(App::FuguVM::CLI->run("--project=$project", '--quiet',
	    'snapshot', 'list'),

t/fuguvm/cli.t  view on Meta::CPAN

    # Restore from nothing. No disk and no state exist, as in a
    # fresh checkout.
    unlink $disk->path('default');
    unlink "$state_dir/default/status";
    is(App::FuguVM::CLI->run("--project=$project", '--quiet',
	    'snapshot', 'restore', 'deps'),
	0, 'restore works with no disk and no state');

    my $reseeded = App::FuguVM::State->new($state_dir, 'default');
    ok($reseeded->is_installed, 'restore reseeds installed state');
    is($reseeded->get_root_password, 'pw',
	'restore reseeds the root password from the base');

    # A running VM refuses both save and restore
    open my $pidfh, '>', "$state_dir/default/vm.pid" or die $!;
    print $pidfh "$$\n";
    close $pidfh;

    is(App::FuguVM::CLI->run("--project=$project", '--quiet',
	    'snapshot', 'save', 'deps'),
	5, 'save refuses while the VM is running');
    is(App::FuguVM::CLI->run("--project=$project", '--quiet',

t/fuguvm/cli.t  view on Meta::CPAN

    my $has_qemu = `which qemu-img 2>/dev/null`;
    skip 'qemu-img not installed', 4 unless $has_qemu;

    my $project = _cache_project();
    my $cache = App::FuguVM::DiskCache->new("$project/cache");
    my $key = $cache->key(App::FuguVM::Config->new($project)->load_vm('default'));

    my $source = "$project/source.qcow2";
    system('qemu-img', 'create', '-f', 'qcow2', $source, '16M') == 0
	or skip 'cannot create a test disk image', 4;
    my $base = $cache->store($key, $source, { root_password => 'pw' });
    App::FuguVM::Disk->new("$project/.fuguvm/state")
	->create('default', undef, $base);
    App::FuguVM::State->new("$project/.fuguvm/state", 'default')->mark_installed('arm64');

    is(_capture_stdout($project, 'snapshot', 'list', '--names'), '',
	'nothing on stdout when there are no snapshots');

    App::FuguVM::CLI->run("--project=$project", '--quiet',
	'snapshot', 'save', 'deps-aaa');
    App::FuguVM::CLI->run("--project=$project", '--quiet',

t/fuguvm/cli.t  view on Meta::CPAN

	    'image', 'export', $target),
	1, 'a guest with no disk exits 1');

    # A working disk on a cached base
    my $cache = App::FuguVM::DiskCache->new("$project/cache");
    my $key = $cache->key(
	App::FuguVM::Config->new($project)->load_vm('default'));
    my $source = "$project/source.qcow2";
    system('qemu-img', 'create', '-f', 'qcow2', $source, '16M') == 0
	or skip 'cannot create a test disk image', 14;
    my $base = $cache->store($key, $source, { root_password => 'pw' });
    App::FuguVM::Disk->new($state_dir)->create('default', undef, $base);
    App::FuguVM::State->new($state_dir, 'default')->mark_installed('arm64');

    # A running guest refuses with 5. The test writes its own
    # process ID, so Fugu::Process->is_alive reports a live guest.
    make_path("$state_dir/default");
    open my $pidfh, '>', "$state_dir/default/vm.pid" or die $!;
    print $pidfh "$$\n";
    close $pidfh;
    is(App::FuguVM::CLI->run("--project=$project", '--quiet',

t/fuguvm/cli.t  view on Meta::CPAN

{
    my ($cache, $key) = @_;
    my $dir = $cache->entry_dir($key);
    make_path($dir);

    open my $bh, '>', "$dir/base.qcow2" or die $!;
    print $bh 'not a real image';
    close $bh;

    open my $mh, '>', "$dir/meta.json" or die $!;
    print $mh qq({"key":"$key","created_at":1,"root_password":"pw"});
    close $mh;

    return $dir;
}

t/fuguvm/config.t  view on Meta::CPAN

# install_mode, and each refusal at the configuration boundary
{
    my $tmpdir = tempdir(CLEANUP => 1);
    my $homedir = tempdir(CLEANUP => 1);
    local $ENV{HOME} = $homedir;
    make_path("$tmpdir/.fuguvm/vms");

    # The files that the directives point at
    for my $seed (["$tmpdir/install.conf", "System hostname = image\n"],
	["$tmpdir/base.qcow2", 'not a real image'],
	["$homedir/password", "secret\n"]) {
	open my $fh, '>', $seed->[0] or die $!;
	print $fh $seed->[1];
	close $fh;
    }

    my $write = sub ($body) {
	open my $fh, '>', "$tmpdir/.fuguvmrc" or die $!;
	print $fh $body;
	close $fh;
	return App::FuguVM::Config->new($tmpdir);

t/fuguvm/config.t  view on Meta::CPAN

    is($vm->{autoinstall}, "$tmpdir/install.conf",
	'a relative path resolves against the project root');

    $config = $write->("vm \"import\" {\n    base_disk base.qcow2\n}\n");
    $vm = $config->load_vm('import');
    is($vm->{install_mode}, 'import', 'base_disk derives the import mode');
    is($vm->{base_disk}, "$tmpdir/base.qcow2",
	'and its path resolves the same way');

    $config = $write->(
	"vm \"tilde\" {\n    root_password_file ~/password\n}\n");
    is($config->load_vm('tilde')->{root_password_file},
	"$homedir/password", 'a leading tilde expands');

    # An absent file is a refusal that names the resolved path
    $config = $write->("vm \"gone\" {\n    autoinstall absent.conf\n}\n");
    is($config->load_vm('gone'), undef,
	'an absent autoinstall file makes load_vm return undef');
    like($config->error, qr{\Q$tmpdir/absent.conf\E},
	'and error names the resolved path');

    $config = $write->("vm \"gone\" {\n    base_disk absent.qcow2\n}\n");
    is($config->load_vm('gone'), undef,

t/fuguvm/config.t  view on Meta::CPAN


    # An imported base lives in the cache, so the cache must be on
    $config = $write->("vm \"import\" {\n"
	. "    base_disk base.qcow2\n"
	. "    image_cache no\n"
	. "}\n");
    is($config->load_vm('import'), undef,
	'base_disk with image_cache no makes load_vm return undef');
    like($config->error, qr/image cache/, 'and error names the cause');

    # ssh_pubkey without root_password_file refuses outside the
    # expect mode, because the tool cannot authenticate
    for my $origin ('autoinstall install.conf', 'base_disk base.qcow2') {
	$config = $write->("ssh_pubkey ssh-ed25519 KEY test\@host\n"
	    . "vm \"keyed\" {\n    $origin\n}\n");
	is($config->load_vm('keyed'), undef,
	    "ssh_pubkey with no root_password_file refuses ($origin)");
	like($config->error, qr/root_password_file/,
	    'and error names one remedy');
	like($config->error, qr/ssh_pubkey/, 'and the other');
    }

    $config = $write->("ssh_pubkey ssh-ed25519 KEY test\@host\n"
	. "vm \"keyed\" {\n"
	. "    autoinstall install.conf\n"
	. "    root_password_file ~/password\n"
	. "}\n");
    ok(defined $config->load_vm('keyed'),
	'root_password_file satisfies the refusal');

    $config = $write->("ssh_pubkey ssh-ed25519 KEY test\@host\n"
	. "vm \"keyed\" {\n}\n");
    ok(defined $config->load_vm('keyed'),
	'the expect mode needs no password file');
    is($config->error, undef, 'and error returns undef after it');
}

# Test VM block with unquoted name
{
    my $tmpdir = tempdir(CLEANUP => 1);
    make_path("$tmpdir/.fuguvm/vms");
    
    open my $fh, '>', "$tmpdir/.fuguvmrc";
    print $fh "vm simple {\n";

t/fuguvm/console.t  view on Meta::CPAN

# that each script documents.

use v5.36;
use Test::More;
use FindBin qw($RealBin);
use lib "$RealBin/../../lib";
use Fugu::TestLog;

use_ok('App::FuguVM::Console');

# run_install passes the root password, the proxy URL, the
# architecture and the verify word, in that order, after the host and
# the port that _expect adds.
{
    my $console = App::FuguVM::Console->new(host => '127.0.0.1', port => 4444);

    my @seen;
    {
	no warnings 'redefine';
	local *App::FuguVM::Console::_expect = sub ($self, $script, @args) {
	    @seen = ($script, @args);
	    return 1;
	};
	ok($console->run_install({
	    root_password => 'secret',
	    proxy_url     => 'http://10.0.2.2:8080',
	    arch          => 'arm64',
	    verify        => 'no',
	}), 'run_install dispatches');
    }

    like($seen[0], qr/install\.exp$/, 'the script is install.exp');
    is_deeply([ @seen[1 .. 4] ],
	['secret', 'http://10.0.2.2:8080', 'arm64', 'no'],
	'the arguments arrive in the documented order');

t/fuguvm/diskcache.t  view on Meta::CPAN

	my $cache = App::FuguVM::DiskCache->new("$tmp/cache");
	my $key   = '7.8-arm64-abcd1234';

	my $disk = "$tmp/disk.qcow2";
	system( 'qemu-img', 'create', '-f', 'qcow2', $disk, '64M' )
	    == 0
	    or skip 'cannot create a test disk image', 19;

	# Store an entry. Look it up again.
	my $base = $cache->store( $key, $disk,
		{ root_password => 's3cret', version => '7.8' } );
	ok( defined $base, 'store returns the published base image path' );
	is( $base, $cache->base_path($key), 'stored at the expected path' );
	ok( -f $base, 'base image exists' );

	is( sprintf( '%04o', ( stat $base )[2] & 07777 ),
		'0400', 'base image is read-only' );
	is(
		sprintf( '%04o',
			( stat $cache->entry_dir($key) . '/meta.json' )[2]
			    & 07777 ),
		'0600',
		'metadata is owner-only: it holds the root password'
	);

	my $hit = $cache->lookup($key);
	ok( defined $hit, 'lookup hits after store' );
	is( $hit->{meta}{root_password},
		's3cret', 'the root password round-trips' );
	is( $hit->{meta}{key}, $key, 'metadata echoes the key' );
	ok( $hit->{meta}{created_at} > 0, 'metadata records a creation time' );

	# The base is a real, self-standing qcow2
	my $out = qx{qemu-img info --output=json "$base" 2>/dev/null};
	my $info = eval { JSON::XS::decode_json($out) };
	is( $info->{format}, 'qcow2', 'the base is a qcow2 image' );
	ok( !defined $info->{'backing-filename'},
		'the base stands alone: no backing file of its own' );

	# Listing
	my $entries = $cache->list;
	is( scalar @$entries, 1, 'list finds the entry' );
	is( $entries->[0]{key}, $key, 'list reports the key' );
	ok( $entries->[0]{size} > 0, 'list reports a size' );
	is_deeply( $entries->[0]{snapshots}, [], 'no snapshots yet' );

	# Write-once: a second store must not replace a populated entry
	my $again = do {
		local $SIG{__WARN__} = sub { };
		$cache->store( $key, $disk, { root_password => 'other' } );
	};
	is( $again, undef, 'store refuses to overwrite a populated key' );
	is( $cache->lookup($key)->{meta}{root_password},
		's3cret', 'the original entry survives the refusal' );

	# A failed store leaves no temporary tree behind
	my $failed = do {
		local $SIG{__WARN__} = sub { };
		$cache->store( 'other-key', "$tmp/no-such-disk.qcow2", {} );
	};
	is( $failed, undef, 'store of a missing disk fails' );

	my $orphans = _temp_trees( $cache->installed_dir );

t/fuguvm/diskcache.t  view on Meta::CPAN

	require App::FuguVM::Disk;

	my $tmp   = tempdir( CLEANUP => 1 );
	my $cache = App::FuguVM::DiskCache->new("$tmp/cache");
	my $key   = '7.8-arm64-0f0f0f0f';

	my $source = "$tmp/source.qcow2";
	system( 'qemu-img', 'create', '-f', 'qcow2', $source, '64M' ) == 0
	    or skip 'cannot create a test disk image', 5;

	my $base = $cache->store( $key, $source, { root_password => 'pw' } );
	ok( defined $base, 'base image published' );

	my $disk = App::FuguVM::Disk->new("$tmp/state");
	my $path = $disk->create( 'default', undef, $base );
	ok( defined $path, 'overlay created without an explicit size' );

	is( $disk->backing_file('default'),
		$base, 'the overlay is backed by the cached base' );

	my $info = $disk->info('default');

t/fuguvm/diskcache.t  view on Meta::CPAN


	require App::FuguVM::Disk;

	my $tmp   = tempdir( CLEANUP => 1 );
	my $cache = App::FuguVM::DiskCache->new("$tmp/cache");
	my $key   = '7.8-arm64-5a5a5a5a';

	my $source = "$tmp/source.qcow2";
	system( 'qemu-img', 'create', '-f', 'qcow2', $source, '64M' ) == 0
	    or skip 'cannot create a test disk image', 16;
	my $base = $cache->store( $key, $source, { root_password => 'pw' } );

	# A working overlay, the shape a snapshot comes from
	my $disk = App::FuguVM::Disk->new("$tmp/state");
	$disk->create( 'default', undef, $base );
	my $disk_path = $disk->path('default');

	is( $cache->snapshot_lookup( $key, 'deps' ),
		undef, 'no snapshot before one is saved' );
	is_deeply( $cache->snapshot_list($key), [], 'and none listed' );

	my $path = $cache->snapshot_store( $key, 'deps', $disk_path,
		{ installed => 1, installed_ssh_pubkey => 'ssh-ed25519 AAA' } );
	ok( defined $path, 'snapshot_store publishes a layer' );
	is( sprintf( '%04o', ( stat $path )[2] & 07777 ),
		'0400', 'the snapshot image is read-only' );

	my $found = $cache->snapshot_lookup( $key, 'deps' );
	ok( defined $found, 'snapshot_lookup hits' );
	is( $found->{meta}{installed_ssh_pubkey},
		'ssh-ed25519 AAA', 'state fields round-trip' );
	is( $found->{meta}{root_password},
		'pw', 'the root password is taken from the base, not the caller' );

	is( _backing($path), $base, 'the snapshot hangs off base.qcow2' );

	is( scalar @{ $cache->snapshot_list($key) }, 1, 'snapshot_list finds it' );
	is_deeply( $cache->list->[0]{snapshots},
		['deps'], 'cache listing counts it' );

	# A re-save from a disk restored FROM the snapshot must not
	# make the snapshot its own parent. It must not stack chains
	# without bound.

t/fuguvm/diskcache.t  view on Meta::CPAN

		'and the re-saved snapshot still hangs off base.qcow2' );
	is( system("qemu-img check '$disk_path' >/dev/null 2>&1"),
		0, 'the working disk chain still resolves' );

	# Removal
	ok( $cache->snapshot_remove( $key, 'deps' ), 'snapshot_remove' );
	is( $cache->snapshot_lookup( $key, 'deps' ),
		undef, 'the snapshot is gone' );
}

# An imported entry: the metadata holds no root password, and the
# snapshot verbs still work over it
SKIP: {
	skip 'qemu-img not installed', 6 if !$HAS_QEMU_IMG;

	my $tmp   = tempdir( CLEANUP => 1 );
	my $cache = App::FuguVM::DiskCache->new("$tmp/cache");
	my $key   = '7.8-amd64-0a0a0a0a';

	my $outside = "$tmp/openbsd.qcow2";
	system( 'qemu-img', 'create', '-f', 'qcow2', $outside, '64M' ) == 0
	    or skip 'cannot create a test disk image', 6;

	my $base = $cache->store( $key, $outside,
		{ imported_from => $outside, install_mode => 'import' } );
	ok( defined $base, 'store publishes an outside image as an entry' );

	my $hit = $cache->lookup($key);
	ok( defined $hit, 'and lookup finds it' );
	is( $hit->{meta}{imported_from},
		$outside, 'the metadata records the source' );
	ok( !defined $hit->{meta}{root_password},
		'and it holds no root password' );

	is( $cache->key_for_path($base),
		$key, 'key_for_path resolves the imported base' );

	my $path = $cache->snapshot_store( $key, 'base', $outside, {} );
	ok( defined $path && defined $cache->snapshot_lookup( $key, 'base' ),
		'the snapshot verbs work over an imported entry' );
}

# A snapshot whose base is gone reads as a miss. Thus callers can

t/fuguvm/diskcache.t  view on Meta::CPAN

SKIP: {
	skip 'qemu-img not installed', 3 if !$HAS_QEMU_IMG;

	my $tmp   = tempdir( CLEANUP => 1 );
	my $cache = App::FuguVM::DiskCache->new("$tmp/cache");
	my $key   = '7.8-arm64-6b6b6b6b';

	my $source = "$tmp/source.qcow2";
	system( 'qemu-img', 'create', '-f', 'qcow2', $source, '64M' ) == 0
	    or skip 'cannot create a test disk image', 3;
	my $base = $cache->store( $key, $source, { root_password => 'pw' } );

	ok( defined $cache->snapshot_store( $key, 'layer', $source, {} ),
		'a snapshot exists' );

	unlink $base;
	is( $cache->snapshot_lookup( $key, 'layer' ),
		undef, 'it reads as a miss once its base is gone' );

	my $orphan = do {
		local $SIG{__WARN__} = sub { };

t/fuguvm/guest.t  view on Meta::CPAN


	my $root = tempdir(CLEANUP => 1);
	my $cache = App::FuguVM::DiskCache->new("$root/cache");
	my $key = '7.8-arm64-11223344';

	# A stand-in for a freshly installed disk
	my $installed = "$root/installed.qcow2";
	system('qemu-img', 'create', '-f', 'qcow2', $installed, '64M') == 0
	    or skip 'cannot create a test disk image', 14;
	my $base = $cache->store($key, $installed,
	    { root_password => 'from-the-image' });
	ok(defined $base, 'a base image is available to restore from');

	my $state = App::FuguVM::State->new("$root/state", 'default');
	my $vm = App::FuguVM::Guest->new(
		config => { name => 'default', arch => 'arm64', cache_dir => "$root/cache" },
		state  => $state,
		log    => TestLog->new,
	);

	# Restore: the overlay plus the state that the installation
	# leaves behind
	ok($vm->_cache_restore($cache, $key), 'restore reports a cache hit');
	ok($state->disk_exists, 'the working disk exists after a restore');
	ok($state->is_installed, 'the restored VM is marked installed');
	is($state->get_root_password, 'from-the-image',
	    'the root password comes from the image, not a new install');
	is($state->data->{cached_from}, $key,
	    'state records which cached image it came from');

	my $disk = App::FuguVM::Disk->new("$root/state");
	is($disk->backing_file('default'), $base,
	    'the working disk is an overlay on the cached base');

	# A resolvable chain passes verification
	ok($vm->_verify_backing_chain, 'an intact backing chain verifies');

t/fuguvm/guest.t  view on Meta::CPAN

	is_deeply([$auto->_media_args], [],
	    'the restart with no media adds nothing');

	my $expect = App::FuguVM::Guest->new(
	    config => { arch => 'amd64', install_mode => 'expect' });
	is_deeply([$expect->_media_args('/x/miniroot.img')],
	    ['-drive', 'file=/x/miniroot.img,format=raw,if=virtio,readonly=on'],
	    'the expect mode boots its media without -no-reboot');
}

# The root password of each mode
{
	my $root = tempdir(CLEANUP => 1);
	open my $fh, '>', "$root/password" or die $!;
	print $fh "s3cret\nsecond line\n";
	close $fh;
	chmod 0600, "$root/password" or die $!;

	my $imported = App::FuguVM::Guest->new(
		config => { install_mode => 'import',
		    root_password_file => "$root/password" },
		log => TestLog->new,
	);
	is($imported->_root_password, 's3cret',
	    '_root_password returns the first line, with no newline');

	my $bare = App::FuguVM::Guest->new(
		config => { install_mode => 'autoinstall' },
		log    => TestLog->new,
	);
	is($bare->_root_password, undef,
	    'no root_password_file means no password outside expect');

	my $expect = App::FuguVM::Guest->new(
		config => { install_mode => 'expect' },
		log    => TestLog->new,
	);
	my $generated = $expect->_root_password;
	is(length($generated), 32,
	    '_root_password generates a password in the expect mode');
	isnt($expect->_root_password, $generated, 'a fresh one each call');

	# A password file that the group or others can read gives a
	# warning
	chmod 0644, "$root/password" or die $!;
	my $log = TestLog->new;
	my $loud = App::FuguVM::Guest->new(
		config => { install_mode => 'import',
		    root_password_file => "$root/password" },
		log => $log,
	);
	is($loud->_root_password, 's3cret', 'the password still reads');
	ok($log->{warned}, 'and the tool warns about the file mode');
}

# The bind address and the connect address
{
	my $vm = App::FuguVM::Guest->new(
	    config => { bind_address => '10.0.0.1' });
	is($vm->bind_address, '10.0.0.1',
	    'bind_address returns the configured address');
	is($vm->connect_address, '10.0.0.1',

t/fuguvm/guest.t  view on Meta::CPAN

	$state->proxy_pidfile->remove;
}

# The expect install carries the verify flag, as the word that the
# script reads by position
{
	my $on = App::FuguVM::Guest->new(
	    config => { name => 'default', arch => 'arm64' });
	my $config = $on->_install_config('secret', 'http://10.0.2.2:8080');
	is($config->{verify}, 'yes', 'verify defaults to yes');
	is($config->{root_password}, 'secret', 'the password rides along');
	is($config->{proxy_url}, 'http://10.0.2.2:8080', 'and the proxy URL');

	my $off = App::FuguVM::Guest->new(
	    config => { name => 'default', arch => 'arm64', verify => 0 });
	is($off->_install_config('secret', undef)->{verify}, 'no',
	    'verify 0 reads as the word no');
	is($off->_install_config('secret', undef)->{proxy_url}, 'none',
	    'and no proxy reads as none');
}

t/fuguvm/state.t  view on Meta::CPAN


# Test disk paths
{
    my $tmpdir = tempdir(CLEANUP => 1);
    my $state = App::FuguVM::State->new($tmpdir, 'test');
    
    like($state->disk_path, qr/disk\.qcow2$/, 'disk_path ends with disk.qcow2');
    ok(!$state->disk_exists, 'disk_exists returns false when no disk');
}

# Test root password management
{
    my $tmpdir = tempdir(CLEANUP => 1);
    my $state = App::FuguVM::State->new($tmpdir, 'test');
    
    is($state->get_root_password, undef, 'No password initially');
    
    $state->set_root_password('testpass123');
    is($state->get_root_password, 'testpass123', 'Password stored and retrieved');
    
    # Reload the state and make sure that the value persists
    my $state2 = App::FuguVM::State->new($tmpdir, 'test');
    is($state2->get_root_password, 'testpass123', 'Password persisted');
}

# Test SSH key installation state
{
    my $tmpdir = tempdir(CLEANUP => 1);
    my $state = App::FuguVM::State->new($tmpdir, 'test');
    
    is($state->get_installed_ssh_pubkey, undef, 'No pubkey stored initially');
    
    my $test_pubkey = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... test@example';

t/fuguvm/state.t  view on Meta::CPAN

    is_deeply($state->get_runtime,
	{ accel => 'kvm', ssh_port => 2223, console_port => 4445 },
	'set_runtime and get_runtime round-trip the three facts');

    # The record persists across a reload
    my $state2 = App::FuguVM::State->new($tmpdir, 'test');
    is($state2->get_runtime->{ssh_port}, 2223,
	'the record survives a reload');

    # clear_runtime empties the record, and the store survives
    $state2->set_root_password('sentinel');
    $state2->clear_runtime;
    is_deeply($state2->get_runtime, {}, 'clear_runtime empties the record');

    my $state3 = App::FuguVM::State->new($tmpdir, 'test');
    is_deeply($state3->get_runtime, {}, 'and the clearing persists');
    is($state3->get_root_password, 'sentinel',
	'the rest of the store survives the clearing');
}

# ============================================================
# Robustness tests (from ROBUSTNESS-REPORT.md)
# ============================================================

# Issue 1: Extremely long VM name
{
    my $tmpdir = tempdir(CLEANUP => 1);



( run in 2.243 seconds using v1.01-cache-2.11-cpan-f5f21f1076c )