ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/lib/AnyEvent/MCP/Config.pm
Revision: 1.11
Committed: Tue Oct 13 10:17:31 2026 UTC (4 weeks, 5 days ago) by root
Branch: MAIN
Changes since 1.10: +14 -16 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.8 my $token = $config->credential ("token", "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 root 1.10 values. Named servers use C<[instance NAME]>.
51 root 1.1
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.8 C<$purpose> is C<token>. C<$name> is the server name, and C<$username>
62     is optional. The default server credential is derived with no username.
63 root 1.1
64 root 1.8 The purpose is now C<token>, not the former C<cookie> HKDF label.
65     This intentionally changes derived credentials after installation; update
66     stored client URLs accordingly. A credential derived with C<$username> is
67     B<not> automatically accepted by the server. This method neither requires
68     a server section nor configures 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 root 1.10 Resolve HTTP settings from C<[instance NAME]> and an optional command-line
88 root 1.4 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.8 Format a URL containing the first accepted token, without listening.
97     Port zero cannot be used because the kernel has not yet selected a port.
98     When the token is derived, the master secret must be persistently stored,
99     so the next process derives the same URL. Explicit static tokens and
100     C<auth =E<gt> "none"> do not require that persistence check.
101 root 1.4
102 root 1.1 =cut
103    
104     package AnyEvent::MCP::Config;
105    
106     use common::sense;
107     use AnyEvent::MCP ();
108     use MIME::Base64 ();
109     use File::Basename ();
110     use File::Path ();
111     use Fcntl qw(O_WRONLY O_RDWR O_CREAT O_EXCL LOCK_EX);
112     use Errno qw(ENOENT);
113 root 1.4 use AnyEvent::Socket ();
114     use Socket ();
115 root 1.1
116     our @ISA = qw(AnyEvent::MCP::Base);
117    
118     sub _file {
119     my $dir = $ENV{XDG_CONFIG_HOME}
120     || ($ENV{HOME} || die "HOME is not set\n") . "/.config";
121    
122     "$dir/anyevent-mcp/global.ini"
123     }
124    
125     my $global;
126    
127     sub global {
128     my $class = shift;
129    
130     $global ||= $class->new (@_)
131     }
132    
133     sub new {
134     my ($class, %kv) = @_;
135 root 1.11
136 root 1.1 my $self = $class->SUPER::new (section => {}, %kv);
137     $self->{file} = _file unless exists $self->{file};
138    
139     if (open my $fh, "<:encoding(UTF-8)", $self->{file}) {
140     $self->_read ($fh);
141     close $fh or die "$self->{file}: $!\n";
142     } else {
143     die "$self->{file}: $!\n" unless $! == ENOENT;
144     }
145    
146     $self->_ensure_secret;
147    
148 root 1.11 $self->{section}{global}{secret} =~ /\A[0-9a-fA-F]{128}\z/
149     or die "$self->{file}: invalid secret; supply 128 hexadecimal digits\n";
150 root 1.1
151     $self
152     }
153    
154     sub _read {
155     my ($self, $fh) = @_;
156    
157     my @stat = stat $fh;
158     die "$self->{file}: configuration must be private and owned by this user\n"
159     if $stat[4] != $< || $stat[2] & 077;
160    
161     my $section = $self->{section}{global} ||= {};
162    
163     while (<$fh>) {
164     next if /\A\s*(?:[#;]|\z)/;
165    
166     if (/\A\s*\[([^\]\r\n]+)\]\s*\z/) {
167     $section = $self->{section}{$1} ||= {};
168     } elsif (/\A\s*([^=\s]+)\s*=\s*(.*?)\s*\z/) {
169     $section->{$1} = $2;
170     } else {
171     die "$self->{file}:$.: invalid configuration line\n";
172     }
173     }
174    
175     }
176    
177     sub _ensure_secret {
178     my ($self) = @_;
179    
180     return if exists $self->{section}{global}{secret};
181    
182     my $secret = eval { unpack "H*", AnyEvent::MCP::random_bytes 64 };
183     die "$@Supply a securely generated 128-digit hexadecimal secret in $self->{file}\n"
184     if $@;
185    
186     eval {
187     File::Path::mkpath (File::Basename::dirname ($self->{file}), 0, 0700);
188     sysopen my $fh, $self->{file}, O_RDWR | O_CREAT, 0600
189     or die "$self->{file}: $!\n";
190     flock $fh, LOCK_EX or die "$self->{file}: $!\n";
191     binmode $fh, ":encoding(UTF-8)";
192    
193     my $disk = bless { file => $self->{file}, section => {} }, ref $self;
194     $disk->_read ($fh);
195    
196     unless (exists $disk->{section}{global}{secret}) {
197     seek $fh, 0, 2 or die "$self->{file}: $!\n";
198     print {$fh} "\n[global]\nsecret = $secret\n"
199     or die "$self->{file}: $!\n";
200     $disk->{section}{global}{secret} = $secret;
201     }
202    
203     close $fh or die "$self->{file}: $!\n";
204     $self->{section} = $disk->{section};
205     1
206     } or warn "Cannot save MCP master secret; credentials may only be stable for this process: $@";
207    
208     $self->{section}{global}{secret} = $secret
209     unless exists $self->{section}{global}{secret};
210     }
211    
212     sub init {
213     my ($class, %kv) = @_;
214 root 1.11
215 root 1.1 my $file = exists $kv{file} ? $kv{file} : _file;
216    
217     my $secret = AnyEvent::MCP::random_bytes 64;
218    
219     File::Path::mkpath (File::Basename::dirname ($file), 0, 0700);
220    
221     sysopen my $fh, $file, O_WRONLY | O_CREAT | O_EXCL, 0600
222     or die "$file: $!\n";
223    
224     print {$fh} "[global]\nsecret = ", unpack ("H*", $secret), "\n"
225     or die "$file: $!\n";
226     close $fh or die "$file: $!\n";
227    
228     $class->new (file => $file)
229     }
230    
231     sub credential {
232     my ($self, $purpose, $name, $username) = @_;
233    
234     $username = "" unless defined $username;
235    
236 root 1.11 $purpose eq "token"
237     or die "Unknown credential purpose '$purpose'\n";
238 root 1.1
239     my $secret = $self->{section}{global}{secret};
240 root 1.11 $secret =~ /\A[0-9a-fA-F]{128}\z/
241     or die "$self->{file}: missing or invalid secret\n";
242 root 1.1
243     my $info = pack "N/a*N/a*N/a*N/a*",
244     "AnyEvent::MCP credential v1", $purpose,
245 root 1.2 AnyEvent::MCP::utf8enc ($name), AnyEvent::MCP::utf8enc ($username);
246 root 1.1
247     my $credential = MIME::Base64::encode_base64 (
248     AnyEvent::MCP::hkdf_sha512_expand (pack ("H*", $secret), $info, 32), ""
249     );
250     $credential =~ y!+/=!-_!d;
251    
252     $credential
253     }
254    
255 root 1.4 sub server_name {
256     my ($name) = @_;
257    
258     unless (defined $name) {
259     $name = File::Basename::basename ($0);
260     $name =~ s/\.(?:pl|perl)\z//;
261     $name = "perl" if $name eq "-e";
262     }
263    
264     $name =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/
265     or die "Invalid MCP server name '$name'\n";
266    
267     $name
268     }
269    
270     sub http_getopt {
271 root 1.5 my ($name, $bind, $print_url, $tokens) = @_;
272 root 1.4
273 root 1.5 "name=s" => $name, "bind=s" => $bind, "print-url" => $print_url, "token=s@" => $tokens
274 root 1.4 }
275    
276     sub server_port {
277     my ($self, $name) = @_;
278    
279     $name = server_name $name;
280    
281     my $info = pack "N/a*N/a*", "AnyEvent::MCP port v1", $name;
282     16384 + ((unpack "n", AnyEvent::MCP::hkdf_sha512_expand (
283     pack ("H*", $self->{section}{global}{secret}), $info, 2
284     )) & 16383)
285     }
286    
287     sub http_settings {
288     my ($self, $name, $bind) = @_;
289    
290     $name = server_name $name;
291 root 1.10 my $settings = $self->{section}{"instance $name"} || {};
292 root 1.4 my $port = $self->server_port ($name);
293     my $configured = $settings->{bind} // "127.0.0.1:$port";
294     $configured = "127.0.0.1$configured" if $configured =~ /\A:[0-9]+\z/;
295     my ($configured_host, $configured_port) = AnyEvent::Socket::parse_hostport $configured, $port;
296     defined $configured_host && defined $configured_port
297     && $configured_port =~ /\A[0-9]+\z/ && $configured_port <= 65535
298     or die "Invalid MCP bind address '$configured'\n";
299    
300     $bind = $configured unless defined $bind;
301     $bind = "127.0.0.1$bind" if $bind =~ /\A:[0-9]+\z/;
302    
303     my ($host, $service) = AnyEvent::Socket::parse_hostport $bind, $configured_port;
304     defined $host && defined $service && $service =~ /\A[0-9]+\z/ && $service <= 65535
305     or die "Invalid MCP bind address '$bind'\n";
306    
307     my %kv = (
308     (map { exists $settings->{$_} ? ($_ => $settings->{$_}) : () }
309 root 1.5 qw(path url_host url_scheme)),
310 root 1.4 name => $name,
311     host => $host,
312     port => $service,
313     );
314    
315     unless (AnyEvent::Socket::parse_address $host) {
316     my ($error, @addresses) = Socket::getaddrinfo ($host, undef, { socktype => Socket::SOCK_STREAM () });
317     !$error && @addresses
318     or die "Cannot resolve MCP bind host '$host': $error\n";
319    
320 root 1.9 my (undef, $address) = AnyEvent::Socket::unpack_sockaddr $addresses[0]{addr};
321 root 1.4
322     $kv{url_host} //= $host;
323 root 1.9 $kv{host} = AnyEvent::Socket::format_address $address;
324 root 1.4 }
325    
326 root 1.11 $kv{tokens} = [exists $settings->{tokens}
327     ? split /\s*,\s*/, $settings->{tokens}, -1
328     : $self->credential ("token", $name)];
329 root 1.4
330     %kv
331     }
332    
333     sub http_url {
334     my ($self, $name, $bind, %options) = @_;
335    
336 root 1.11 # only a derived token depends on the master secret surviving this process.
337 root 1.8 if (($options{auth} || "") ne "none"
338     && !exists $options{tokens}
339 root 1.10 && !exists $self->{section}{"instance $name"}{tokens}) {
340 root 1.8 my $stored = ref ($self)->new (file => $self->{file});
341     $stored->{section}{global}{secret} eq $self->{section}{global}{secret}
342     or die "MCP master secret is not persistently stored in $self->{file}\n";
343     }
344 root 1.4
345     require AnyEvent::MCP::Server::HTTP;
346 root 1.8 my %http = $self->http_settings ($name, $bind);
347     delete $http{tokens} if ($options{auth} || "") eq "none";
348 root 1.11
349     AnyEvent::MCP::Server::HTTP->new (%http, %options)->url
350 root 1.4 }
351    
352 root 1.1
353     1