view release on metacpan or search on metacpan
consulted, unlike the `docker` CLI, docker-java or Testcontainers.
0.002 2026-05-17 05:36:20Z
- HTTP role: `_request` now accepts a `headers => {}` option to set
extra HTTP request headers. Headers are sanitised against CR/LF
injection. Used by `images->push` to send `X-Registry-Auth`, and
available to any caller that needs custom headers.
- `images->push` now always sends an `X-Registry-Auth` header â the
Docker Engine refuses pushes without it (`HTTP 400: missing
X-Registry-Auth: invalid X-Registry-Auth header: EOF`). A new `auth`
option accepts a hashref of credentials (`username`, `password`,
`serveraddress`, or `identitytoken`) which is JSON-encoded and
base64url-wrapped per the Docker Engine spec. Without `auth` the
header carries an empty JSON object so unauthenticated/public
pushes succeed where they previously failed at the HTTP layer.
0.001 2026-04-29 00:40:43Z
- Initial release as API::Docker
- Docker Engine API client with Unix socket and TCP support
- Auto-negotiate API version from daemon
- Container, Image, Network, Volume, System, and Exec APIs
lib/API/Docker/API/Distribution.pm view on Meta::CPAN
my $docker = API::Docker->new;
# Ask a registry about an image reference without pulling it
my $descriptor = $docker->distribution->inspect('nginx:latest');
# With registry credentials
my $descriptor = $docker->distribution->inspect('private/app:1.0',
auth => {
username => 'someone',
password => 'secret',
},
);
# The same question as a predicate: is that tag already published?
if ($docker->distribution->exists('myrepo/app:1.0', auth => $auth)) {
die "refusing to overwrite a released tag";
}
=head1 DESCRIPTION
lib/API/Docker/API/Distribution.pm view on Meta::CPAN
my $d = eval { $distribution->inspect($ref, response => \%res) };
# $res{status} == 404 here means the registry said no *or* the engine
# has no such route -- see L</exists>, which separates the two.
Options:
=over
=item * C<auth> - Registry credentials, in any shape
L<API::Docker::API::Images/push> accepts them: a HashRef of C<username> /
C<password> / C<serveraddress> / C<identitytoken>, or a pre-encoded base64
string. Sent as C<X-Registry-Auth>. Unlike C<push>, which always sends the
header, it is omitted entirely without this option -- the lookup is then
anonymous, which is what a public image needs
=item * C<response> - HashRef the status line and the response headers are
written into, as for L<API::Docker::Role::HTTP/get>
=back
=head2 exists
lib/API/Docker/API/Images.pm view on Meta::CPAN
=item * C<networkmode> - Network mode during build
=item * C<platform> - Platform (e.g. C<linux/amd64>)
=item * C<target> - Multi-stage build target
=item * C<registry_config> - Registry credentials for the base images the build
pulls, sent as C<X-Registry-Config>. A HashRef mapping each registry hostname
to its AuthConfig --
C<< { 'registry.example:5000' => { username => 'me', password => 'secret' } } >>
-- so a C<FROM private.registry/...> can authenticate, and a build drawing from
several registries can carry all of them at once. A pre-encoded base64 string
is also accepted. Sent only when given. This is B<not> C<auth>/C<X-Registry-Auth>,
which carries a single AuthConfig; C</build> uses the map form. See
L<API::Docker::Role::RegistryAuth>
=item * C<on_event> - CodeRef called with each build event as it arrives,
instead of the ArrayRef being collected and returned; see below
=back
lib/API/Docker/API/Images.pm view on Meta::CPAN
=over
=item * C<fromImage> - Image name to pull (required)
=item * C<tag> - Tag to pull. Defaulted to C<latest> only when C<fromImage>
carries no tag or digest of its own; see above
=item * C<auth> - Registry credentials for pulling from a private registry,
sent as C<X-Registry-Auth>. A HashRef of the usual keys (C<username>,
C<password>, C<serveraddress>, or C<identitytoken>) or a pre-encoded base64
string, exactly as L</push> takes it. Unlike C<push>, the header is sent
B<only> when C<auth> is given -- an anonymous pull carries none, which the
engine reads as the anonymous case. See L<API::Docker::Role::RegistryAuth>
=item * C<on_event> - CodeRef called with each progress event as it arrives,
instead of the ArrayRef being collected and returned. The return value is then
the summary HashRef and a stream failure croaks one event in, exactly as for
L</build>; see L</"Progress as it arrives">
=back
lib/API/Docker/API/Images.pm view on Meta::CPAN
my $history = $images->history('nginx:latest');
Get image history (layers). Returns ArrayRef of layer information.
=head2 push
my $events = $images->push('myrepo/nginx', tag => 'v1');
$images->push('myrepo/nginx', auth => {
username => 'me',
password => 'secret',
serveraddress => 'https://index.docker.io/v1/',
});
Push an image to a registry. Optionally specify C<tag>.
Returns an ArrayRef of progress events, one per object in the engine's
newline-delimited JSON stream, even when the stream carried a single object.
A failed push croaks, by one of two routes depending on the engine -- an
unauthorised push to a private registry is the common case, and it is exactly
lib/API/Docker/API/Images.pm view on Meta::CPAN
the transport's status handling croaks with an L<API::Docker::Error::HTTP> --
which is that same string to anything inspecting C<$@> as text -- before the
stream is ever decoded. That body carries no C<message> key, so the whole
JSON object ends up as the croak text.
Either way the failure is loud. Inspect C<$@> as a string rather than testing
for the exception class, which only the first route produces.
The Docker Engine requires an C<X-Registry-Auth> header on every push,
even for anonymous attempts; the header is always sent. Pass C<auth> as
a hashref of credentials (typical keys: C<username>, C<password>,
C<serveraddress>, or C<identitytoken>), or as a pre-encoded base64 string.
Without C<auth> the header carries an empty JSON object.
Options:
=over
=item * C<tag> - Tag to push
=item * C<auth> - Registry credentials, as above
lib/API/Docker/API/Plugins.pm view on Meta::CPAN
The C<remote> reference is normalised by the daemon, so C<vieux/sshfs> and
C<docker.io/vieux/sshfs:latest> name the same plugin; C<:latest> is the
default when no tag is given.
Options:
=over
=item * C<auth> - Registry credentials for a plugin in a private registry;
HashRef of C<username> / C<password> / C<serveraddress> / C<identitytoken>,
or a pre-encoded base64 string. Sent as C<X-Registry-Auth>. The Engine API
reference does not document this header on this endpoint, but the daemon
reads it here exactly as it does on the pull
=back
=head2 install
my $privileges = $plugins->privileges('vieux/sshfs:latest');
$plugins->install('vieux/sshfs:latest', privileges => $privileges);
lib/API/Docker/API/Plugins.pm view on Meta::CPAN
=back
Returns an ArrayRef of progress events, C<[]> when the engine sent no
progress. Failure is reported by the same two routes as L</install>.
=head2 push
$plugins->push('myrepo/sshfs:v1', auth => {
username => 'me',
password => 'secret',
serveraddress => 'https://index.docker.io/v1/',
});
Push an installed plugin to a registry. B<This writes to a real registry>
under the credentials given.
Options:
=over
=item * C<auth> - Registry credentials; HashRef of C<username> / C<password> /
C<serveraddress> / C<identitytoken>, or a pre-encoded base64 string. Sent as
C<X-Registry-Auth>
=item * C<on_event> - CodeRef called with each progress event as it arrives --
layer by layer, rather than the whole upload in one silence. The return value
is then the summary HashRef; see L</"Progress as it arrives">
=back
Unlike L<API::Docker::API::Images/push>, which sends C<X-Registry-Auth> on
lib/API/Docker/API/System.pm view on Meta::CPAN
sub auth {
my ($self, %opts) = @_;
# Two spellings of the same AuthConfig. The credential keys and the name
# `auth` cannot collide -- the engine's AuthConfig has no `auth` field --
# so both are accepted, but not at once: which one wins would be a silent
# choice about someone's credentials.
my @flat = grep { defined $opts{$_} }
qw( username password email serveraddress identitytoken );
croak __PACKAGE__ . '->auth takes either auth => $config or the credential '
. 'keys themselves, not both (' . join(', ', @flat) . ' given beside auth)'
if defined $opts{auth} && @flat;
my $config = defined $opts{auth}
? $self->_registry_auth_config($opts{auth})
: { map { $_ => $opts{$_} } @flat };
# Stricter than the engine, deliberately. An empty AuthConfig is a valid
# body -- Podman answers it 500 'getting username and password: cannot
# prompt for username without stdin' -- but a credential check with no
# credentials in it is a caller bug, and answering it with the engine's
# message would hide that.
croak __PACKAGE__ . '->auth requires credentials: pass username/password, '
. 'identitytoken, or auth => $config' unless keys %$config;
return $self->client->post('/auth', $config,
%{ $self->_request_options },
(exists $opts{response} ? (response => $opts{response}) : ()));
}
1;
lib/API/Docker/API/System.pm view on Meta::CPAN
my $events = $docker->system->events(
since => time() - 3600,
);
# Disk usage
my $df = $docker->system->df;
# Check registry credentials before doing the work that needs them
my $login = $docker->system->auth(
username => 'me',
password => 'secret',
serveraddress => 'ghcr.io',
);
say $login->{Status}; # Login Succeeded
=head1 DESCRIPTION
This module provides access to Docker system-level operations including daemon
information, version detection, health checks, and event monitoring.
Accessed via C<< $docker->system >>, or through
lib/API/Docker/API/System.pm view on Meta::CPAN
my $usage = $system->df;
Get data usage information (disk usage by images, containers, and volumes).
Returns hashref with C<LayersSize>, C<Images>, C<Containers>, and C<Volumes> arrays.
=head2 auth
my $login = $system->auth(
username => 'me',
password => 'secret',
serveraddress => 'ghcr.io',
);
# Or hand over the same auth argument images->push takes
$system->auth(auth => $auth);
Check a set of registry credentials against the registry, without pulling or
pushing anything. Returns the decoded C<< POST /auth >> response, a HashRef
with C<Status> (C<Login Succeeded>) and, where the registry issues one,
C<IdentityToken>.
lib/API/Docker/API/System.pm view on Meta::CPAN
die "could not reach the registry: $@";
};
Options -- the AuthConfig keys the engine defines, all optional
individually, but at least one is required:
=over
=item * C<username> - Registry account name
=item * C<password> - Its password or token
=item * C<email> - Legacy field, accepted and ignored by current registries
=item * C<serveraddress> - Registry to check against, e.g. C<ghcr.io>.
Omitted, the engine uses its default registry
=item * C<identitytoken> - Bearer token, instead of username and password
=item * C<auth> - The whole AuthConfig at once, in any shape
L<API::Docker::API::Images/push> accepts it: a HashRef, a JSON object, or a
base64url-encoded one. Cannot be combined with the keys above
=item * C<response> - HashRef the status line and the response headers are
written into, as for L<API::Docker::Role::HTTP/get>
=back
lib/API/Docker/API/System.pm view on Meta::CPAN
made.
=head3 What Podman answers
Measured against the rootless Podman socket (5.4.2, API 1.41): the endpoint
exists, but a failed check is B<500 Internal Server Error>, not Docker's 401,
and the message is the registry's own text wrapped by Podman --
C<< {"message":"login attempt to 127.0.0.1:1 failed with status: ..."} >>.
An empty AuthConfig answers
C<< {"message":"login attempt to failed with status: getting username and
password: cannot prompt for username without stdin"} >>, also 500. So the
croak is reliable on both engines while the status behind it is not: test the
outcome, not the number.
=head1 SEE ALSO
=over
=item * L<API::Docker> - Main Docker client
=back
lib/API/Docker/Role/Entity/Plugin.pm view on Meta::CPAN
privileges => $privileges);
Upgrade the plugin in place. C<privileges> is required, as it is on
L<API::Docker::API::Plugins/upgrade>, and C<remote> defaults to
L<API::Docker::Type::Plugin/name> -- which is not what you want for a
plugin installed under a local name, hence
C<< ->plugin_reference >>.
=head2 push
$plugin->push(auth => { username => 'me', password => 'secret' });
Push the plugin to a registry. B<This writes to a real registry> under the
credentials given.
C<push> shadows the Perl builtin inside this package, which is why
L<namespace::clean> is loaded. Always call it as a method.
=head1 SEE ALSO
=over
lib/API/Docker/Role/RegistryAuth.pm view on Meta::CPAN
# The map-header form: X-Registry-Config on /build, hostname -> AuthConfig
my $cfg_header = $self->_registry_config_header($opts{registry_config});
# The body form: the same credentials as a plain HashRef
my $config = $self->_registry_auth_config($opts{auth});
=head1 DESCRIPTION
One AuthConfig, three carriers. The Docker Engine takes registry credentials
as a JSON object with the keys C<username>, C<password>, C<serveraddress>,
C<identitytoken> and C<email>, and moves it around in three shapes:
=over
=item * base64url-encoded in the C<X-Registry-Auth> request header, for
C<< POST /images/{name}/push >>, C<< POST /images/create >>,
C<< GET /distribution/{name}/json >> and the C</plugins> family
=item * as a base64url-encoded B<map> of registry hostname to AuthConfig in
the C<X-Registry-Config> request header, for C<< POST /build >> -- one build
lib/API/Docker/Role/RegistryAuth.pm view on Meta::CPAN
C<_registry_auth_header($auth)> returns the padded base64url value for
C<X-Registry-Auth>. C<undef> gives the anonymous encoding C<e30=>, a HashRef
is JSON-encoded, and a string that already looks base64-encoded is passed
through -- but respelled into the URL-safe alphabet, so a value pre-encoded in
standard base64 (with C<+> or C</>) reaches the wire as the C<->/C<_> the
engine's C<base64.URLEncoding> decoder expects rather than failing there.
C<_registry_config_header($map)> is the same encoding for C<X-Registry-Config>
on C<< POST /build >>. It takes the same shapes, but the HashRef it JSON-encodes
is a B<map> of registry hostname to AuthConfig
(C<< { 'registry.example:5000' => { username => ..., password => ... } } >>),
not a single AuthConfig.
C<_registry_auth_config($auth)> returns the same credentials as a plain
HashRef for a JSON request body. C<undef> gives C<undef> -- whether that is
an error is the endpoint's call, not this role's. A HashRef is copied, a JSON
object is decoded, and a base64url string is decoded back through both
layers. Anything that does not read as an AuthConfig croaks.
=head1 SEE ALSO
lib/API/Docker/Type/AuthConfig.pm view on Meta::CPAN
package API::Docker::Type::AuthConfig;
# ABSTRACT: The body of a C<POST /auth> request
our $VERSION = '0.006';
use API::Docker::Type;
use namespace::clean;
docker username => Str, wire => 'username';
docker password => Str, wire => 'password';
docker email => Str, wire => 'email';
docker serveraddress => Str, wire => 'serveraddress';
1;
lib/API/Docker/Type/AuthConfig.pm view on Meta::CPAN
Generated from the C<AuthConfig> definition of C<spec/v1.51.yaml>, which the
swagger leaves undescribed. C<paths:> says what it is: the body of a C<POST
/auth> request.
=head2 username
Undocumented upstream. The registry account name, C<hannibal> in the
definition's own example. Serialised as C<username> -- spelled out, because
deriving it from the Perl name would produce C<Username>.
=head2 password
Undocumented upstream. Its password, C<xxxx> in the definition's own
example. The swagger's introduction gives the same three keys as the
structure that travels base64url-encoded in C<X-Registry-Auth>, and notes
that an identity token from C<POST /auth> can be sent instead of a username
and password; see L<API::Docker::Role::RegistryAuth>. Serialised as
C<password> -- spelled out, because deriving it from the Perl name would
produce C<Password>.
=head2 email
Email is an optional value associated with the username.
> B<Deprecated>: This field is deprecated since docker 1.11 (API v1.23) and
will be removed in a future release. Serialised as C<email> -- spelled out,
because deriving it from the Perl name would produce C<Email>.
misc/agent-context/.claude/skills/docker-engine-api/examples/python/tests/test_engine_helpers.py view on Meta::CPAN
def test_bad_versions(self):
for value in ('1', '1.2.3', 'v1.51', '1.01', 1.51, None, True):
with self.subTest(value=value), self.assertRaises(CompatibilityError): parse_version(value)
def test_reversed_range(self):
with self.assertRaises(CompatibilityError): self.choose({'ApiVersion':'1.40','MinAPIVersion':'1.51'})
class AuthTests(unittest.TestCase):
def test_empty_padding(self): self.assertEqual(encode_registry_auth({}), 'e30=')
def test_round_trip(self):
obj={'username':'test','password':'äð','serveraddress':'registry.example.com'}
value=encode_registry_auth(obj)
self.assertEqual(json.loads(base64.urlsafe_b64decode(value)), obj)
self.assertNotIn('+',value)
self.assertNotIn('/',value)
def test_reject_non_string(self):
with self.assertRaises(TypeError): encode_registry_auth({'password':123})
class FrameTests(unittest.TestCase):
def test_short_reads(self):
self.assertEqual(list(iter_output(ShortReader(frame(1,b'OUT\n')+frame(2,b'ERR\n')))),[(1,b'OUT\n'),(2,b'ERR\n')])
def test_empty(self): self.assertEqual(list(iter_output(io.BytesIO())),[])
def test_zero_frame(self): self.assertEqual(list(iter_output(io.BytesIO(frame(1,b'')))),[(1,b'')])
def test_stdin_kind(self): self.assertEqual(list(iter_output(io.BytesIO(frame(0,b'x')))),[(0,b'x')])
def test_system_error(self):
with self.assertRaisesRegex(DaemonStreamError,'failure'): list(iter_output(io.BytesIO(frame(3,b'failure'))))
misc/agent-context/.claude/skills/docker-engine-api/references/images/pull-push-and-registry-auth.md view on Meta::CPAN
> Read when: pulling or pushing images through the Engine API.
The Engine's registry-auth header is not the Registry HTTP API's bearer-token exchange. A client supplies registry credentials to the daemon, and the daemon contacts the registry. The daemon still needs network reachability and TLS trust independentl...
Encode the JSON auth object using **padded URL-safe base64**, matching Moby's encoder. An explicit empty object encodes as `e30=`. Keep padding; do not substitute standard base64 or an unpadded variant merely because a particular value appears to wor...
```python
import base64, json
header = base64.urlsafe_b64encode(
json.dumps({"username": "user", "password": "secret", "serveraddress": "registry.example.com"},
separators=(",", ":")).encode("utf-8")
).decode("ascii")
```
Do not put real credentials in source or logs. The example explains encoding only. Prefer credential-helper integration and short-lived scoped credentials. Treat `identitytoken` and `registrytoken` according to the selected endpoint/auth flow rather ...
## Correct the anonymous-push assumption
The pinned Moby decoder accepts an empty/missing auth value as an empty configuration. Consequently, âevery anonymous push always requires this headerâ is not a universal daemon rule. Supply the documented format when credentials are needed or wh...
t/fixtures/secrets_list.json view on Meta::CPAN
[
{
"ID": "28497238e77f873904ff31cb2",
"CreatedAt": "2026-08-27T05:01:40.791536705Z",
"UpdatedAt": "2026-08-27T05:01:40.791536705Z",
"Spec": {
"Name": "db-password",
"Driver": {
"Name": "file",
"Options": {
"path": "/home/getty/.local/share/containers/storage/secrets/filedriver"
}
},
"Labels": {
"env": "prod"
}
},
t/images_push_auth.t view on Meta::CPAN
# deduced: with the '=' stripped, a push against a local registry answers
# 400 'failed to parse "X-Registry-Auth" header ... unexpected EOF', and the
# anonymous case is the shortest and most certain to need a pad -- '{}'
# encodes to three characters plus one '='.
subtest 'the header carries its base64 padding' => sub {
my $hdr = $images->_registry_auth_header(undef);
is $hdr, 'e30=', 'anonymous auth is exactly the padded encoding of {}';
is length($hdr) % 4, 0, 'length is a multiple of four';
my $creds = $images->_registry_auth_header(
{ username => 'me', password => 'secret' });
is length($creds) % 4, 0, 'credentials are padded too';
};
subtest 'empty/undef auth -> base64url("{}")' => sub {
my $hdr = $images->_registry_auth_header(undef);
ok length($hdr), 'header is non-empty for undef';
is_deeply(decode_json(b64url_decode($hdr)), {},
'decodes to empty JSON object');
};
subtest 'hashref auth -> JSON-encoded credentials' => sub {
my $auth = {
username => 'me',
password => 'secret',
serveraddress => 'https://index.docker.io/v1/',
};
my $hdr = $images->_registry_auth_header($auth);
is_deeply(decode_json(b64url_decode($hdr)), $auth,
'header roundtrips through base64url + JSON');
};
subtest 'identitytoken auth' => sub {
my $auth = { identitytoken => 'tok-123', serveraddress => 'ghcr.io' };
my $hdr = $images->_registry_auth_header($auth);
t/images_push_auth.t view on Meta::CPAN
my ($self, $method, $path, %opts) = @_;
$captured = { method => $method, path => $path, %opts };
return [];
};
no warnings 'redefine';
local *API::Docker::_request = $mock;
$docker->images->push(
'raudssus/karr:user',
auth => { username => 'u', password => 'p' },
tag => 'user',
);
is $captured->{method}, 'POST', 'POST issued';
like $captured->{path}, qr{^/images/raudssus/karr:user/push}, 'push path';
ok exists $captured->{headers}{'X-Registry-Auth'},
'X-Registry-Auth header present';
is_deeply(
decode_json(b64url_decode($captured->{headers}{'X-Registry-Auth'})),
{ username => 'u', password => 'p' },
'header decodes to passed credentials',
);
is $captured->{params}{tag}, 'user', 'tag param present';
};
done_testing;
t/images_registry_auth.t view on Meta::CPAN
# No padding is added back, and the standard alphabet is deliberately NOT mapped
# to URL-safe here -- decode exactly what the engine would receive, so an
# unconverted '+'/'/' on the wire is a decode failure the test can see.
sub b64url_decode {
my ($s) = @_;
$s =~ tr{-_}{+/};
return decode_base64($s);
}
my $CREDS = { username => 'me', password => 'secret', serveraddress => 'ghcr.io' };
# ---------------------------------------------------------------------------
# The :63 fix, at the encoder. A pre-encoded standard-base64 string (with '+'
# and '/') used to pass through untouched; it must now be respelled URL-safe.
# This subtest goes red the moment the tr{+/}{-_} is dropped and the old
# `return $auth if ... base64-like` is restored.
subtest 'a pre-encoded standard-base64 auth is respelled URL-safe' => sub {
my $images = API::Docker->new(
host => 'unix:///dev/null',
api_version => '1.47',
t/images_registry_auth.t view on Meta::CPAN
my $captured;
my $docker = test_docker(
'POST /build' => sub {
my ($method, $path, %opts) = @_;
$captured = \%opts;
return [ { stream => 'Successfully built deadbeef\n' } ];
},
);
my $map = {
'registry.example:5000' => { username => 'me', password => 'secret' },
'ghcr.io' => { identitytoken => 'tok-123' },
};
$docker->images->build(
context => 'fake-tar-data',
t => 'myapp:latest',
registry_config => $map,
);
my $hdr = $captured->{headers}{'X-Registry-Config'};
ok defined $hdr, 'X-Registry-Config present when registry_config given';
t/plugins.t view on Meta::CPAN
# Unguarded, that undef would be POSTed to /plugins/pull as a JSON null
# where the engine expects an array.
is_deeply $c->plugins->privileges('vieux/sshfs'), [],
'privileges normalises it to the empty list it means';
};
subtest 'privileges: auth is sent as padded base64url X-Registry-Auth' => sub {
my $c = fake_client('[]');
$c->plugins->privileges('private.example.com/p/sshfs',
auth => { username => 'me', password => 'secret' });
my ($hdr) = $c->written =~ /^X-Registry-Auth: (\S+)\r$/m;
ok defined $hdr, 'header present when auth was given';
is length($hdr) % 4, 0, 'padded, as Go base64.URLEncoding requires';
is_deeply decode_json(b64url_decode($hdr)),
{ username => 'me', password => 'secret' },
'header decodes to the credentials passed';
};
# ---------------------------------------------------------------------------
subtest 'install: the privilege list is the request body' => sub {
my $c = fake_client(qq({"status":"Pulling plugin"}\n));
my $events = $c->plugins->install('vieux/sshfs:latest',
privileges => $PRIVILEGES);
like request_line($c->written), qr{\APOST /v1\.41/plugins/pull\?},
t/plugins.t view on Meta::CPAN
);
eval { $docker->plugins->upgrade('vieux/sshfs:latest') };
like $@, qr/upgrade requires privileges/, 'refused, naming the method';
};
# ---------------------------------------------------------------------------
subtest 'push: request assembly only' => sub {
# This never reaches a registry -- the socket is an in-memory sink. There
# is no live variant of this subtest and there must not be one.
my $c = fake_client(qq({"status":"Pushing"}\n));
$c->plugins->push('myrepo/sshfs:v1', auth => { username => 'u', password => 'p' });
is request_line($c->written),
'POST /v1.41/plugins/myrepo/sshfs:v1/push HTTP/1.1',
'POST /plugins/{name}/push, no query string';
my ($hdr) = $c->written =~ /^X-Registry-Auth: (\S+)\r$/m;
is_deeply decode_json(b64url_decode($hdr)), { username => 'u', password => 'p' },
'credentials in X-Registry-Auth, which the reference does not document '
. 'on this endpoint but the daemon reads';
};
subtest 'push: anonymous sends no auth header' => sub {
my $c = fake_client(qq({"status":"Pushing"}\n));
$c->plugins->push('myrepo/sshfs:v1');
unlike $c->written, qr/X-Registry-Auth/i,
'unlike images->push, which must always send one';
};
t/registry_auth.t view on Meta::CPAN
my ($hdr) = $raw =~ /^X-Registry-Auth: (\S+)\r$/m;
return $hdr;
}
sub b64url_decode {
my ($s) = @_;
$s =~ tr{-_}{+/};
return decode_base64($s);
}
my $CREDS = { username => 'me', password => 'secret', serveraddress => 'ghcr.io' };
# ---------------------------------------------------------------------------
subtest 'the encoder lives in one place and every registry class sees it' => sub {
my $docker = API::Docker->new(
host => 'unix:///dev/null',
api_version => '1.47',
);
my @consumers = (
[ images => $docker->images ],
t/registry_auth.t view on Meta::CPAN
is_deeply $system->_registry_auth_config(encode_json($CREDS)), $CREDS,
'a JSON object is decoded';
# The round trip that makes POST /auth able to take what push was given.
my $header = $system->_registry_auth_header($CREDS);
is_deeply $system->_registry_auth_config($header), $CREDS,
'a header value decodes back to the AuthConfig it was built from';
# base64url, not plain base64: a payload with a '/' or '+' in its base64
# would not survive the wrong alphabet.
my $slashy = { password => join('', map { chr } 0xfb, 0xff, 0xbf, 0xfe) };
my $slashy_header = $system->_registry_auth_header($slashy);
like $slashy_header, qr/[-_]/,
'this payload really does exercise the substituted characters';
is_deeply $system->_registry_auth_config($slashy_header), $slashy,
'the -_ alphabet round trips';
is $system->_registry_auth_config(undef), undef,
'undef stays undef -- whether that is an error is the endpoint\'s call';
ok !eval { $system->_registry_auth_config('not base64 at all !!'); 1 },
t/secrets_configs.t view on Meta::CPAN
}
is(ref $secrets, 'ARRAY', 'list returns an ArrayRef');
return if is_live();
is(scalar @$secrets, 2, 'two secrets in the fixture');
isa_ok($secrets->[0], 'API::Docker::Type::Secret', 'entries are wrapped and the first one');
isa_ok($secrets->[1], 'API::Docker::Type::Secret', 'so is the second');
is($secrets->[0]->id, '28497238e77f873904ff31cb2', 'id off the entity');
is($secrets->[0]->spec->name, 'db-password', 'first secret name');
is($secrets->[0]->version_index, 1, 'version_index reaches the Version.Index that update needs');
is($secrets->[0]->created_at, '2026-08-27T05:01:40.791536705Z', 'created_at is carried');
is($secrets->[0]->updated_at, '2026-08-27T05:01:40.791536705Z', 'updated_at is carried');
# The old entity kept Spec as the raw HashRef, so `!exists ...->{Data}` was
# the whole claim. SecretSpec declares `data` whether the daemon sent it or
# not, so the accessor now always exists and the claim moves to what it
# reads -- plus TO_JSON, which is the level where "the key was never there"
# is still observable.
is($secrets->[0]->spec->data, undef, 'a secret never comes back with its value');
t/secrets_configs.t view on Meta::CPAN
my ($method, $path, %opts) = @_;
($update_path, $update_params, $update_body) = ($path, $opts{params}, $opts{body});
return undef;
},
);
my $secret = $docker->secrets->list->[0];
my $fresh = $secret->inspect;
isa_ok($fresh, 'API::Docker::Type::Secret', 'inspect on the entity returns a fresh entity, and it');
is($fresh->spec->name, 'db-password', 'holding the same secret');
# The spec is an object now, so the "send the whole spec back" idiom goes
# through TO_JSON, which renders it in the daemon's own spelling.
my %spec = %{ $secret->spec->TO_JSON };
$spec{Labels} = { env => 'staging' };
$secret->update(%spec);
is($update_path, '/secrets/28497238e77f873904ff31cb2/update',
'update addresses the secret by id, not by Spec.Name');
is_deeply($update_params, { version => 1 },
t/secrets_configs.t view on Meta::CPAN
});
$docker->secrets->list;
is_deeply($params, {}, 'no filters key invented');
};
subtest 'secrets inspect' => sub {
plan skip_all => $REQUEST_SHAPE if is_live();
my $docker = test_docker(
'GET /secrets/db-password' => load_fixture('secrets_list')->[0],
);
my $secret = $docker->secrets->inspect('db-password');
isa_ok($secret, 'API::Docker::Type::Secret', 'inspect wraps the daemon response and it');
is($secret->spec->name, 'db-password', 'carrying the spec');
is($secret->version_index, 1, 'with the Version.Index');
};
# --- create: the base64 contract --------------------------------------------
subtest 'secrets create encodes Data for the caller' => sub {
plan skip_all => $REQUEST_SHAPE if is_live();
my $body;
my $docker = test_docker('POST /secrets/create' => sub {
my ($method, $path, %opts) = @_;
$body = $opts{body};
return { ID => 'abc123' };
});
my $created = $docker->secrets->create(
Name => 'db-password',
Data => "hunter2\n",
Labels => { env => 'prod' },
);
is($created->{ID}, 'abc123', 'returns the daemon response unwrapped');
is($body->{Name}, 'db-password', 'Name goes out untouched');
is_deeply($body->{Labels}, { env => 'prod' }, 'Labels go out untouched');
isnt($body->{Data}, "hunter2\n",
'the raw bytes are not what goes on the wire -- the daemon would store garbage and answer 200');
is($body->{Data}, 'aHVudGVyMgo=', 'Data is base64 of exactly what the caller passed');
is(decode_base64($body->{Data}), "hunter2\n", 'and decodes back to it');
};
subtest 'secrets create uses the alphabet the engine accepts' => sub {
plan skip_all => $REQUEST_SHAPE if is_live();
t/secrets_configs.t view on Meta::CPAN
is($requests, 0, 'none of them reached the daemon');
};
# --- update: the version query parameter ------------------------------------
subtest 'secrets update sends Version.Index as the version parameter' => sub {
plan skip_all => $REQUEST_SHAPE if is_live();
my ($path, $params, $body);
my $docker = test_docker(
'GET /secrets/db-password' => load_fixture('secrets_list')->[0],
'POST /secrets/db-password/update' => sub {
my ($method, $req_path, %opts) = @_;
($path, $params, $body) = ($req_path, $opts{params}, $opts{body});
return undef;
},
);
my $secret = $docker->secrets->inspect('db-password');
is($secret->version_index, 1, 'the version the caller is meant to pass comes from inspect');
my %spec = %{ $secret->spec->TO_JSON };
$spec{Labels} = { env => 'staging' };
my $result = $docker->secrets->update('db-password', $secret->version_index, %spec);
is($path, '/secrets/db-password/update', 'update posts to the right path');
is_deeply($params, { version => 1 },
'Version.Index rides in the version query parameter, and it is the only parameter');
is_deeply($body->{Labels}, { env => 'staging' }, 'the spec is the request body');
is($body->{Name}, 'db-password', 'the rest of the spec goes back unchanged');
ok(!exists $body->{version}, 'version is not also smuggled into the body');
is($result, undef, 'update returns nothing -- the daemon answers with an empty body');
};
subtest 'secrets update will not go out without a usable version' => sub {
plan skip_all => $REQUEST_SHAPE if is_live();
my $requests = 0;
my $docker = test_docker(
'POST /secrets/db-password/update' => sub { $requests++; return undef },
);
eval { $docker->secrets->update('db-password', undef, Labels => {}) };
my $missing = $@;
like($missing, qr/version/, 'a missing version croaks about the version');
like($missing, qr/Version\.Index/, 'and names the field it comes from');
like($missing, qr/inspect/, 'and the call that produces it');
eval { $docker->secrets->update('db-password', 'latest', Labels => {}) };
like($@, qr/must be the numeric Version\.Index/, 'a non-numeric version croaks');
eval { $docker->secrets->update(undef, 1, Labels => {}) };
like($@, qr/ID or name required/, 'a missing id croaks');
is($requests, 0,
'the guard is client-side: no request was made for any of them');
};
subtest 'secrets update encodes a Data it is given' => sub {
t/secrets_configs.t view on Meta::CPAN
is($body->{Data}, 'aHVudGVyMgo=', 'Data is encoded on update just as on create');
$docker->secrets->update('s', 7, Name => 's', Labels => { a => 'b' });
ok(!exists $body->{Data}, 'and no Data key is invented when none was passed');
};
subtest 'secrets remove' => sub {
plan skip_all => $REQUEST_SHAPE if is_live();
my $method_seen;
my $docker = test_docker('DELETE /secrets/db-password' => sub {
my ($method) = @_;
$method_seen = $method;
return undef;
});
my $result = $docker->secrets->remove('db-password');
is($method_seen, 'DELETE', 'remove uses DELETE');
is($result, undef, 'and returns nothing -- the daemon answers 204');
eval { $docker->secrets->remove('') };
like($@, qr/ID or name required/, 'an empty id croaks');
};
# --- configs: the same five endpoints, one different return -----------------
#
# Podman has no /configs route: GET /configs (the collection) answers the
t/system_auth.t view on Meta::CPAN
# socket so _request assembles a real request line, headers and body with
# nothing on the other end, and the assertions read what would have gone on
# the wire. That is the whole of what this method decides -- the outcome is
# the registry's to give.
#
# The canned success body is the Engine API reference's own example payload,
# and the canned failure bodies are captures from the rootless Podman socket
# (5.4.2, API 1.41), taken with an unreachable serveraddress so that no
# registry was ever asked about anyone's credentials:
#
# POST /v1.41/auth {"username":"nobody","password":"nothing",
# "serveraddress":"127.0.0.1:1"}
# -> 500 {"message":"login attempt to 127.0.0.1:1 failed with status:
# authenticating creds for \"127.0.0.1:1\": pinging container
# registry 127.0.0.1:1: Get \"https://127.0.0.1:1/v2/\": dial tcp
# 127.0.0.1:1: connect: connection refused"}
#
# Note the 500: Podman does not answer a failed check with Docker's 401. The
# croak is what both engines have in common, which is why this file asserts
# the croak and not the number.
t/system_auth.t view on Meta::CPAN
}
sub request_body {
my ($raw) = @_;
my ($body) = $raw =~ /\r\n\r\n(.*)\z/s;
return $body;
}
my $CREDS = {
username => 'me',
password => 'secret',
serveraddress => 'ghcr.io',
};
# ---------------------------------------------------------------------------
subtest 'the credentials go in the body, not in a header' => sub {
my $c = fake_client();
my $out = $c->system->auth(%$CREDS);
is request_line($c->written), 'POST /v1.41/auth HTTP/1.1',
'POST /auth, no query string';
t/system_auth.t view on Meta::CPAN
ok !eval { $c->system->auth; 1 }, 'no arguments croaks';
like $@, qr/requires credentials/, 'and says what is missing';
is $c->written, '', 'nothing was sent';
my $e = fake_client();
ok !eval { $e->system->auth(auth => {}); 1 },
'an empty AuthConfig croaks too';
is $e->written, '', 'nothing was sent';
# Stricter than the engine on purpose: Podman answers the empty body with
# 500 'getting username and password: cannot prompt for username without
# stdin', which describes the daemon's stdin rather than the caller's bug.
};
# ---------------------------------------------------------------------------
subtest 'only identitytoken is enough' => sub {
my $c = fake_client();
$c->system->auth(identitytoken => 'tok-123', serveraddress => 'ghcr.io');
is_deeply decode_json(request_body($c->written)),
{ identitytoken => 'tok-123', serveraddress => 'ghcr.io' },
'a token-only AuthConfig is a complete one';
t/timeout_forwarding.t view on Meta::CPAN
'system' => sub { $_[0]->info } ],
[ 'system->version', 'GET /version',
'system' => sub { $_[0]->version } ],
[ 'system->ping', 'GET /_ping',
'system' => sub { $_[0]->ping } ],
[ 'system->events', 'GET /events',
'system' => sub { $_[0]->events } ],
[ 'system->df', 'GET /system/df',
'system' => sub { $_[0]->df } ],
[ 'system->auth', 'POST /auth',
'system' => sub { $_[0]->auth(username => 'u', password => 'p') } ],
# -- plugins -------------------------------------------------------------
[ 'plugins->list', 'GET /plugins',
'plugins' => sub { $_[0]->list } ],
[ 'plugins->privileges', 'GET /plugins/privileges',
'plugins' => sub { $_[0]->privileges('p') } ],
[ 'plugins->install', 'POST /plugins/pull',
'plugins' => sub { $_[0]->install('p', privileges => []) } ],
[ 'plugins->install privileges pre-flight', 'GET /plugins/privileges',
'plugins' => sub { $_[0]->install('p', accept_privileges => 1) } ],