ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/lib/AnyEvent/MCP/Config.pm
Revision: 1.6
Committed: Sun Oct 11 01:02:38 2026 UTC (2 weeks, 5 days ago) by root
Branch: MAIN
Changes since 1.5: +1 -25 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3     AnyEvent::MCP::Config - named servers and derived MCP credentials
4    
5     =head1 SYNOPSIS
6    
7     my $config = AnyEvent::MCP::Config->global;
8 root 1.5 my $token = $config->credential ("cookie", "agni");
9 root 1.6 my $url = $config->http_url ("agni", undef, path => "/");
10 root 1.1
11     =head1 DESCRIPTION
12    
13 root 1.3 An MCP server and its clients often need matching credentials. Rather than
14     maintaining a separate password for each server and user, this module can
15     derive them from one private master secret. A server name, optional username
16     and credential purpose each contribute to the result. A password derived for
17     one server is therefore not the password for another.
18    
19     The shared file format is described in L<AnyEvent::MCP/GLOBAL CONFIGURATION>.
20     Loading this module does not read any files. The first call to C<global>
21     reads the configuration, ensures a master secret exists and caches the object
22     for the process.
23 root 1.1
24     A missing secret is generated using C<AnyEvent::MCP::random_bytes> and saved
25     when possible. Saving failure produces a warning; the generated secret remains
26 root 1.3 usable in this process, but another process might derive different credentials.
27     A supplied invalid secret is an error. Changing or losing the master secret
28     invalidates all credentials derived from it.
29 root 1.1
30     Derivation uses HKDF-SHA512 expansion with the random master key as its PRK.
31     Server name, username and credential purpose are separately length-prefixed,
32     so credentials for different servers, users or authentication methods differ.
33 root 1.3 Deriving a password does not create an account or configure the server to
34     accept it: authentication still belongs to the server.
35 root 1.1
36     =head1 METHODS
37    
38     =head2 $config = AnyEvent::MCP::Config->global (file => $file)
39    
40     Returns the cached global configuration. The first call accepts the same
41     arguments as C<new>; later calls return the same object without rereading
42     the file. Call this explicitly during program startup.
43    
44     =head2 $config = AnyEvent::MCP::Config->new (file => $file)
45    
46     Reads C<$file>, or the default file when omitted, and ensures a master
47     secret exists. Unlike C<global>, each call creates an independent object.
48     A missing file is allowed; other read errors are fatal. Sections are available
49     as C<< $config->{section}{$section} >>, each a hash reference of string
50     values. Named servers use C<[server NAME]>.
51    
52     =head2 $config = AnyEvent::MCP::Config->init (file => $file)
53    
54     Explicitly creates the configuration file with a random secret, mode 0600.
55     Creates missing parent directories with mode 0700. Fails if the file already
56     exists, so it cannot accidentally replace an existing secret.
57    
58     =head2 $credential = $config->credential ($purpose, $name, $username)
59    
60     Derives a 32-byte credential, returned as unpadded URL-safe Base64.
61 root 1.5 C<$purpose> is C<cookie> (the default server token) or C<bearer> (a separate
62     derivation domain). C<$name> is the server name. C<$username> is optional.
63 root 1.1
64     This method does not require a corresponding server section.
65    
66 root 1.4 =head2 $name = AnyEvent::MCP::Config::server_name ($name)
67    
68     Validate a service-instance name, or use the program basename if undefined.
69     Names consist of an ASCII letter or underscore followed by letters, digits,
70     underscores or hyphens.
71    
72 root 1.5 =head2 @options = AnyEvent::MCP::Config::http_getopt (\$name, \$bind, \$print_url, \@tokens)
73 root 1.4
74     Return standard C<Getopt::Long> options referring to the caller's scalars.
75    
76     =head2 $port = $config->server_port ($name)
77    
78     Derive a stable default port in 16384..32767 from the master secret and
79     service-instance name. Collisions produce ordinary listener bind errors.
80    
81     =head2 %settings = $config->http_settings ($name, $bind)
82    
83     Resolve HTTP settings from C<[server NAME]> and an optional command-line
84     C<bind> override. The default is IPv4 loopback and the name-derived port.
85     The bind setting accepts C<ADDRESS:PORT>, C<[IPv6]:PORT>, C<ADDRESS>,
86     and C<:PORT> (which keeps the default loopback address).
87     Hostnames are resolved once to a numeric address at startup; their original
88     spelling is advertised unless C<url_host> overrides it.
89    
90     =head2 $url = $config->http_url ($name, $bind, %options)
91    
92 root 1.5 Format a URL containing the first accepted token, without listening. Port zero cannot be used
93 root 1.4 because the kernel has not yet selected a port.
94    
95 root 1.1 =cut
96    
97     package AnyEvent::MCP::Config;
98    
99     use common::sense;
100     use AnyEvent::MCP ();
101     use MIME::Base64 ();
102     use File::Basename ();
103     use File::Path ();
104     use Fcntl qw(O_WRONLY O_RDWR O_CREAT O_EXCL LOCK_EX);
105     use Errno qw(ENOENT);
106 root 1.4 use AnyEvent::Socket ();
107     use Socket ();
108 root 1.1
109     our @ISA = qw(AnyEvent::MCP::Base);
110    
111     sub _file {
112     my $dir = $ENV{XDG_CONFIG_HOME}
113     || ($ENV{HOME} || die "HOME is not set\n") . "/.config";
114    
115     "$dir/anyevent-mcp/global.ini"
116     }
117    
118     my $global;
119    
120     sub global {
121     my $class = shift;
122    
123     $global ||= $class->new (@_)
124     }
125    
126     sub new {
127     my ($class, %kv) = @_;
128     my $self = $class->SUPER::new (section => {}, %kv);
129     $self->{file} = _file unless exists $self->{file};
130    
131     if (open my $fh, "<:encoding(UTF-8)", $self->{file}) {
132     $self->_read ($fh);
133     close $fh or die "$self->{file}: $!\n";
134     } else {
135     die "$self->{file}: $!\n" unless $! == ENOENT;
136     }
137    
138     $self->_ensure_secret;
139    
140     die "$self->{file}: invalid secret; supply 128 hexadecimal digits\n"
141     unless $self->{section}{global}{secret} =~ /\A[0-9a-fA-F]{128}\z/;
142    
143     $self
144     }
145    
146     sub _read {
147     my ($self, $fh) = @_;
148    
149     my @stat = stat $fh;
150     die "$self->{file}: configuration must be private and owned by this user\n"
151     if $stat[4] != $< || $stat[2] & 077;
152    
153     my $section = $self->{section}{global} ||= {};
154    
155     while (<$fh>) {
156     next if /\A\s*(?:[#;]|\z)/;
157    
158     if (/\A\s*\[([^\]\r\n]+)\]\s*\z/) {
159     $section = $self->{section}{$1} ||= {};
160     } elsif (/\A\s*([^=\s]+)\s*=\s*(.*?)\s*\z/) {
161     $section->{$1} = $2;
162     } else {
163     die "$self->{file}:$.: invalid configuration line\n";
164     }
165     }
166    
167     }
168    
169     sub _ensure_secret {
170     my ($self) = @_;
171    
172     return if exists $self->{section}{global}{secret};
173    
174     my $secret = eval { unpack "H*", AnyEvent::MCP::random_bytes 64 };
175     die "$@Supply a securely generated 128-digit hexadecimal secret in $self->{file}\n"
176     if $@;
177    
178     eval {
179     File::Path::mkpath (File::Basename::dirname ($self->{file}), 0, 0700);
180     sysopen my $fh, $self->{file}, O_RDWR | O_CREAT, 0600
181     or die "$self->{file}: $!\n";
182     flock $fh, LOCK_EX or die "$self->{file}: $!\n";
183     binmode $fh, ":encoding(UTF-8)";
184    
185     my $disk = bless { file => $self->{file}, section => {} }, ref $self;
186     $disk->_read ($fh);
187    
188     unless (exists $disk->{section}{global}{secret}) {
189     seek $fh, 0, 2 or die "$self->{file}: $!\n";
190     print {$fh} "\n[global]\nsecret = $secret\n"
191     or die "$self->{file}: $!\n";
192     $disk->{section}{global}{secret} = $secret;
193     }
194    
195     close $fh or die "$self->{file}: $!\n";
196     $self->{section} = $disk->{section};
197     1
198     } or warn "Cannot save MCP master secret; credentials may only be stable for this process: $@";
199    
200     $self->{section}{global}{secret} = $secret
201     unless exists $self->{section}{global}{secret};
202     }
203    
204     sub init {
205     my ($class, %kv) = @_;
206     my $file = exists $kv{file} ? $kv{file} : _file;
207    
208     my $secret = AnyEvent::MCP::random_bytes 64;
209    
210     File::Path::mkpath (File::Basename::dirname ($file), 0, 0700);
211    
212     sysopen my $fh, $file, O_WRONLY | O_CREAT | O_EXCL, 0600
213     or die "$file: $!\n";
214    
215     print {$fh} "[global]\nsecret = ", unpack ("H*", $secret), "\n"
216     or die "$file: $!\n";
217     close $fh or die "$file: $!\n";
218    
219     $class->new (file => $file)
220     }
221    
222     sub credential {
223     my ($self, $purpose, $name, $username) = @_;
224    
225     $username = "" unless defined $username;
226    
227     die "Unknown credential purpose '$purpose'\n"
228 root 1.5 unless $purpose =~ /\A(?:bearer|cookie)\z/;
229 root 1.1
230     my $secret = $self->{section}{global}{secret};
231     die "$self->{file}: missing or invalid secret\n"
232     unless $secret =~ /\A[0-9a-fA-F]{128}\z/;
233    
234     my $info = pack "N/a*N/a*N/a*N/a*",
235     "AnyEvent::MCP credential v1", $purpose,
236 root 1.2 AnyEvent::MCP::utf8enc ($name), AnyEvent::MCP::utf8enc ($username);
237 root 1.1
238     my $credential = MIME::Base64::encode_base64 (
239     AnyEvent::MCP::hkdf_sha512_expand (pack ("H*", $secret), $info, 32), ""
240     );
241     $credential =~ y!+/=!-_!d;
242    
243     $credential
244     }
245    
246 root 1.4 sub server_name {
247     my ($name) = @_;
248    
249     unless (defined $name) {
250     require File::Basename;
251     $name = File::Basename::basename ($0);
252     $name =~ s/\.(?:pl|perl)\z//;
253     $name = "perl" if $name eq "-e";
254     }
255    
256     $name =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/
257     or die "Invalid MCP server name '$name'\n";
258    
259     $name
260     }
261    
262     sub http_getopt {
263 root 1.5 my ($name, $bind, $print_url, $tokens) = @_;
264 root 1.4
265 root 1.5 "name=s" => $name, "bind=s" => $bind, "print-url" => $print_url, "token=s@" => $tokens
266 root 1.4 }
267    
268     sub server_port {
269     my ($self, $name) = @_;
270    
271     $name = server_name $name;
272    
273     my $info = pack "N/a*N/a*", "AnyEvent::MCP port v1", $name;
274     16384 + ((unpack "n", AnyEvent::MCP::hkdf_sha512_expand (
275     pack ("H*", $self->{section}{global}{secret}), $info, 2
276     )) & 16383)
277     }
278    
279     sub http_settings {
280     my ($self, $name, $bind) = @_;
281    
282     $name = server_name $name;
283     my $settings = $self->{section}{"server $name"} || {};
284     my $port = $self->server_port ($name);
285     my $configured = $settings->{bind} // "127.0.0.1:$port";
286     $configured = "127.0.0.1$configured" if $configured =~ /\A:[0-9]+\z/;
287     my ($configured_host, $configured_port) = AnyEvent::Socket::parse_hostport $configured, $port;
288     defined $configured_host && defined $configured_port
289     && $configured_port =~ /\A[0-9]+\z/ && $configured_port <= 65535
290     or die "Invalid MCP bind address '$configured'\n";
291    
292     $bind = $configured unless defined $bind;
293     $bind = "127.0.0.1$bind" if $bind =~ /\A:[0-9]+\z/;
294    
295     my ($host, $service) = AnyEvent::Socket::parse_hostport $bind, $configured_port;
296     defined $host && defined $service && $service =~ /\A[0-9]+\z/ && $service <= 65535
297     or die "Invalid MCP bind address '$bind'\n";
298    
299     my %kv = (
300     (map { exists $settings->{$_} ? ($_ => $settings->{$_}) : () }
301 root 1.5 qw(path url_host url_scheme)),
302 root 1.4 name => $name,
303     host => $host,
304     port => $service,
305     );
306    
307     unless (AnyEvent::Socket::parse_address $host) {
308     my ($error, @addresses) = Socket::getaddrinfo ($host, undef, { socktype => Socket::SOCK_STREAM () });
309     !$error && @addresses
310     or die "Cannot resolve MCP bind host '$host': $error\n";
311    
312     my ($error2, $address) = Socket::getnameinfo ($addresses[0]{addr}, Socket::NI_NUMERICHOST ());
313     !$error2 && length $address
314     or die "Cannot format MCP bind host '$host': $error2\n";
315    
316     $kv{url_host} //= $host;
317     $kv{host} = $address;
318     }
319    
320 root 1.5 if (exists $settings->{tokens}) {
321     $kv{tokens} = [split /\s*,\s*/, $settings->{tokens}, -1];
322     } else {
323 root 1.4 my $token = $self->credential ("cookie", $name);
324 root 1.5 $kv{tokens} = [$token];
325 root 1.4 }
326    
327     %kv
328     }
329    
330     sub http_url {
331     my ($self, $name, $bind, %options) = @_;
332    
333     # A printed URL needs a credential that survives the next process.
334     my $stored = ref ($self)->new (file => $self->{file});
335     $stored->{section}{global}{secret} eq $self->{section}{global}{secret}
336     or die "MCP master secret is not persistently stored in $self->{file}\n";
337    
338     require AnyEvent::MCP::Server::HTTP;
339     my $server = AnyEvent::MCP::Server::HTTP->new ($self->http_settings ($name, $bind), %options);
340     $server->url
341     }
342    
343 root 1.1
344     1