ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/lib/AnyEvent/MCP/Config.pm
Revision: 1.7
Committed: Sun Oct 11 01:17:26 2026 UTC (4 weeks, 3 days ago) by root
Branch: MAIN
Changes since 1.6: +5 -1 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 root 1.7 The C<cookie> purpose is a historical HKDF label retained so existing
65     tokens do not change when the terminology does. It does not imply an HTTP
66     Cookie header. A derived C<bearer> token or a credential with C<$username>
67     is B<not> automatically accepted by the server. This method does not
68     require a corresponding server section or configure authentication.
69 root 1.1
70 root 1.4 =head2 $name = AnyEvent::MCP::Config::server_name ($name)
71    
72     Validate a service-instance name, or use the program basename if undefined.
73     Names consist of an ASCII letter or underscore followed by letters, digits,
74     underscores or hyphens.
75    
76 root 1.5 =head2 @options = AnyEvent::MCP::Config::http_getopt (\$name, \$bind, \$print_url, \@tokens)
77 root 1.4
78     Return standard C<Getopt::Long> options referring to the caller's scalars.
79    
80     =head2 $port = $config->server_port ($name)
81    
82     Derive a stable default port in 16384..32767 from the master secret and
83     service-instance name. Collisions produce ordinary listener bind errors.
84    
85     =head2 %settings = $config->http_settings ($name, $bind)
86    
87     Resolve HTTP settings from C<[server NAME]> and an optional command-line
88     C<bind> override. The default is IPv4 loopback and the name-derived port.
89     The bind setting accepts C<ADDRESS:PORT>, C<[IPv6]:PORT>, C<ADDRESS>,
90     and C<:PORT> (which keeps the default loopback address).
91     Hostnames are resolved once to a numeric address at startup; their original
92     spelling is advertised unless C<url_host> overrides it.
93    
94     =head2 $url = $config->http_url ($name, $bind, %options)
95    
96 root 1.5 Format a URL containing the first accepted token, without listening. Port zero cannot be used
97 root 1.4 because the kernel has not yet selected a port.
98    
99 root 1.1 =cut
100    
101     package AnyEvent::MCP::Config;
102    
103     use common::sense;
104     use AnyEvent::MCP ();
105     use MIME::Base64 ();
106     use File::Basename ();
107     use File::Path ();
108     use Fcntl qw(O_WRONLY O_RDWR O_CREAT O_EXCL LOCK_EX);
109     use Errno qw(ENOENT);
110 root 1.4 use AnyEvent::Socket ();
111     use Socket ();
112 root 1.1
113     our @ISA = qw(AnyEvent::MCP::Base);
114    
115     sub _file {
116     my $dir = $ENV{XDG_CONFIG_HOME}
117     || ($ENV{HOME} || die "HOME is not set\n") . "/.config";
118    
119     "$dir/anyevent-mcp/global.ini"
120     }
121    
122     my $global;
123    
124     sub global {
125     my $class = shift;
126    
127     $global ||= $class->new (@_)
128     }
129    
130     sub new {
131     my ($class, %kv) = @_;
132     my $self = $class->SUPER::new (section => {}, %kv);
133     $self->{file} = _file unless exists $self->{file};
134    
135     if (open my $fh, "<:encoding(UTF-8)", $self->{file}) {
136     $self->_read ($fh);
137     close $fh or die "$self->{file}: $!\n";
138     } else {
139     die "$self->{file}: $!\n" unless $! == ENOENT;
140     }
141    
142     $self->_ensure_secret;
143    
144     die "$self->{file}: invalid secret; supply 128 hexadecimal digits\n"
145     unless $self->{section}{global}{secret} =~ /\A[0-9a-fA-F]{128}\z/;
146    
147     $self
148     }
149    
150     sub _read {
151     my ($self, $fh) = @_;
152    
153     my @stat = stat $fh;
154     die "$self->{file}: configuration must be private and owned by this user\n"
155     if $stat[4] != $< || $stat[2] & 077;
156    
157     my $section = $self->{section}{global} ||= {};
158    
159     while (<$fh>) {
160     next if /\A\s*(?:[#;]|\z)/;
161    
162     if (/\A\s*\[([^\]\r\n]+)\]\s*\z/) {
163     $section = $self->{section}{$1} ||= {};
164     } elsif (/\A\s*([^=\s]+)\s*=\s*(.*?)\s*\z/) {
165     $section->{$1} = $2;
166     } else {
167     die "$self->{file}:$.: invalid configuration line\n";
168     }
169     }
170    
171     }
172    
173     sub _ensure_secret {
174     my ($self) = @_;
175    
176     return if exists $self->{section}{global}{secret};
177    
178     my $secret = eval { unpack "H*", AnyEvent::MCP::random_bytes 64 };
179     die "$@Supply a securely generated 128-digit hexadecimal secret in $self->{file}\n"
180     if $@;
181    
182     eval {
183     File::Path::mkpath (File::Basename::dirname ($self->{file}), 0, 0700);
184     sysopen my $fh, $self->{file}, O_RDWR | O_CREAT, 0600
185     or die "$self->{file}: $!\n";
186     flock $fh, LOCK_EX or die "$self->{file}: $!\n";
187     binmode $fh, ":encoding(UTF-8)";
188    
189     my $disk = bless { file => $self->{file}, section => {} }, ref $self;
190     $disk->_read ($fh);
191    
192     unless (exists $disk->{section}{global}{secret}) {
193     seek $fh, 0, 2 or die "$self->{file}: $!\n";
194     print {$fh} "\n[global]\nsecret = $secret\n"
195     or die "$self->{file}: $!\n";
196     $disk->{section}{global}{secret} = $secret;
197     }
198    
199     close $fh or die "$self->{file}: $!\n";
200     $self->{section} = $disk->{section};
201     1
202     } or warn "Cannot save MCP master secret; credentials may only be stable for this process: $@";
203    
204     $self->{section}{global}{secret} = $secret
205     unless exists $self->{section}{global}{secret};
206     }
207    
208     sub init {
209     my ($class, %kv) = @_;
210     my $file = exists $kv{file} ? $kv{file} : _file;
211    
212     my $secret = AnyEvent::MCP::random_bytes 64;
213    
214     File::Path::mkpath (File::Basename::dirname ($file), 0, 0700);
215    
216     sysopen my $fh, $file, O_WRONLY | O_CREAT | O_EXCL, 0600
217     or die "$file: $!\n";
218    
219     print {$fh} "[global]\nsecret = ", unpack ("H*", $secret), "\n"
220     or die "$file: $!\n";
221     close $fh or die "$file: $!\n";
222    
223     $class->new (file => $file)
224     }
225    
226     sub credential {
227     my ($self, $purpose, $name, $username) = @_;
228    
229     $username = "" unless defined $username;
230    
231     die "Unknown credential purpose '$purpose'\n"
232 root 1.5 unless $purpose =~ /\A(?:bearer|cookie)\z/;
233 root 1.1
234     my $secret = $self->{section}{global}{secret};
235     die "$self->{file}: missing or invalid secret\n"
236     unless $secret =~ /\A[0-9a-fA-F]{128}\z/;
237    
238     my $info = pack "N/a*N/a*N/a*N/a*",
239     "AnyEvent::MCP credential v1", $purpose,
240 root 1.2 AnyEvent::MCP::utf8enc ($name), AnyEvent::MCP::utf8enc ($username);
241 root 1.1
242     my $credential = MIME::Base64::encode_base64 (
243     AnyEvent::MCP::hkdf_sha512_expand (pack ("H*", $secret), $info, 32), ""
244     );
245     $credential =~ y!+/=!-_!d;
246    
247     $credential
248     }
249    
250 root 1.4 sub server_name {
251     my ($name) = @_;
252    
253     unless (defined $name) {
254     require File::Basename;
255     $name = File::Basename::basename ($0);
256     $name =~ s/\.(?:pl|perl)\z//;
257     $name = "perl" if $name eq "-e";
258     }
259    
260     $name =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/
261     or die "Invalid MCP server name '$name'\n";
262    
263     $name
264     }
265    
266     sub http_getopt {
267 root 1.5 my ($name, $bind, $print_url, $tokens) = @_;
268 root 1.4
269 root 1.5 "name=s" => $name, "bind=s" => $bind, "print-url" => $print_url, "token=s@" => $tokens
270 root 1.4 }
271    
272     sub server_port {
273     my ($self, $name) = @_;
274    
275     $name = server_name $name;
276    
277     my $info = pack "N/a*N/a*", "AnyEvent::MCP port v1", $name;
278     16384 + ((unpack "n", AnyEvent::MCP::hkdf_sha512_expand (
279     pack ("H*", $self->{section}{global}{secret}), $info, 2
280     )) & 16383)
281     }
282    
283     sub http_settings {
284     my ($self, $name, $bind) = @_;
285    
286     $name = server_name $name;
287     my $settings = $self->{section}{"server $name"} || {};
288     my $port = $self->server_port ($name);
289     my $configured = $settings->{bind} // "127.0.0.1:$port";
290     $configured = "127.0.0.1$configured" if $configured =~ /\A:[0-9]+\z/;
291     my ($configured_host, $configured_port) = AnyEvent::Socket::parse_hostport $configured, $port;
292     defined $configured_host && defined $configured_port
293     && $configured_port =~ /\A[0-9]+\z/ && $configured_port <= 65535
294     or die "Invalid MCP bind address '$configured'\n";
295    
296     $bind = $configured unless defined $bind;
297     $bind = "127.0.0.1$bind" if $bind =~ /\A:[0-9]+\z/;
298    
299     my ($host, $service) = AnyEvent::Socket::parse_hostport $bind, $configured_port;
300     defined $host && defined $service && $service =~ /\A[0-9]+\z/ && $service <= 65535
301     or die "Invalid MCP bind address '$bind'\n";
302    
303     my %kv = (
304     (map { exists $settings->{$_} ? ($_ => $settings->{$_}) : () }
305 root 1.5 qw(path url_host url_scheme)),
306 root 1.4 name => $name,
307     host => $host,
308     port => $service,
309     );
310    
311     unless (AnyEvent::Socket::parse_address $host) {
312     my ($error, @addresses) = Socket::getaddrinfo ($host, undef, { socktype => Socket::SOCK_STREAM () });
313     !$error && @addresses
314     or die "Cannot resolve MCP bind host '$host': $error\n";
315    
316     my ($error2, $address) = Socket::getnameinfo ($addresses[0]{addr}, Socket::NI_NUMERICHOST ());
317     !$error2 && length $address
318     or die "Cannot format MCP bind host '$host': $error2\n";
319    
320     $kv{url_host} //= $host;
321     $kv{host} = $address;
322     }
323    
324 root 1.5 if (exists $settings->{tokens}) {
325     $kv{tokens} = [split /\s*,\s*/, $settings->{tokens}, -1];
326     } else {
327 root 1.4 my $token = $self->credential ("cookie", $name);
328 root 1.5 $kv{tokens} = [$token];
329 root 1.4 }
330    
331     %kv
332     }
333    
334     sub http_url {
335     my ($self, $name, $bind, %options) = @_;
336    
337     # A printed URL needs a credential that survives the next process.
338     my $stored = ref ($self)->new (file => $self->{file});
339     $stored->{section}{global}{secret} eq $self->{section}{global}{secret}
340     or die "MCP master secret is not persistently stored in $self->{file}\n";
341    
342     require AnyEvent::MCP::Server::HTTP;
343     my $server = AnyEvent::MCP::Server::HTTP->new ($self->http_settings ($name, $bind), %options);
344     $server->url
345     }
346    
347 root 1.1
348     1