ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/lib/AnyEvent/MCP/Config.pm
Revision: 1.2
Committed: Fri Oct 9 06:18:51 2026 UTC (4 weeks, 4 days ago) by root
Branch: MAIN
Changes since 1.1: +1 -2 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     my $password = $config->credential ("basic", "agni", "alice");
9     my $url = $config->url ("agni");
10    
11     =head1 DESCRIPTION
12    
13     This module loads and holds the shared configuration described in
14     L<AnyEvent::MCP/GLOBAL CONFIGURATION>. Loading the module itself does not
15     access files. The first call to C<global> reads the configuration, ensures
16     a master secret exists and caches the object for the process.
17    
18     A missing secret is generated using C<AnyEvent::MCP::random_bytes> and saved
19     when possible. Saving failure produces a warning; the generated secret remains
20     usable in this process. A supplied invalid secret is an error.
21     Credentials change if the master key changes.
22    
23     Derivation uses HKDF-SHA512 expansion with the random master key as its PRK.
24     Server name, username and credential purpose are separately length-prefixed,
25     so credentials for different servers, users or authentication methods differ.
26     Deriving a password does not create or authorize an account on a server.
27    
28     =head1 METHODS
29    
30     =head2 $config = AnyEvent::MCP::Config->global (file => $file)
31    
32     Returns the cached global configuration. The first call accepts the same
33     arguments as C<new>; later calls return the same object without rereading
34     the file. Call this explicitly during program startup.
35    
36     =head2 $config = AnyEvent::MCP::Config->new (file => $file)
37    
38     Reads C<$file>, or the default file when omitted, and ensures a master
39     secret exists. Unlike C<global>, each call creates an independent object.
40     A missing file is allowed; other read errors are fatal. Sections are available
41     as C<< $config->{section}{$section} >>, each a hash reference of string
42     values. Named servers use C<[server NAME]>.
43    
44     =head2 $config = AnyEvent::MCP::Config->init (file => $file)
45    
46     Explicitly creates the configuration file with a random secret, mode 0600.
47     Creates missing parent directories with mode 0700. Fails if the file already
48     exists, so it cannot accidentally replace an existing secret.
49    
50     =head2 $credential = $config->credential ($purpose, $name, $username)
51    
52     Derives a 32-byte credential, returned as unpadded URL-safe Base64.
53     C<$purpose> is C<basic>, C<bearer> or C<cookie>. C<$name> is the server
54     name. C<$username> can be omitted for a server-wide credential.
55    
56     This method does not require a corresponding server section.
57    
58     =head2 $url = $config->url ($name, $username)
59    
60     Returns the configured C<url> for C<$name>, replacing C<{cookie}> with the
61     derived cookie credential. C<$username> can be omitted.
62    
63     The template supplies scheme, host, port, path and cookie placement explicitly.
64     This method neither contacts a server nor infers an ephemeral listening port.
65     The HTTP server does not consume this configuration automatically.
66    
67     =cut
68    
69     package AnyEvent::MCP::Config;
70    
71     use common::sense;
72     use AnyEvent::MCP ();
73     use MIME::Base64 ();
74     use File::Basename ();
75     use File::Path ();
76     use Fcntl qw(O_WRONLY O_RDWR O_CREAT O_EXCL LOCK_EX);
77     use Errno qw(ENOENT);
78    
79     our @ISA = qw(AnyEvent::MCP::Base);
80    
81     sub _file {
82     my $dir = $ENV{XDG_CONFIG_HOME}
83     || ($ENV{HOME} || die "HOME is not set\n") . "/.config";
84    
85     "$dir/anyevent-mcp/global.ini"
86     }
87    
88     my $global;
89    
90     sub global {
91     my $class = shift;
92    
93     $global ||= $class->new (@_)
94     }
95    
96     sub new {
97     my ($class, %kv) = @_;
98     my $self = $class->SUPER::new (section => {}, %kv);
99     $self->{file} = _file unless exists $self->{file};
100    
101     if (open my $fh, "<:encoding(UTF-8)", $self->{file}) {
102     $self->_read ($fh);
103     close $fh or die "$self->{file}: $!\n";
104     } else {
105     die "$self->{file}: $!\n" unless $! == ENOENT;
106     }
107    
108     $self->_ensure_secret;
109    
110     die "$self->{file}: invalid secret; supply 128 hexadecimal digits\n"
111     unless $self->{section}{global}{secret} =~ /\A[0-9a-fA-F]{128}\z/;
112    
113     $self
114     }
115    
116     sub _read {
117     my ($self, $fh) = @_;
118    
119     my @stat = stat $fh;
120     die "$self->{file}: configuration must be private and owned by this user\n"
121     if $stat[4] != $< || $stat[2] & 077;
122    
123     my $section = $self->{section}{global} ||= {};
124    
125     while (<$fh>) {
126     next if /\A\s*(?:[#;]|\z)/;
127    
128     if (/\A\s*\[([^\]\r\n]+)\]\s*\z/) {
129     $section = $self->{section}{$1} ||= {};
130     } elsif (/\A\s*([^=\s]+)\s*=\s*(.*?)\s*\z/) {
131     $section->{$1} = $2;
132     } else {
133     die "$self->{file}:$.: invalid configuration line\n";
134     }
135     }
136    
137     }
138    
139     sub _ensure_secret {
140     my ($self) = @_;
141    
142     return if exists $self->{section}{global}{secret};
143    
144     my $secret = eval { unpack "H*", AnyEvent::MCP::random_bytes 64 };
145     die "$@Supply a securely generated 128-digit hexadecimal secret in $self->{file}\n"
146     if $@;
147    
148     eval {
149     File::Path::mkpath (File::Basename::dirname ($self->{file}), 0, 0700);
150     sysopen my $fh, $self->{file}, O_RDWR | O_CREAT, 0600
151     or die "$self->{file}: $!\n";
152     flock $fh, LOCK_EX or die "$self->{file}: $!\n";
153     binmode $fh, ":encoding(UTF-8)";
154    
155     my $disk = bless { file => $self->{file}, section => {} }, ref $self;
156     $disk->_read ($fh);
157    
158     unless (exists $disk->{section}{global}{secret}) {
159     seek $fh, 0, 2 or die "$self->{file}: $!\n";
160     print {$fh} "\n[global]\nsecret = $secret\n"
161     or die "$self->{file}: $!\n";
162     $disk->{section}{global}{secret} = $secret;
163     }
164    
165     close $fh or die "$self->{file}: $!\n";
166     $self->{section} = $disk->{section};
167     1
168     } or warn "Cannot save MCP master secret; credentials may only be stable for this process: $@";
169    
170     $self->{section}{global}{secret} = $secret
171     unless exists $self->{section}{global}{secret};
172     }
173    
174     sub init {
175     my ($class, %kv) = @_;
176     my $file = exists $kv{file} ? $kv{file} : _file;
177    
178     my $secret = AnyEvent::MCP::random_bytes 64;
179    
180     File::Path::mkpath (File::Basename::dirname ($file), 0, 0700);
181    
182     sysopen my $fh, $file, O_WRONLY | O_CREAT | O_EXCL, 0600
183     or die "$file: $!\n";
184    
185     print {$fh} "[global]\nsecret = ", unpack ("H*", $secret), "\n"
186     or die "$file: $!\n";
187     close $fh or die "$file: $!\n";
188    
189     $class->new (file => $file)
190     }
191    
192     sub credential {
193     my ($self, $purpose, $name, $username) = @_;
194    
195     $username = "" unless defined $username;
196    
197     die "Unknown credential purpose '$purpose'\n"
198     unless $purpose =~ /\A(?:basic|bearer|cookie)\z/;
199    
200     my $secret = $self->{section}{global}{secret};
201     die "$self->{file}: missing or invalid secret\n"
202     unless $secret =~ /\A[0-9a-fA-F]{128}\z/;
203    
204     my $info = pack "N/a*N/a*N/a*N/a*",
205     "AnyEvent::MCP credential v1", $purpose,
206 root 1.2 AnyEvent::MCP::utf8enc ($name), AnyEvent::MCP::utf8enc ($username);
207 root 1.1
208     my $credential = MIME::Base64::encode_base64 (
209     AnyEvent::MCP::hkdf_sha512_expand (pack ("H*", $secret), $info, 32), ""
210     );
211     $credential =~ y!+/=!-_!d;
212    
213     $credential
214     }
215    
216     sub url {
217     my ($self, $name, $username) = @_;
218    
219     my $url = $self->{section}{"server $name"}{url}
220     or die "No URL configured for server '$name'\n";
221    
222     $url =~ s/\{cookie\}/$self->credential ("cookie", $name, $username)/ge;
223    
224     $url
225     }
226    
227     1