Skip to main content

smgw/management/
mod.rs

1//! One read-only HTTP resource for the GWA and its loopback gateway simulator.
2//!
3//! The gateway initiates mutual TLS, then serves an HTTP request from its
4//! commissioned administrator. Both sides own the deadline for the entire
5//! connection. The local XML resource is a simulator contract, separate from
6//! the BSI management resources and their VDE-defined schemas.
7
8use crate::taf15::Record;
9use openssl::x509::X509;
10use smgw_sec::tls::TlsIdentity;
11pub use smgw_sec::transport::{SecureStream, TlsEndpoint};
12use std::{fs, io, path::Path};
13use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
14
15mod window;
16mod xml;
17pub use window::ProfileWindow;
18
19/// Correlates a callback to the exact signed wake-up accepted by the simulator.
20pub fn callback_id(signed_packet: &[u8]) -> [u8; 32] {
21    openssl::sha::sha256(signed_packet)
22}
23
24/// Announce the attempt, authenticate the administrator and confirm the attempt inside TLS.
25pub async fn connect_callback(
26    endpoint: &TlsEndpoint,
27    address: std::net::SocketAddr,
28    id: [u8; 32],
29    budget: std::time::Duration,
30) -> io::Result<SecureStream> {
31    smgw_sec::transport::check_loopback(address)?;
32    tokio::time::timeout(budget, async {
33        let mut tcp = tokio::net::TcpStream::connect(address).await?;
34        tcp.write_all(&id).await?;
35        let mut tls = endpoint.connect_socket(tcp, "gwa.test", budget).await?;
36        tls.write_all(&id).await?;
37        Ok(tls)
38    })
39    .await?
40}
41
42/// HTTP target for the fixture meter's registered 15-minute readings.
43pub const PROFILE_PATH: &str = "/simulator/v1/meter-profile";
44
45/// Synthetic DIN 43849 equipment identifier used by the simulator.
46pub const FIXTURE_RECIPIENT: [u8; 9] = [0x0e, b'T', b'S', b'T', 0, 0, 0, 0, 1];
47
48/// Parse a commissioned equipment identifier from 18 hexadecimal digits.
49pub fn parse_recipient(hex: &str) -> io::Result<[u8; 9]> {
50    if hex.len() != 18 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
51        return Err(io::Error::new(
52            io::ErrorKind::InvalidInput,
53            "expected an 18-digit hexadecimal gateway ID",
54        ));
55    }
56    let mut id = [0; 9];
57    for (i, byte) in id.iter_mut().enumerate() {
58        *byte =
59            u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).expect("validated hexadecimal octet");
60    }
61    if !crate::wakeup::valid_recipient(&id) {
62        return Err(io::Error::new(
63            io::ErrorKind::InvalidInput,
64            "invalid gateway equipment identifier",
65        ));
66    }
67    Ok(id)
68}
69
70/// Read a regular PEM fixture file within the maximum provisioning input size.
71pub fn read_provisioned_pem(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
72    use std::io::Read;
73    const MAX_PEM: u64 = 64 * 1024;
74    let path = path.as_ref();
75    if !fs::metadata(path)?.is_file() {
76        return Err(io::Error::new(
77            io::ErrorKind::InvalidInput,
78            "expected a regular PEM file",
79        ));
80    }
81    let mut pem = Vec::new();
82    fs::File::open(path)?
83        .take(MAX_PEM + 1)
84        .read_to_end(&mut pem)?;
85    if pem.len() as u64 > MAX_PEM {
86        return Err(invalid("management PEM exceeds 64 KiB"));
87    }
88    Ok(pem)
89}
90
91fn read_peer_leaf(bundle: &Path) -> io::Result<X509> {
92    Ok(X509::from_pem(&read_provisioned_pem(
93        bundle.join("peer.chain.pem"),
94    )?)?)
95}
96
97/// Read the commissioned gateway leaf pin from its administrator's bundle.
98/// This needs only the peer certificate. An executing worker must compare its
99/// loaded TLS endpoint's pin with the saved value before sending a wake-up.
100pub fn peer_fingerprint(bundle: &Path) -> io::Result<[u8; 32]> {
101    let peer = read_peer_leaf(bundle)?;
102    smgw_sec::transport::leaf_fingerprint(&peer)
103}
104
105/// Load one role's TLS identity, dedicated management root and peer pin from
106/// its own `management/gwa` or `management/smgw` credential bundle.
107pub fn load_endpoint(bundle: &Path) -> io::Result<TlsEndpoint> {
108    let identity = TlsIdentity::from_pem(
109        &read_provisioned_pem(bundle.join("tls.chain.pem"))?,
110        &read_provisioned_pem(bundle.join("tls.key.pem"))?,
111    )?;
112    let root = X509::from_pem(&read_provisioned_pem(bundle.join("root.pem"))?)?;
113    let peer = read_peer_leaf(bundle)?;
114    TlsEndpoint::from_identity(identity, &root, &peer)
115}
116
117const MAX_HEAD: usize = 2048;
118const MAX_BODY: usize = 2048;
119
120fn invalid(message: &'static str) -> io::Error {
121    io::Error::new(io::ErrorKind::InvalidData, message)
122}
123
124async fn read_head(reader: &mut (impl AsyncRead + Unpin)) -> io::Result<Vec<u8>> {
125    let mut head = Vec::new();
126    while head.len() < MAX_HEAD {
127        head.push(reader.read_u8().await?);
128        if head.ends_with(b"\r\n\r\n") {
129            return Ok(head);
130        }
131    }
132    Err(invalid("management HTTP header exceeds 2048 bytes"))
133}
134
135fn header<'a>(headers: &[httparse::Header<'a>], name: &str) -> io::Result<Option<&'a [u8]>> {
136    let mut matches = headers.iter().filter(|h| h.name.eq_ignore_ascii_case(name));
137    let value = matches.next().map(|h| h.value);
138    if matches.next().is_some() {
139        return Err(invalid("duplicate management HTTP header"));
140    }
141    Ok(value)
142}
143
144fn length(headers: &[httparse::Header<'_>]) -> io::Result<Option<usize>> {
145    if header(headers, "Transfer-Encoding")?.is_some()
146        || header(headers, "Content-Encoding")?.is_some()
147    {
148        return Err(invalid(
149            "management HTTP requires identity encoding and fixed framing",
150        ));
151    }
152    header(headers, "Content-Length")?
153        .map(|v| {
154            let n = std::str::from_utf8(v)
155                .ok()
156                .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
157                .and_then(|s| s.parse::<usize>().ok())
158                .filter(|n| *n <= MAX_BODY);
159            n.ok_or_else(|| invalid("invalid management HTTP content length"))
160        })
161        .transpose()
162}
163
164/// Read a bodyless profile GET and validate its quarter-hour window.
165pub async fn read_request(stream: &mut (impl AsyncRead + Unpin)) -> io::Result<ProfileWindow> {
166    let head = read_head(&mut BufReader::new(stream)).await?;
167    let mut headers = [httparse::EMPTY_HEADER; 16];
168    let mut request = httparse::Request::new(&mut headers);
169    if request.parse(&head) != Ok(httparse::Status::Complete(head.len()))
170        || request.version != Some(1)
171        || request.method != Some("GET")
172        || request.path != Some(PROFILE_PATH)
173        || header(request.headers, "Host")? != Some(&b"smgw.test"[..])
174        || length(request.headers)?.unwrap_or(0) != 0
175    {
176        return Err(invalid(
177            "expected a bodyless GET of the commissioned meter profile",
178        ));
179    }
180    let first = header(request.headers, "X-Profile-Start")?
181        .and_then(|v| std::str::from_utf8(v).ok())
182        .and_then(|v| v.parse().ok())
183        .ok_or_else(|| invalid("expected a profile window start"))?;
184    ProfileWindow::new(first)
185}
186
187/// Send the registered readings for the single commissioned fixture channel.
188pub async fn write_profile(
189    stream: &mut (impl AsyncWrite + Unpin),
190    window: ProfileWindow,
191    records: &[Record],
192) -> io::Result<()> {
193    let body = xml::encode(window, records)?;
194    let head = format!(
195        "HTTP/1.1 200 OK\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
196        body.len()
197    );
198    stream.write_all(head.as_bytes()).await?;
199    stream.write_all(body.as_bytes()).await?;
200    stream.flush().await
201}
202
203/// Return a bodyless HTTP 503 identifying the requested window.
204pub async fn write_unavailable(
205    stream: &mut (impl AsyncWrite + Unpin),
206    window: ProfileWindow,
207) -> io::Result<()> {
208    let head = format!(
209        "HTTP/1.1 503 Service Unavailable\r\nX-Profile-Start: {}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
210        window.first()
211    );
212    stream.write_all(head.as_bytes()).await?;
213    stream.flush().await
214}
215
216/// A complete, validated management response from a commissioned gateway.
217#[derive(Debug, PartialEq, Eq)]
218pub enum ReadOutcome {
219    /// The full profile, including an empty successful result when applicable.
220    Profile(Vec<Record>),
221    /// The gateway explicitly returned the simulator's bodyless HTTP 503.
222    MeterUnavailable,
223}
224
225/// Request the fixture resource from a mutually authenticated gateway. A meter
226/// outage returns `NotConnected`; malformed frames or XML return `InvalidData`.
227pub async fn request_profile(
228    stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
229    window: ProfileWindow,
230) -> io::Result<Vec<Record>> {
231    match request_profile_outcome(stream, window).await? {
232        ReadOutcome::Profile(records) => Ok(records),
233        ReadOutcome::MeterUnavailable => Err(io::Error::new(
234            io::ErrorKind::NotConnected,
235            "gateway could not read its commissioned meter",
236        )),
237    }
238}
239
240/// Issue the read and distinguish a complete gateway report from transport errors.
241/// A response can be trusted only when the caller authenticated the stream.
242pub async fn request_profile_outcome(
243    stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
244    window: ProfileWindow,
245) -> io::Result<ReadOutcome> {
246    let request = format!(
247        "GET {PROFILE_PATH} HTTP/1.1\r\nHost: smgw.test\r\nX-Profile-Start: {}\r\nAccept: application/xml\r\nConnection: close\r\n\r\n",
248        window.first()
249    );
250    stream.write_all(request.as_bytes()).await?;
251    stream.flush().await?;
252    let mut reader = BufReader::new(stream);
253    let head = read_head(&mut reader).await?;
254    let mut headers = [httparse::EMPTY_HEADER; 16];
255    let mut response = httparse::Response::new(&mut headers);
256    if response.parse(&head) != Ok(httparse::Status::Complete(head.len()))
257        || response.version != Some(1)
258    {
259        return Err(invalid("invalid management HTTP response"));
260    }
261    let len = length(response.headers)?
262        .ok_or_else(|| invalid("expected management HTTP content length"))?;
263    if response.code == Some(503)
264        && len == 0
265        && header(response.headers, "X-Profile-Start")?
266            == Some(window.first().to_string().as_bytes())
267    {
268        return Ok(ReadOutcome::MeterUnavailable);
269    }
270    if response.code != Some(200)
271        || header(response.headers, "Content-Type")? != Some(b"application/xml")
272    {
273        return Err(invalid("expected a successful management XML response"));
274    }
275    let mut body = vec![0; len];
276    reader.read_exact(&mut body).await?;
277    xml::decode(window, &body).map(ReadOutcome::Profile)
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use tokio::io::{AsyncReadExt, AsyncWriteExt, duplex};
284
285    #[tokio::test]
286    async fn only_a_bounded_bodyless_read_of_the_fixture_is_accepted() {
287        let head =
288            format!("GET {PROFILE_PATH} HTTP/1.1\r\nHost: smgw.test\r\nX-Profile-Start: 0\r\n");
289        let requests = [
290            head.replace("X-Profile-Start: 0\r\n", "") + "\r\n",
291            head.replace("Start: 0", "Start: 1") + "\r\n",
292            head.clone() + "X-Profile-Start: 900\r\n\r\n",
293            head.replace("GET ", "POST ") + "\r\n",
294            head.replace(PROFILE_PATH, "/") + "\r\n",
295            head.replace("smgw.test", "other.test") + "\r\n",
296            head.clone() + "Host: smgw.test\r\n\r\n",
297            head.clone() + "Transfer-Encoding: chunked\r\n\r\n",
298            head.clone() + "Content-Length: 0\r\nContent-Length: 0\r\n\r\n",
299            head.clone() + "Content-Length: 1\r\n\r\nx",
300            head + "X-Fill: " + &"x".repeat(MAX_HEAD) + "\r\n\r\n",
301        ];
302        for request in requests {
303            assert_eq!(
304                read_request(&mut request.as_bytes())
305                    .await
306                    .unwrap_err()
307                    .kind(),
308                io::ErrorKind::InvalidData
309            );
310        }
311    }
312
313    #[tokio::test]
314    async fn the_gwa_checks_response_framing_and_reports_meter_outage() {
315        let head = "HTTP/1.1 200 OK\r\nContent-Type: application/xml\r\n";
316        for (response, kind) in [
317            (
318                format!("{head}Content-Length: 2049\r\n\r\n"),
319                io::ErrorKind::InvalidData,
320            ),
321            (
322                format!("{head}Transfer-Encoding: chunked\r\nContent-Length: 0\r\n\r\n"),
323                io::ErrorKind::InvalidData,
324            ),
325            (
326                format!("{head}Content-Length: 2\r\n\r\nx"),
327                io::ErrorKind::UnexpectedEof,
328            ),
329            (
330                format!("{head}Content-Length: 1\r\n\r\nx"),
331                io::ErrorKind::InvalidData,
332            ),
333            (
334                "HTTP/1.1 503 Service Unavailable\r\nX-Profile-Start: 900\r\nContent-Length: 0\r\n\r\n".into(),
335                io::ErrorKind::InvalidData,
336            ),
337            (
338                "HTTP/1.1 503 Service Unavailable\r\nX-Profile-Start: 0\r\nContent-Length: 0\r\n\r\n".into(),
339                io::ErrorKind::NotConnected,
340            ),
341        ] {
342            let (mut gwa, mut gateway) = duplex(4096);
343            let (result, ()) =
344                tokio::join!(request_profile(&mut gwa, ProfileWindow::default()), async {
345                    let mut scratch = [0; 512];
346                    assert!(gateway.read(&mut scratch).await.unwrap() > 0);
347                    gateway.write_all(response.as_bytes()).await.unwrap();
348                    gateway.shutdown().await.unwrap();
349                });
350            assert_eq!(result.unwrap_err().kind(), kind);
351        }
352    }
353
354    #[test]
355    fn empty_response_still_identifies_its_window() {
356        let window = ProfileWindow::new(900).unwrap();
357        let xml = xml::encode(window, &[]).unwrap();
358        assert!(xml::decode(window, xml.as_bytes()).unwrap().is_empty());
359        assert!(xml::decode(ProfileWindow::default(), xml.as_bytes()).is_err());
360        for first in [1, i64::MIN, i64::MAX, -62_167_220_100, 2_005_917_607_800] {
361            assert!(ProfileWindow::new(first).is_err());
362        }
363    }
364
365    #[test]
366    fn profile_xml_checks_identity_and_preserves_original_measurement_fields() {
367        let record = Record {
368            reference_utc: 0,
369            measured_utc: 2,
370            coefficient: -12340,
371            scale: -1,
372            meter_status: None,
373        };
374        let xml = xml::encode(ProfileWindow::default(), &[record]).unwrap();
375        assert_eq!(
376            xml::decode(ProfileWindow::default(), xml.as_bytes()).unwrap(),
377            [record]
378        );
379        for other in [
380            xml.replace("fixture-meter", "another-meter"),
381            xml.replace("Wh", "kWh"),
382            xml.replace("firstUtc=\"0\"", "firstUtc=\"900\""),
383            xml.replace("profile:1", "other:1"),
384            xml.replace("referenceUtc=\"0\"", "referenceUtc=\"1\""),
385            xml.replace("scale=\"-1\"", "scale=\"-256\""),
386        ] {
387            assert!(xml::decode(ProfileWindow::default(), other.as_bytes()).is_err());
388        }
389        assert!(xml::encode(ProfileWindow::default(), &[record, record]).is_err());
390    }
391}