lockbook-server 26.11.25

Lockbook's server, exposed as a library for testing.
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! The server as a library inside a client's process. It trusts its caller: requests carry no
//! signature, and the account's public key stands in for the one a signature would prove.

use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use db_rs::View;
use lb_rs::io::copy::copy_db;
use lb_rs::io::network::ApiError;
use lb_rs::io::server::{ApiResult, Server};
use lb_rs::model::account::Account;
use lb_rs::model::api::*;
use lb_rs::model::crypto::EncryptedDocument;
use lb_rs::model::file_metadata::DocumentHmac;
use uuid::Uuid;

use crate::billing::Nop;
use crate::billing::app_store_client::AppStoreClient;
use crate::billing::google_play_client::GooglePlayClient;
use crate::billing::stripe_client::StripeClient;
use crate::config::{
    AdminConfig, AppleConfig, BillingConfig, Config, Environment, FeatureFlags, FilesConfig,
    GoogleConfig, IndexDbConf, MetricsConfig, ServerConfig, StripeConfig,
};
use crate::document_service::DocumentService;
use crate::schema::ServerDb;
use crate::utils::get_build_info;
use crate::{RequestContext, ServerError, ServerState};
use lb_rs::io::docs::DocumentStore;
use lb_rs::model::errors::LbResult;

/// A server whose index and documents live in memory, with no billing.
pub type InMemoryServer = ServerState<Nop, Nop, Nop, InMemDocuments>;

impl InMemoryServer {
    /// An empty server that accepts new accounts and has no admins.
    pub fn in_memory() -> Self {
        ServerState::with_documents(InMemDocuments::default())
    }
}

impl<D: DocumentService> ServerState<Nop, Nop, Nop, D> {
    /// [`InMemoryServer::in_memory`] with `documents` as its document store.
    pub fn with_documents(documents: D) -> Self {
        let config = in_process_config();
        let index_db = ServerDb::init(&db_rs::config::Config::in_memory())
            .expect("an in-memory database initializes");
        Self {
            config,
            index_db: Arc::new(tokio::sync::Mutex::new(index_db)),
            stripe_client: Nop {},
            google_play_client: Nop {},
            app_store_client: Nop {},
            document_service: documents,
            discord_client: Default::default(),
            recent_new_account_ips: Default::default(),
            clock: Default::default(),
        }
    }
}

impl<D: DocumentService> ServerState<Nop, Nop, Nop, D> {
    /// A server holding this one's index, its settings and `documents`, sharing nothing with it.
    pub async fn copy_with<E: DocumentService>(
        &self, documents: E,
    ) -> ServerState<Nop, Nop, Nop, E> {
        let index_db =
            copy_db(&mut *self.index_db.lock().await).expect("an in-memory database copies");
        let ips = self.recent_new_account_ips.lock().await.clone();
        ServerState {
            config: self.config.clone(),
            index_db: Arc::new(tokio::sync::Mutex::new(index_db)),
            stripe_client: Nop {},
            google_play_client: Nop {},
            app_store_client: Nop {},
            document_service: documents,
            discord_client: self.discord_client.clone(),
            recent_new_account_ips: Arc::new(tokio::sync::Mutex::new(ips)),
            clock: Arc::new((*self.clock).clone()),
        }
    }
}

/// Every setting a handler reads, chosen for tests: accounts open, no rate limit, no admins.
/// Settings the in-process path never reads are empty.
fn in_process_config() -> Config {
    let none = String::new;
    Config {
        server: ServerConfig {
            env: Environment::Local,
            port: 0,
            max_auth_delay: 0,
            log_path: none(),
            pd_api_key: None,
            discord_webhook_url: None,
            ssl_cert_location: None,
            ssl_private_key_location: None,
            min_core_version: semver::VersionReq::STAR,
        },
        index_db: IndexDbConf { db_location: none(), time_between_compacts: Duration::ZERO },
        files: FilesConfig { path: PathBuf::new() },
        metrics: MetricsConfig {
            addr: ([127, 0, 0, 1], 0).into(),
            time_between_metrics_refresh: Duration::ZERO,
            time_between_metrics: Duration::ZERO,
        },
        billing: BillingConfig {
            millis_between_user_payment_flows: 0,
            time_between_lock_attempts: Duration::ZERO,
            google: GoogleConfig {
                service_account_key: None,
                premium_subscription_product_id: none(),
                premium_subscription_offer_id: none(),
                pubsub_token: none(),
            },
            stripe: StripeConfig {
                stripe_secret: none(),
                signing_secret: none(),
                premium_price_id: none(),
            },
            apple: AppleConfig {
                iap_key: none(),
                iap_key_id: none(),
                asc_public_key: none(),
                issuer_id: none(),
                subscription_product_id: none(),
                asc_shared_secret: none(),
                apple_root_cert: vec![],
                monthly_sub_group_id: none(),
            },
        },
        admin: AdminConfig { admins: HashSet::new() },
        features: FeatureFlags {
            new_accounts: true,
            new_account_rate_limit: false,
            bandwidth_controls: true,
            meta_v2: true,
        },
    }
}

/// Documents held in memory.
#[derive(Clone, Default)]
pub struct InMemDocuments {
    docs: Arc<Mutex<HashMap<(Uuid, DocumentHmac), EncryptedDocument>>>,
}

impl InMemDocuments {
    /// A store holding these documents, sharing nothing with this one.
    pub fn copy(&self) -> Self {
        Self { docs: Arc::new(Mutex::new(self.docs.lock().unwrap().clone())) }
    }
}

impl DocumentStore for InMemDocuments {
    async fn insert(
        &self, id: Uuid, hmac: DocumentHmac, content: &EncryptedDocument,
    ) -> LbResult<()> {
        self.docs
            .lock()
            .unwrap()
            .insert((id, hmac), content.clone());
        Ok(())
    }

    async fn maybe_get(&self, id: Uuid, hmac: DocumentHmac) -> LbResult<Option<EncryptedDocument>> {
        Ok(self.docs.lock().unwrap().get(&(id, hmac)).cloned())
    }

    async fn delete(&self, id: Uuid, hmac: DocumentHmac) -> LbResult<()> {
        self.docs.lock().unwrap().remove(&(id, hmac));
        Ok(())
    }

    fn exists(&self, id: Uuid, hmac: DocumentHmac) -> bool {
        self.docs.lock().unwrap().contains_key(&(id, hmac))
    }
}

impl DocumentService for InMemDocuments {
    fn get_path(&self, id: Uuid, hmac: DocumentHmac) -> PathBuf {
        let hmac = base64::encode_config(hmac, base64::URL_SAFE);
        PathBuf::from(format!("memory/{id}-{hmac}"))
    }
}

fn context<T>(account: &Account, request: T) -> RequestContext<T> {
    RequestContext { request, public_key: account.public_key(), ip: None }
}

fn api_error<E: Debug>(err: ServerError<E>) -> ApiError<E> {
    match err {
        ServerError::ClientError(e) => ApiError::Endpoint(e),
        ServerError::InternalError(e) => {
            tracing::error!("internal: {e}");
            ApiError::InternalError
        }
    }
}

impl<S, A, G, D> Server for ServerState<S, A, G, D>
where
    S: StripeClient,
    A: AppStoreClient,
    G: GooglePlayClient,
    D: DocumentService,
{
    async fn new_account_v2(
        &self, account: &Account, request: NewAccountRequestV2,
    ) -> ApiResult<NewAccountRequestV2> {
        ServerState::new_account_v2(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn new_sub_account(
        &self, account: &Account, request: NewSubAccountRequest,
    ) -> ApiResult<NewSubAccountRequest> {
        ServerState::new_sub_account(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn list_sub_accounts(
        &self, account: &Account, request: ListSubAccountsRequest,
    ) -> ApiResult<ListSubAccountsRequest> {
        ServerState::list_sub_accounts(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn delete_sub_account(
        &self, account: &Account, request: DeleteSubAccountRequest,
    ) -> ApiResult<DeleteSubAccountRequest> {
        ServerState::delete_sub_account(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn change_doc_v2(
        &self, account: &Account, request: ChangeDocRequestV2,
    ) -> ApiResult<ChangeDocRequestV2> {
        ServerState::change_doc_v2(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn upsert_file_metadata_v2(
        &self, account: &Account, request: UpsertRequestV2,
    ) -> ApiResult<UpsertRequestV2> {
        ServerState::upsert_file_metadata_v2(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_document(
        &self, account: &Account, request: GetDocRequest,
    ) -> ApiResult<GetDocRequest> {
        ServerState::get_document(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_public_key(
        &self, account: &Account, request: GetPublicKeyRequest,
    ) -> ApiResult<GetPublicKeyRequest> {
        ServerState::get_public_key(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_username(
        &self, account: &Account, request: GetUsernameRequest,
    ) -> ApiResult<GetUsernameRequest> {
        ServerState::get_username(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_usage(
        &self, account: &Account, request: GetUsageRequest,
    ) -> ApiResult<GetUsageRequest> {
        ServerState::get_usage(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_file_ids(
        &self, account: &Account, request: GetFileIdsRequest,
    ) -> ApiResult<GetFileIdsRequest> {
        ServerState::get_file_ids(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_updates_v2(
        &self, account: &Account, request: GetUpdatesRequestV2,
    ) -> ApiResult<GetUpdatesRequestV2> {
        ServerState::get_updates_v2(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_build_info(
        &self, _: &Account, _: GetBuildInfoRequest,
    ) -> ApiResult<GetBuildInfoRequest> {
        get_build_info().map_err(api_error)
    }

    async fn delete_account(
        &self, account: &Account, request: DeleteAccountRequest,
    ) -> ApiResult<DeleteAccountRequest> {
        ServerState::delete_account(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn stripe_checkout(
        &self, account: &Account, request: StripeCheckoutRequest,
    ) -> ApiResult<StripeCheckoutRequest> {
        ServerState::stripe_checkout(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn stripe_billing_portal(
        &self, account: &Account, request: StripeBillingPortalRequest,
    ) -> ApiResult<StripeBillingPortalRequest> {
        ServerState::stripe_billing_portal(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn upgrade_account_google_play(
        &self, account: &Account, request: UpgradeAccountGooglePlayRequest,
    ) -> ApiResult<UpgradeAccountGooglePlayRequest> {
        ServerState::upgrade_account_google_play(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn upgrade_account_app_store(
        &self, account: &Account, request: UpgradeAccountAppStoreRequest,
    ) -> ApiResult<UpgradeAccountAppStoreRequest> {
        ServerState::upgrade_account_app_store(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn cancel_subscription(
        &self, account: &Account, request: CancelSubscriptionRequest,
    ) -> ApiResult<CancelSubscriptionRequest> {
        ServerState::cancel_subscription(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_subscription_info(
        &self, account: &Account, request: GetSubscriptionInfoRequest,
    ) -> ApiResult<GetSubscriptionInfoRequest> {
        ServerState::get_subscription_info(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn get_subscription_info_v2(
        &self, account: &Account, request: GetSubscriptionInfoRequestV2,
    ) -> ApiResult<GetSubscriptionInfoRequestV2> {
        ServerState::get_subscription_info_v2(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn upsert_debug_info(
        &self, account: &Account, request: UpsertDebugInfoRequest,
    ) -> ApiResult<UpsertDebugInfoRequest> {
        ServerState::upsert_debug_info(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_disappear_account(
        &self, account: &Account, request: AdminDisappearAccountRequest,
    ) -> ApiResult<AdminDisappearAccountRequest> {
        ServerState::admin_disappear_account(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_disappear_file(
        &self, account: &Account, request: AdminDisappearFileRequest,
    ) -> ApiResult<AdminDisappearFileRequest> {
        ServerState::admin_disappear_file(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_validate_account(
        &self, account: &Account, request: AdminValidateAccountRequest,
    ) -> ApiResult<AdminValidateAccountRequest> {
        ServerState::admin_validate_account(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_validate_server(
        &self, account: &Account, request: AdminValidateServerRequest,
    ) -> ApiResult<AdminValidateServerRequest> {
        ServerState::admin_validate_server(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_list_users(
        &self, account: &Account, request: AdminListUsersRequest,
    ) -> ApiResult<AdminListUsersRequest> {
        ServerState::admin_list_users(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_get_account_info(
        &self, account: &Account, request: AdminGetAccountInfoRequest,
    ) -> ApiResult<AdminGetAccountInfoRequest> {
        ServerState::admin_get_account_info(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_file_info(
        &self, account: &Account, request: AdminFileInfoRequest,
    ) -> ApiResult<AdminFileInfoRequest> {
        ServerState::admin_file_info(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_set_user_tier(
        &self, account: &Account, request: AdminSetUserTierRequest,
    ) -> ApiResult<AdminSetUserTierRequest> {
        ServerState::admin_set_user_tier(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_sync_stripe(
        &self, account: &Account, request: AdminSyncStripeRequest,
    ) -> ApiResult<AdminSyncStripeRequest> {
        ServerState::admin_sync_stripe(self, context(account, request))
            .await
            .map_err(api_error)
    }

    async fn admin_rebuild_index(
        &self, account: &Account, request: AdminRebuildIndexRequest,
    ) -> ApiResult<AdminRebuildIndexRequest> {
        ServerState::admin_rebuild_index(self, context(account, request))
            .await
            .map_err(api_error)
    }
}