postgres-mcp-readonly 0.1.8

Read-only MCP server for PostgreSQL and TimescaleDB
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! SSL modes and the rustls client configuration used for PostgreSQL connections.
// WireError::Db holds DbError by value (fixed by the interface), so Result<_, WireError> is large.
#![allow(clippy::result_large_err)]

use std::borrow::Cow;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;

use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::client::{WebPkiServerVerifier, verify_server_cert_signed_by_trust_anchor};
use rustls::crypto::CryptoProvider;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::{
    CertificateError, ClientConfig, DigitallySignedStruct, Error as TlsError, InconsistentKeys,
    RootCertStore, SignatureScheme,
};
use x509_parser::parse_x509_certificate;

use crate::pg::wire::WireError;

/// libpq-style SSL modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SslMode {
    Disable,
    Prefer,
    Require,
    VerifyCa,
    VerifyFull,
}

impl SslMode {
    /// The libpq name of the mode, as the configuration spells it.
    pub fn as_str(self) -> &'static str {
        match self {
            SslMode::Disable => "disable",
            SslMode::Prefer => "prefer",
            SslMode::Require => "require",
            SslMode::VerifyCa => "verify-ca",
            SslMode::VerifyFull => "verify-full",
        }
    }
}

impl FromStr for SslMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "disable" => Ok(SslMode::Disable),
            "prefer" => Ok(SslMode::Prefer),
            "require" => Ok(SslMode::Require),
            "verify-ca" => Ok(SslMode::VerifyCa),
            "verify-full" => Ok(SslMode::VerifyFull),
            other => Err(format!("invalid ssl mode \"{other}\"")),
        }
    }
}

/// Where one PEM item comes from: a file read at startup, or PEM text given inline. Inline text is never printed.
#[derive(Clone)]
pub enum PemSource {
    File(PathBuf),
    Inline(String),
}

impl fmt::Debug for PemSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PemSource::File(path) => f.debug_tuple("File").field(path).finish(),
            PemSource::Inline(_) => f.write_str("Inline(<redacted>)"),
        }
    }
}

/// The TLS items of one database: the trusted roots, and a client certificate chain with its key.
#[derive(Clone, Debug, Default)]
pub struct TlsSources {
    pub root: Option<PemSource>,
    pub client_cert: Option<PemSource>,
    pub client_key: Option<PemSource>,
}

/// A client certificate chain (leaf first) and its private key.
type Identity = (Vec<CertificateDer<'static>>, PrivateKeyDer<'static>);

/// Builds the rustls client configuration for `mode`, with roots from `root_cert` (a PEM file) when given.
pub fn client_config(
    mode: SslMode,
    root_cert: Option<&Path>,
) -> Result<Arc<ClientConfig>, WireError> {
    if mode == SslMode::VerifyCa && root_cert.is_none() {
        return Err(WireError::Tls("sslmode=verify-ca needs sslrootcert".into()));
    }
    let roots = match root_cert {
        Some(path) => read_roots_file(path).map_err(|e| e.wire(path))?,
        None => bundled_roots(),
    };
    build_config(mode, roots, None).map_err(WireError::Tls)
}

/// The configuration for a database at startup, read once and then shared. Every error names the setting
/// (`sslrootcert`, `sslcert_pem` and so on) and never the file path's contents or any key material.
pub fn startup_client_config(
    mode: SslMode,
    sources: &TlsSources,
) -> Result<Arc<ClientConfig>, String> {
    if mode == SslMode::VerifyCa && sources.root.is_none() {
        return Err("sslmode=verify-ca needs sslrootcert".to_owned());
    }
    let roots = match &sources.root {
        Some(source) => startup_roots(source)?,
        None => bundled_roots(),
    };
    let identity = client_identity(sources)?;
    build_config(mode, roots, identity)
}

/// The trusted roots, and the certificates they were read from. The latter are pinned (see `Verifier`).
struct Roots {
    store: RootCertStore,
    pinned: Vec<CertificateDer<'static>>,
}

fn bundled_roots() -> Roots {
    let mut store = RootCertStore::empty();
    store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    Roots {
        store,
        pinned: Vec::new(),
    }
}

/// The setting name in a message: `base` for a file, `base_pem` for inline text.
fn item_name(source: &PemSource, base: &str) -> String {
    match source {
        PemSource::File(_) => base.to_owned(),
        PemSource::Inline(_) => format!("{base}_pem"),
    }
}

/// The PEM bytes of one item. A file that cannot be read gives `cannot read <item>: <io reason>`.
fn pem_bytes<'a>(source: &'a PemSource, item: &str) -> Result<Cow<'a, [u8]>, String> {
    match source {
        PemSource::File(path) => std::fs::read(path)
            .map(Cow::Owned)
            .map_err(|e| format!("cannot read {item}: {e}")),
        PemSource::Inline(text) => Ok(Cow::Borrowed(text.as_bytes())),
    }
}

/// Why a root certificate cannot be used. The variants hold the cause, never the file contents.
enum RootsError {
    Open(io::Error),
    Read(String),
    Empty,
    Add(String),
}

impl RootsError {
    /// The text the wire client reports for a connection that cannot load its root file.
    fn wire(self, path: &Path) -> WireError {
        let shown = path.display();
        WireError::Tls(match self {
            RootsError::Open(e) => format!("cannot open {shown}: {e}"),
            RootsError::Read(m) => format!("cannot read {shown}: {m}"),
            RootsError::Empty => format!("no certificates found in {shown}"),
            RootsError::Add(m) => m,
        })
    }

    /// The text the startup check reports for the setting `item`; PEM syntax errors are not echoed.
    fn startup(self, item: &str) -> String {
        match self {
            RootsError::Open(e) => format!("cannot read {item}: {e}"),
            RootsError::Read(_) => format!("{item} is not valid PEM"),
            RootsError::Empty => format!("{item} holds no certificate"),
            RootsError::Add(m) => format!("cannot read {item}: {m}"),
        }
    }
}

fn read_roots_file(path: &Path) -> Result<Roots, RootsError> {
    let bytes = std::fs::read(path).map_err(RootsError::Open)?;
    roots_from_pem(&bytes)
}

fn startup_roots(source: &PemSource) -> Result<Roots, String> {
    let item = item_name(source, "sslrootcert");
    let bytes = pem_bytes(source, &item)?;
    roots_from_pem(&bytes).map_err(|e| e.startup(&item))
}

fn roots_from_pem(bytes: &[u8]) -> Result<Roots, RootsError> {
    let mut store = RootCertStore::empty();
    let mut pinned = Vec::new();
    for cert in CertificateDer::pem_slice_iter(bytes) {
        let cert = cert.map_err(|e| RootsError::Read(e.to_string()))?;
        store
            .add(cert.clone())
            .map_err(|e| RootsError::Add(e.to_string()))?;
        pinned.push(cert);
    }
    if store.is_empty() {
        return Err(RootsError::Empty);
    }
    Ok(Roots { store, pinned })
}

/// The client identity from the certificate and key sources: both or neither. None when neither is set.
fn client_identity(sources: &TlsSources) -> Result<Option<Identity>, String> {
    let (cert_source, key_source) = match (&sources.client_cert, &sources.client_key) {
        (None, None) => return Ok(None),
        (Some(cert), Some(key)) => (cert, key),
        _ => return Err("sslcert and sslkey must be set together".to_owned()),
    };
    let cert_item = item_name(cert_source, "sslcert");
    let chain = {
        let bytes = pem_bytes(cert_source, &cert_item)?;
        CertificateDer::pem_slice_iter(&bytes)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|_| format!("{cert_item} is not valid PEM"))?
    };
    if chain.is_empty() {
        return Err(format!("{cert_item} holds no certificate"));
    }
    let key_item = item_name(key_source, "sslkey");
    let key = {
        let bytes = pem_bytes(key_source, &key_item)?;
        if is_encrypted_pem(&bytes) {
            return Err(format!(
                "{key_item} is encrypted; provide an unencrypted PEM key"
            ));
        }
        match PrivateKeyDer::pem_slice_iter(&bytes).next() {
            None => return Err(format!("{key_item} holds no private key")),
            Some(Err(_)) => return Err(format!("{key_item} is not valid PEM")),
            Some(Ok(key)) => key,
        }
    };
    Ok(Some((chain, key)))
}

/// True for PKCS#8 encrypted armour and for the PEM `Proc-Type: 4,ENCRYPTED` header. Only the labels are read.
fn is_encrypted_pem(bytes: &[u8]) -> bool {
    String::from_utf8_lossy(bytes).lines().any(|line| {
        let line = line.trim();
        line == "-----BEGIN ENCRYPTED PRIVATE KEY-----"
            || (line.starts_with("Proc-Type:") && line.contains("ENCRYPTED"))
    })
}

fn build_config(
    mode: SslMode,
    roots: Roots,
    identity: Option<Identity>,
) -> Result<Arc<ClientConfig>, String> {
    let store = Arc::new(roots.store);
    let provider = Arc::new(rustls::crypto::ring::default_provider());
    let webpki = WebPkiServerVerifier::builder_with_provider(store.clone(), provider.clone())
        .build()
        .map_err(|e| e.to_string())?;
    let verifier = Verifier {
        mode,
        provider: provider.clone(),
        roots: store,
        pinned: roots.pinned,
        webpki,
    };
    let builder = ClientConfig::builder_with_provider(provider)
        .with_safe_default_protocol_versions()
        .map_err(|e| e.to_string())?
        .dangerous()
        .with_custom_certificate_verifier(Arc::new(verifier));
    let config = match identity {
        None => builder.with_no_client_auth(),
        Some((chain, key)) => builder
            .with_client_auth_cert(chain, key)
            .map_err(client_key_error)?,
    };
    Ok(Arc::new(config))
}

/// rustls refuses a key that does not belong to the certificate; any other refusal means the key is unusable.
fn client_key_error(error: TlsError) -> String {
    match error {
        TlsError::InconsistentKeys(InconsistentKeys::KeyMismatch) => {
            "sslkey does not match sslcert".to_owned()
        }
        _ => "sslkey is not a supported private key".to_owned(),
    }
}

/// Certificate verifier: Require/Prefer accept any certificate, VerifyCa checks the chain only,
/// VerifyFull also checks the server name. Handshake signatures are always checked.
#[derive(Debug)]
struct Verifier {
    mode: SslMode,
    provider: Arc<CryptoProvider>,
    roots: Arc<RootCertStore>,
    /// The configured root certificates, compared byte for byte with the server certificate.
    pinned: Vec<CertificateDer<'static>>,
    webpki: Arc<WebPkiServerVerifier>,
}

impl Verifier {
    /// True when `end_entity` is byte for byte one of the configured root certificates.
    fn is_pinned(&self, end_entity: &CertificateDer<'_>) -> bool {
        self.pinned
            .iter()
            .any(|der| der.as_ref() == end_entity.as_ref())
    }

    /// The checks for a pinned certificate, its own trust anchor: validity period, then the server
    /// name when `server_name` is given (VerifyFull).
    fn verify_pinned(
        &self,
        end_entity: &CertificateDer<'_>,
        server_name: Option<&ServerName<'_>>,
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        check_validity(end_entity, now)?;
        if let Some(name) = server_name {
            let parsed = webpki::EndEntityCert::try_from(end_entity)
                .map_err(|_| CertificateError::BadEncoding)?;
            parsed
                .verify_is_valid_for_subject_name(name)
                .map_err(name_error)?;
        }
        Ok(ServerCertVerified::assertion())
    }
}

/// The validity period of a pinned certificate: notBefore <= now <= notAfter.
fn check_validity(end_entity: &CertificateDer<'_>, now: UnixTime) -> Result<(), rustls::Error> {
    let (_, cert) =
        parse_x509_certificate(end_entity.as_ref()).map_err(|_| CertificateError::BadEncoding)?;
    let validity = cert.validity();
    let now = i64::try_from(now.as_secs()).unwrap_or(i64::MAX);
    if now < validity.not_before.timestamp() {
        return Err(CertificateError::NotValidYet.into());
    }
    if now > validity.not_after.timestamp() {
        return Err(CertificateError::Expired.into());
    }
    Ok(())
}

/// The name refusal as rustls reports it, with webpki's context.
fn name_error(error: webpki::Error) -> rustls::Error {
    match error {
        webpki::Error::CertNotValidForName(context) => CertificateError::NotValidForNameContext {
            expected: context.expected,
            presented: context.presented,
        }
        .into(),
        _ => CertificateError::NotValidForName.into(),
    }
}

impl ServerCertVerifier for Verifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        match self.mode {
            SslMode::VerifyFull => match self.webpki.verify_server_cert(
                end_entity,
                intermediates,
                server_name,
                ocsp_response,
                now,
            ) {
                Err(_) if self.is_pinned(end_entity) => {
                    self.verify_pinned(end_entity, Some(server_name), now)
                }
                verdict => verdict,
            },
            SslMode::VerifyCa => {
                let parsed = end_entity.try_into()?;
                match verify_server_cert_signed_by_trust_anchor(
                    &parsed,
                    &self.roots,
                    intermediates,
                    now,
                    self.provider.signature_verification_algorithms.all,
                ) {
                    Ok(()) => Ok(ServerCertVerified::assertion()),
                    Err(_) if self.is_pinned(end_entity) => {
                        self.verify_pinned(end_entity, None, now)
                    }
                    Err(e) => Err(e),
                }
            }
            SslMode::Disable | SslMode::Prefer | SslMode::Require => {
                Ok(ServerCertVerified::assertion())
            }
        }
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.webpki.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.webpki.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.webpki.supported_verify_schemes()
    }
}