• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

polyphony-chat / polyproto-rs / #90

18 Jun 2025 09:45AM UTC coverage: 64.119% (-9.7%) from 73.783%
#90

push

bitfl0wer
feat: add faq shield

1401 of 2185 relevant lines covered (64.12%)

1.62 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

48.28
/src/api/core/mod.rs
1
// This Source Code Form is subject to the terms of the Mozilla Public
2
// License, v. 2.0. If a copy of the MPL was not distributed with this
3
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4

5
use std::time::UNIX_EPOCH;
6

7
use crate::certs::idcerttbs::IdCertTbs;
8
use crate::url::Url;
9

10
use crate::key::PublicKey;
11
use crate::signature::Signature;
12

13
use super::cacheable_cert::CacheableIdCert;
14
use crate::types::x509_cert::SerialNumber;
15
use log::trace;
16

17
use crate::certs::SessionId;
18
use crate::certs::idcert::IdCert;
19
#[cfg(feature = "reqwest")]
20
use crate::errors::RequestError;
21
use crate::key::PrivateKey;
22
use crate::types::routes::core::v1::*;
23
use crate::types::{EncryptedPkm, FederationId, Service, ServiceName};
24

25
#[cfg(feature = "reqwest")]
26
use super::{HttpClient, HttpResult, Session};
27

28
#[cfg(feature = "reqwest")]
29
mod federated_identity;
30
#[cfg(feature = "reqwest")]
31
mod migration;
32
#[cfg(feature = "reqwest")]
33
mod rawr;
34
#[cfg(feature = "reqwest")]
35
mod services;
36

37
#[cfg(feature = "reqwest")]
38
pub use routes::*;
39

40
/// Get the current UNIX timestamp according to the system clock.
41
pub fn current_unix_time() -> u64 {
1✔
42
    std::time::SystemTime::now()
1✔
43
        .duration_since(UNIX_EPOCH)
44
        .unwrap()
45
        .as_secs()
46
}
47

48
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
49
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
50
/// Response from querying a polyproto `.well-known` endpoint.
51
pub struct WellKnown {
52
    api: Url,
53
}
54

55
impl WellKnown {
56
    /// Return the [Url] that this .well-known entry points to.
57
    pub fn api(&self) -> &Url {
×
58
        &self.api
59
    }
60

61
    /// Create [Self] from a [Url], setting the `api` field to the supplied URL without performing any
62
    /// validity checks. Use [Self::new()] if you want to create [Self] from a link to a "visible domain".
63
    pub fn from_url(url: &Url) -> Self {
1✔
64
        Self::from(url.clone())
1✔
65
    }
66

67
    /**
68
    Checks whether the "visible domain" in a certificate matches the "actual url" specified by the
69
    `.well-known` endpoint of that "visible domain".
70

71
    ## .well-known validation criterions
72

73
    > *The following is an excerpt from section 3.1 of the polyproto specification.*
74

75
    polyproto servers can be hosted under a domain name different from the domain name appearing on ID-Certs managed by that server if all the following conditions are met:
76
    1. Define the "visible domain name" as the domain name visible on an ID-Cert.
77
    2. Define the "actual domain name" as the domain name where the polyproto server is actually hosted under.
78
    3. The visible domain name must have a URI [visible domain name]/.well-known/polyproto-core, accessible via an HTTP GET request.
79
    4. The resource accessible at this URI must be a JSON object formatted as such:
80

81
    ```json
82
     {
83
         "api": "[actual domain name]/.p2/core/"
84
     }
85
    ```
86

87
    5.  The ID-Cert received when querying [actual domain name]/.p2/core/idcert/server with an HTTP
88
        GET request must have a field "issuer" containing domain components (dc) that, when parsed,
89
        equal the domain name of the visible domain name. If the domain components in this field do
90
        not match the domain components of the visible domain name, the server hosted under the actual
91
        domain name must not be treated as a polyproto server for the visible domain name.
92

93
    If all the above-mentioned conditions can be fulfilled, the client
94
    can treat the server located at the actual domain name as a polyproto server serving the visible domain
95
    name. Clients must not treat the server located at the actual domain name as a polyproto server
96
    serving the actual domain name.
97

98
    ## TL;DR
99

100
    This function verifies these 5 criteria. If all of these criteria
101
    are fulfilled, `true` is returned. If any of the criteria are not fulfilled, `false` is returned.
102
    Criterion #3 is fulfilled by the existence of this struct object.
103
    */
104
    pub fn matches_certificate<S: Signature, P: PublicKey<S>>(
1✔
105
        &self,
106
        cert: &IdCertTbs<S, P>,
107
    ) -> bool {
108
        let visible_domain = match cert.issuer_url() {
1✔
109
            Ok(url) => url,
1✔
110
            Err(_) => return false,
×
111
        };
112
        let actual_domain = &self.api.host();
2✔
113
        trace!(
1✔
114
            "Checking for equality of {:?} and {:?}",
×
115
            visible_domain.host(),
×
116
            *actual_domain
×
117
        );
118
        visible_domain.host() == *actual_domain
2✔
119
    }
120

121
    /// Request the contents of the polyproto `.well-known` endpoint from a base url.
122
    ///
123
    /// This is a shorthand for
124
    /// ```rs
125
    /// self.request_as::<WellKnown>(http::Method::GET, url, None).await
126
    /// ```
127
    ///
128
    /// ## Errors
129
    ///
130
    /// This method will error if the server is unreachable or if the resource is malformed.
131
    #[cfg(feature = "reqwest")]
132
    pub async fn new(client: &HttpClient, url: &Url) -> HttpResult<Self> {
×
133
        client.get_well_known(url).await
×
134
    }
135
}
136

137
impl std::fmt::Display for WellKnown {
138
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
×
139
        f.write_str(self.api.as_str())
×
140
    }
141
}
142

143
impl From<Url> for WellKnown {
144
    /// Does NOT check whether [Self] is valid. Use [Self::new()] instead.
145
    fn from(value: Url) -> Self {
1✔
146
        WellKnown { api: value }
147
    }
148
}
149

150
impl<'a> From<&'a WellKnown> for &'a str {
151
    fn from(value: &'a WellKnown) -> Self {
×
152
        value.api.as_str()
×
153
    }
154
}
155

156
impl From<WellKnown> for Url {
157
    fn from(value: WellKnown) -> Self {
×
158
        value.api
×
159
    }
160
}
161

162
impl From<WellKnown> for String {
163
    fn from(value: WellKnown) -> Self {
×
164
        value.api.to_string()
×
165
    }
166
}
167

168
#[cfg(feature = "reqwest")]
169
/// Module containing an implementation of a reqwest-based HTTP client with polyproto routes
170
/// implemented on it.
171
pub mod routes {
172
    use serde::{Deserialize, Serialize};
173
    use url::Url;
174

175
    use crate::api::{HttpClient, HttpResult};
176
    use crate::types::Service;
177

178
    use super::WellKnown;
179

180
    // Core Routes: No registration needed
181
    impl HttpClient {
182
        /// Request the contents of the polyproto `.well-known` endpoint from a base url.
183
        ///
184
        /// This is a shorthand for
185
        /// ```rs
186
        /// self.request_as::<WellKnown>(http::Method::GET, url, None).await
187
        /// ```
188
        ///
189
        /// ## Errors
190
        ///
191
        /// This method will error if the server is unreachable or if the resource is malformed.
192
        pub async fn get_well_known(&self, url: &Url) -> HttpResult<WellKnown> {
4✔
193
            let url = url.join(".well-known/polyproto-core")?;
2✔
194
            self.request_as(http::Method::GET, url.as_str(), None).await
3✔
195
        }
196
    }
197

198
    #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
199
    /// Represents a pair of an [IdCert] and a token, used in the API as a response when an [IdCsr] has
200
    /// been accepted by the server.
201
    pub struct IdCertToken {
202
        /// The [IdCert] as a PEM encoded string
203
        pub id_cert: String,
204
        /// The token as a string
205
        pub token: String,
206
    }
207

208
    #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
209
    #[derive(Debug, Clone, PartialEq, Eq)]
210
    /// Represents a response to a service discovery deletion request. Contains the deleted service
211
    /// and, if applicable, the new primary service provider for the service.
212
    pub struct ServiceDeleteResponse {
213
        /// The service that was deleted.
214
        pub deleted: Service,
215
        /// The new primary service provider for the service, if applicable.
216
        pub new_primary: Option<Service>,
217
    }
218
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc