ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/lib/AnyEvent/MCP/Config.pm
Revision: 1.8
Committed: Sun Oct 11 01:46:31 2026 UTC (4 weeks, 3 days ago) by root
Branch: MAIN
Changes since 1.7: +26 -17 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     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.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     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.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     my $self = $class->SUPER::new (section => {}, %kv);
136     $self->{file} = _file unless exists $self->{file};
137    
138     if (open my $fh, "<:encoding(UTF-8)", $self->{file}) {
139     $self->_read ($fh);
140     close $fh or die "$self->{file}: $!\n";
141     } else {
142     die "$self->{file}: $!\n" unless $! == ENOENT;
143     }
144    
145     $self->_ensure_secret;
146    
147     die "$self->{file}: invalid secret; supply 128 hexadecimal digits\n"
148     unless $self->{section}{global}{secret} =~ /\A[0-9a-fA-F]{128}\z/;
149    
150     $self
151     }
152    
153     sub _read {
154     my ($self, $fh) = @_;
155    
156     my @stat = stat $fh;
157     die "$self->{file}: configuration must be private and owned by this user\n"
158     if $stat[4] != $< || $stat[2] & 077;
159    
160     my $section = $self->{section}{global} ||= {};
161    
162     while (<$fh>) {
163     next if /\A\s*(?:[#;]|\z)/;
164    
165     if (/\A\s*\[([^\]\r\n]+)\]\s*\z/) {
166     $section = $self->{section}{$1} ||= {};
167     } elsif (/\A\s*([^=\s]+)\s*=\s*(.*?)\s*\z/) {
168     $section->{$1} = $2;
169     } else {
170     die "$self->{file}:$.: invalid configuration line\n";
171     }
172     }
173    
174     }
175    
176     sub _ensure_secret {
177     my ($self) = @_;
178    
179     return if exists $self->{section}{global}{secret};
180    
181     my $secret = eval { unpack "H*", AnyEvent::MCP::random_bytes 64 };
182     die "$@Supply a securely generated 128-digit hexadecimal secret in $self->{file}\n"
183     if $@;
184    
185     eval {
186     File::Path::mkpath (File::Basename::dirname ($self->{file}), 0, 0700);
187     sysopen my $fh, $self->{file}, O_RDWR | O_CREAT, 0600
188     or die "$self->{file}: $!\n";
189     flock $fh, LOCK_EX or die "$self->{file}: $!\n";
190     binmode $fh, ":encoding(UTF-8)";
191    
192     my $disk = bless { file => $self->{file}, section => {} }, ref $self;
193     $disk->_read ($fh);
194    
195     unless (exists $disk->{section}{global}{secret}) {
196     seek $fh, 0, 2 or die "$self->{file}: $!\n";
197     print {$fh} "\n[global]\nsecret = $secret\n"
198     or die "$self->{file}: $!\n";
199     $disk->{section}{global}{secret} = $secret;
200     }
201    
202     close $fh or die "$self->{file}: $!\n";
203     $self->{section} = $disk->{section};
204     1
205     } or warn "Cannot save MCP master secret; credentials may only be stable for this process: $@";
206    
207     $self->{section}{global}{secret} = $secret
208     unless exists $self->{section}{global}{secret};
209     }
210    
211     sub init {
212     my ($class, %kv) = @_;
213     my $file = exists $kv{file} ? $kv{file} : _file;
214    
215     my $secret = AnyEvent::MCP::random_bytes 64;
216    
217     File::Path::mkpath (File::Basename::dirname ($file), 0, 0700);
218    
219     sysopen my $fh, $file, O_WRONLY | O_CREAT | O_EXCL, 0600
220     or die "$file: $!\n";
221    
222     print {$fh} "[global]\nsecret = ", unpack ("H*", $secret), "\n"
223     or die "$file: $!\n";
224     close $fh or die "$file: $!\n";
225    
226     $class->new (file => $file)
227     }
228    
229     sub credential {
230     my ($self, $purpose, $name, $username) = @_;
231    
232     $username = "" unless defined $username;
233    
234     die "Unknown credential purpose '$purpose'\n"
235 root 1.8 unless $purpose eq "token";
236 root 1.1
237     my $secret = $self->{section}{global}{secret};
238     die "$self->{file}: missing or invalid secret\n"
239     unless $secret =~ /\A[0-9a-fA-F]{128}\z/;
240    
241     my $info = pack "N/a*N/a*N/a*N/a*",
242     "AnyEvent::MCP credential v1", $purpose,
243 root 1.2 AnyEvent::MCP::utf8enc ($name), AnyEvent::MCP::utf8enc ($username);
244 root 1.1
245     my $credential = MIME::Base64::encode_base64 (
246     AnyEvent::MCP::hkdf_sha512_expand (pack ("H*", $secret), $info, 32), ""
247     );
248     $credential =~ y!+/=!-_!d;
249    
250     $credential
251     }
252    
253 root 1.4 sub server_name {
254     my ($name) = @_;
255    
256     unless (defined $name) {
257     require File::Basename;
258     $name = File::Basename::basename ($0);
259     $name =~ s/\.(?:pl|perl)\z//;
260     $name = "perl" if $name eq "-e";
261     }
262    
263     $name =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/
264     or die "Invalid MCP server name '$name'\n";
265    
266     $name
267     }
268    
269     sub http_getopt {
270 root 1.5 my ($name, $bind, $print_url, $tokens) = @_;
271 root 1.4
272 root 1.5 "name=s" => $name, "bind=s" => $bind, "print-url" => $print_url, "token=s@" => $tokens
273 root 1.4 }
274    
275     sub server_port {
276     my ($self, $name) = @_;
277    
278     $name = server_name $name;
279    
280     my $info = pack "N/a*N/a*", "AnyEvent::MCP port v1", $name;
281     16384 + ((unpack "n", AnyEvent::MCP::hkdf_sha512_expand (
282     pack ("H*", $self->{section}{global}{secret}), $info, 2
283     )) & 16383)
284     }
285    
286     sub http_settings {
287     my ($self, $name, $bind) = @_;
288    
289     $name = server_name $name;
290     my $settings = $self->{section}{"server $name"} || {};
291     my $port = $self->server_port ($name);
292     my $configured = $settings->{bind} // "127.0.0.1:$port";
293     $configured = "127.0.0.1$configured" if $configured =~ /\A:[0-9]+\z/;
294     my ($configured_host, $configured_port) = AnyEvent::Socket::parse_hostport $configured, $port;
295     defined $configured_host && defined $configured_port
296     && $configured_port =~ /\A[0-9]+\z/ && $configured_port <= 65535
297     or die "Invalid MCP bind address '$configured'\n";
298    
299     $bind = $configured unless defined $bind;
300     $bind = "127.0.0.1$bind" if $bind =~ /\A:[0-9]+\z/;
301    
302     my ($host, $service) = AnyEvent::Socket::parse_hostport $bind, $configured_port;
303     defined $host && defined $service && $service =~ /\A[0-9]+\z/ && $service <= 65535
304     or die "Invalid MCP bind address '$bind'\n";
305    
306     my %kv = (
307     (map { exists $settings->{$_} ? ($_ => $settings->{$_}) : () }
308 root 1.5 qw(path url_host url_scheme)),
309 root 1.4 name => $name,
310     host => $host,
311     port => $service,
312     );
313    
314     unless (AnyEvent::Socket::parse_address $host) {
315     my ($error, @addresses) = Socket::getaddrinfo ($host, undef, { socktype => Socket::SOCK_STREAM () });
316     !$error && @addresses
317     or die "Cannot resolve MCP bind host '$host': $error\n";
318    
319     my ($error2, $address) = Socket::getnameinfo ($addresses[0]{addr}, Socket::NI_NUMERICHOST ());
320     !$error2 && length $address
321     or die "Cannot format MCP bind host '$host': $error2\n";
322    
323     $kv{url_host} //= $host;
324     $kv{host} = $address;
325     }
326    
327 root 1.5 if (exists $settings->{tokens}) {
328     $kv{tokens} = [split /\s*,\s*/, $settings->{tokens}, -1];
329     } else {
330 root 1.8 my $token = $self->credential ("token", $name);
331 root 1.5 $kv{tokens} = [$token];
332 root 1.4 }
333    
334     %kv
335     }
336    
337     sub http_url {
338     my ($self, $name, $bind, %options) = @_;
339    
340 root 1.8 # Only a derived token depends on the master secret surviving this process.
341     if (($options{auth} || "") ne "none"
342     && !exists $options{tokens}
343     && !exists $self->{section}{"server $name"}{tokens}) {
344     my $stored = ref ($self)->new (file => $self->{file});
345     $stored->{section}{global}{secret} eq $self->{section}{global}{secret}
346     or die "MCP master secret is not persistently stored in $self->{file}\n";
347     }
348 root 1.4
349     require AnyEvent::MCP::Server::HTTP;
350 root 1.8 my %http = $self->http_settings ($name, $bind);
351     delete $http{tokens} if ($options{auth} || "") eq "none";
352     my $server = AnyEvent::MCP::Server::HTTP->new (%http, %options);
353 root 1.4 $server->url
354     }
355    
356 root 1.1
357     1