Skip to main content

passalong_https/
api.rs

1//! The server's JSON documents, as its `openapi.json` defines them. Fields
2//! this client does not know are ignored, as the contract asks. Byte counts
3//! travel as strings, since item sizes are 64-bit.
4
5use serde::de::Error as _;
6use serde::{Deserialize, Deserializer, Serialize};
7use serde_json::value::RawValue;
8
9/// `getViewer`: the API key in use, and the server.
10#[derive(Debug, Clone, Deserialize)]
11#[serde(rename_all = "camelCase")]
12#[non_exhaustive]
13pub struct Viewer {
14    /// The key.
15    pub key: ViewerKey,
16    /// The server.
17    pub server: ServerInfo,
18}
19
20/// The API key, as the server knows it.
21#[derive(Debug, Clone, Deserialize)]
22#[serde(rename_all = "camelCase")]
23#[non_exhaustive]
24pub struct ViewerKey {
25    /// Its public id.
26    pub id: String,
27    /// Its label, such as the device's name.
28    #[serde(default)]
29    pub label: Option<String>,
30    /// What it may do.
31    pub role: Role,
32    /// When it expires, RFC 3339; `None` for never.
33    #[serde(default)]
34    pub expires_at: Option<String>,
35}
36
37/// What an API key may do.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
39#[serde(rename_all = "camelCase")]
40#[non_exhaustive]
41pub enum Role {
42    /// Read and write.
43    ReadWrite,
44    /// Read only.
45    ReadOnly,
46    /// A role this client does not know.
47    #[serde(other)]
48    Unknown,
49}
50
51/// The server's version and limits.
52#[derive(Debug, Clone, Deserialize)]
53#[serde(rename_all = "camelCase")]
54#[non_exhaustive]
55pub struct ServerInfo {
56    /// The server's version.
57    pub version: String,
58    /// The API version it speaks.
59    pub api_version: u32,
60    /// The largest item it takes; `None` for no limit.
61    #[serde(default, deserialize_with = "optional_bytes")]
62    pub max_item_bytes: Option<u64>,
63    /// Where the server's source is.
64    #[serde(default)]
65    pub source_url: Option<String>,
66}
67
68/// `getWorkspace`: the workspace the API key opens.
69#[derive(Debug, Clone, Deserialize)]
70#[serde(rename_all = "camelCase")]
71#[non_exhaustive]
72pub struct Workspace {
73    /// Its name.
74    pub name: String,
75    /// Its quota.
76    #[serde(deserialize_with = "bytes")]
77    pub quota_bytes: u64,
78    /// The bytes its items take.
79    #[serde(deserialize_with = "bytes")]
80    pub used_bytes: u64,
81    /// How many items it holds.
82    pub item_count: u64,
83    /// Its encryption.
84    pub encryption: Encryption,
85}
86
87/// A workspace's encryption, as the server says it is.
88#[derive(Debug, Clone, Deserialize)]
89#[serde(rename_all = "camelCase")]
90#[non_exhaustive]
91pub struct Encryption {
92    /// Plaintext, sealed, or being rewritten.
93    pub state: EncryptionState,
94    /// The key id readers need; while a rewrite is open, the one before it.
95    #[serde(default)]
96    pub key_id: Option<String>,
97    /// The store header, as the client wrote it.
98    #[serde(default)]
99    pub header: Option<Box<RawValue>>,
100    /// The rewrite session, when one is open.
101    #[serde(default)]
102    pub rewrite: Option<RewriteSession>,
103}
104
105/// A workspace's encryption state.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
107#[serde(rename_all = "camelCase")]
108#[non_exhaustive]
109pub enum EncryptionState {
110    /// Not encrypted.
111    Plaintext,
112    /// Encrypted.
113    Sealed,
114    /// A migration or rotation is open.
115    Rewriting,
116    /// A state this client does not know.
117    #[serde(other)]
118    Unknown,
119}
120
121/// An open migration or rotation.
122#[derive(Debug, Clone, Deserialize)]
123#[serde(rename_all = "camelCase")]
124#[non_exhaustive]
125pub struct RewriteSession {
126    /// `migrate` or `rotate`.
127    pub kind: String,
128    /// The public id of the API key that holds the lease.
129    pub holder: String,
130    /// When the lease ends, RFC 3339.
131    pub lease_expires_at: String,
132    /// The new key's id.
133    pub new_key_id: String,
134    /// Ids already staged under the new key.
135    #[serde(default)]
136    pub staged_ids: Vec<String>,
137    /// How many items the workspace held when it began.
138    pub source_items: u64,
139    /// The new header, which the new words unlock (PLAN-00010 D-05).
140    #[serde(default)]
141    pub new_header: Option<Box<RawValue>>,
142}
143
144/// An item's envelope: what the server knows of it. `meta` is the client's
145/// `meta.json`, as it sent it.
146#[derive(Debug, Clone, Deserialize)]
147#[serde(rename_all = "camelCase")]
148#[non_exhaustive]
149pub struct Item {
150    /// The item's id.
151    pub id: String,
152    /// Its `meta.json`, byte for byte.
153    pub meta: Box<RawValue>,
154    /// The bytes its stored content takes.
155    #[serde(deserialize_with = "bytes")]
156    pub stored_bytes: u64,
157    /// When the server received it, RFC 3339.
158    pub received_at: String,
159}
160
161/// `beginUpload`'s answer when the content is stored already, and
162/// `commitUpload`'s.
163#[derive(Debug, Clone, Deserialize)]
164#[non_exhaustive]
165pub struct PutOutcome {
166    /// The stored item.
167    pub item: Item,
168    /// `false` when identical content was stored already.
169    pub created: bool,
170}
171
172/// `beginUpload`'s answer when content is to be sent.
173#[derive(Debug, Clone, Deserialize)]
174#[serde(rename_all = "camelCase")]
175#[non_exhaustive]
176pub struct UploadTicket {
177    /// The upload's id, and its idempotency key.
178    pub upload_id: String,
179    /// When the ticket lapses.
180    pub expires_at: String,
181}
182
183/// `beginUpload`'s request.
184#[derive(Debug, Serialize)]
185#[serde(rename_all = "camelCase")]
186pub struct BeginUpload<'a> {
187    /// The id the client proposes.
188    pub id: &'a str,
189    /// The item's `meta.json`, byte for byte.
190    pub meta: &'a RawValue,
191    /// The stored content's size, as a string.
192    pub size: String,
193    /// The key the client believes the workspace is under; `None` for
194    /// plaintext.
195    pub expected_key_id: Option<String>,
196    /// Whether this stages a rewrite's next generation.
197    pub in_rewrite: bool,
198}
199
200/// `resolveItem`'s answer.
201#[derive(Debug, Clone, Deserialize)]
202#[non_exhaustive]
203pub struct Resolved {
204    /// `resolved`, `ambiguous`, `notFound`, or `invalidPrefix`.
205    pub result: String,
206    /// The item, when resolved.
207    #[serde(default)]
208    pub id: Option<String>,
209    /// The candidates, when ambiguous.
210    #[serde(default)]
211    pub candidates: Vec<String>,
212}
213
214/// `cleanStaging`'s answer.
215#[derive(Debug, Clone, Deserialize)]
216#[non_exhaustive]
217pub struct Cleaned {
218    /// How many staging places were removed.
219    pub removed: usize,
220}
221
222/// A byte count sent as a string of digits.
223fn bytes<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
224    let text = String::deserialize(deserializer)?;
225    text.parse()
226        .map_err(|_| D::Error::custom(format!("`{text}` is not a byte count")))
227}
228
229fn optional_bytes<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u64>, D::Error> {
230    match Option::<String>::deserialize(deserializer)? {
231        Some(text) => text
232            .parse()
233            .map(Some)
234            .map_err(|_| D::Error::custom(format!("`{text}` is not a byte count"))),
235        None => Ok(None),
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242
243    #[test]
244    fn a_viewer_reads_as_the_server_sends_it() {
245        let viewer: Viewer = serde_json::from_str(
246            r#"{"key":{"expiresAt":null,"id":"052a09a4bd92","label":"curl","role":"readWrite"},"server":{"apiVersion":1,"maxItemBytes":null,"sourceUrl":"https://github.com/joelee/passalong-server","version":"0.1.0"}}"#,
247        )
248        .unwrap();
249        assert_eq!(viewer.key.id, "052a09a4bd92");
250        assert_eq!(viewer.key.role, Role::ReadWrite);
251        assert_eq!(viewer.server.max_item_bytes, None);
252        let limited: ServerInfo = serde_json::from_str(
253            r#"{"version":"9","apiVersion":1,"maxItemBytes":"18446744073709551615","later":true}"#,
254        )
255        .unwrap();
256        assert_eq!(limited.max_item_bytes, Some(u64::MAX));
257        assert!(
258            serde_json::from_str::<ServerInfo>(
259                r#"{"version":"9","apiVersion":1,"maxItemBytes":"-1"}"#
260            )
261            .is_err()
262        );
263    }
264
265    #[test]
266    fn a_workspace_keeps_its_header_as_it_was_written() {
267        let workspace: Workspace = serde_json::from_str(
268            r#"{"name":"home","quotaBytes":"21474836480","usedBytes":"5","itemCount":1,"encryption":{"state":"sealed","keyId":"0011223344556677","header":{ "b": 1,  "a": [2] }}}"#,
269        )
270        .unwrap();
271        assert_eq!(workspace.quota_bytes, 21_474_836_480);
272        assert_eq!(workspace.encryption.state, EncryptionState::Sealed);
273        assert_eq!(
274            workspace.encryption.header.unwrap().get(),
275            r#"{ "b": 1,  "a": [2] }"#
276        );
277        let other: Encryption = serde_json::from_str(r#"{"state":"somethingNew"}"#).unwrap();
278        assert_eq!(other.state, EncryptionState::Unknown);
279    }
280}