mycelium-api 8.3.1-rc.4

Provide API ports to the mycelium project.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use crate::dtos::{MyceliumProfileData, TenantData};

use actix_web::{delete, post, web, HttpRequest, HttpResponse, Responder};
use chrono::Utc;
use myc_core::{
    domain::entities::{
        AccountDeletion, AccountFetching, AccountUpdating, TelegramConfig,
        TenantFetching,
    },
    models::AccountLifeCycle,
    use_cases::gateway::telegram::{
        link_telegram_identity, login_via_telegram, unlink_telegram_identity,
    },
};
use myc_diesel::repositories::SqlAppModule;
use myc_http_tools::{
    telegram::{
        types::{BotToken, InitData, WebhookSecret},
        verify_init_data, verify_webhook_secret,
    },
    utils::HttpJsonResponse,
    wrappers::default_response_to_http_response::handle_mapped_error,
};
use myc_svc::repositories::TelegramConfigSvcRepo;
use mycelium_base::entities::FetchResponseKind;
use secrecy::SecretString;
use serde::Serialize;
use shaku::HasComponent;
use tracing::warn;
use uuid::Uuid;

// ? ---------------------------------------------------------------------------
// ? Configure application
// ? ---------------------------------------------------------------------------

pub fn configure(config: &mut web::ServiceConfig) {
    config
        .service(link_telegram_url)
        .service(unlink_telegram_url)
        .service(login_via_telegram_url)
        .service(webhook_url);
}

// ? ---------------------------------------------------------------------------
// ? Define API structs
// ? ---------------------------------------------------------------------------

#[derive(serde::Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct TelegramInitDataBody {
    init_data: String,
}

#[derive(Serialize, utoipa::ToResponse, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct TelegramLoginResponse {
    connection_string: String,
    expires_at: chrono::DateTime<chrono::Local>,
}

// ? ---------------------------------------------------------------------------
// ? Define API paths
// ? ---------------------------------------------------------------------------

/// Link Telegram identity
///
/// Verifies the Telegram Mini App initData HMAC and stores the Telegram user
/// identifier in the authenticated Mycelium account's metadata. Requires a
/// valid connection-string or JWT in the request.
///
/// **Cross-tenant constraint**: The authenticated account (`x-mycelium-profile`)
/// must be a guest or subscriber of the tenant supplied in
/// `x-mycelium-tenant-id`. If it is not, the link will be stored but
/// `POST /auth/telegram/login/{tenant_id}` will return 404 for that account
/// because the tenant-scoped lookup will find no matching guest record. This
/// constraint is enforced by the `login_via_telegram` use-case rather than
/// here; callers must ensure the account belongs to the target tenant.
///
#[utoipa::path(
    post,
    path = "/auth/telegram/link",
    operation_id = "link_telegram_identity",
    request_body = TelegramInitDataBody,
    responses(
        (
            status = 204,
            description = "Telegram identity linked successfully.",
        ),
        (
            status = 401,
            description = "Unauthorized.",
            body = HttpJsonResponse,
        ),
        (
            status = 409,
            description = "Conflict — already linked or Telegram ID in use.",
            body = HttpJsonResponse,
        ),
        (
            status = 422,
            description = "Telegram not configured for this tenant.",
            body = HttpJsonResponse,
        ),
        (
            status = 500,
            description = "Unknown internal server error.",
            body = HttpJsonResponse,
        ),
    ),
)]
#[post("/link")]
pub async fn link_telegram_url(
    profile: MyceliumProfileData,
    tenant: TenantData,
    body: web::Json<TelegramInitDataBody>,
    life_cycle_settings: web::Data<AccountLifeCycle>,
    sql_app_module: web::Data<SqlAppModule>,
) -> impl Responder {
    let tenant_id = *tenant.tenant_id();

    let tenant_record = match fetch_tenant(tenant_id, &sql_app_module).await {
        Ok(t) => t,
        Err(resp) => return resp,
    };

    let meta = match tenant_record.meta {
        Some(m) => m,
        None => {
            return HttpResponse::UnprocessableEntity().json(
                HttpJsonResponse::new_message(
                    "telegram_not_configured_for_tenant",
                ),
            )
        }
    };

    let config_repo = match TelegramConfigSvcRepo::from_tenant_meta(
        &meta,
        tenant_id,
        life_cycle_settings.get_ref().clone(),
        &*sql_app_module.resolve_ref(),
    )
    .await
    {
        Ok(r) => r,
        Err(err) => {
            warn!("telegram config missing: {:?}", err);
            return HttpResponse::UnprocessableEntity().json(
                HttpJsonResponse::new_message(
                    "telegram_not_configured_for_tenant",
                ),
            );
        }
    };

    let bot_token_str: String = match config_repo.get_bot_token(tenant_id).await
    {
        Ok(t) => t,
        Err(err) => {
            warn!("failed to resolve bot token: {:?}", err);
            return HttpResponse::InternalServerError().json(
                HttpJsonResponse::new_message("failed_to_resolve_bot_token"),
            );
        }
    };

    let bot_token = BotToken(SecretString::new(bot_token_str.into()));

    let telegram_user = match verify_init_data(
        &InitData(body.init_data.clone()),
        &bot_token,
        Utc::now(),
    ) {
        Ok(u) => u,
        Err(err) => {
            warn!("telegram initData verification failed: {:?}", err);
            return HttpResponse::Unauthorized().json(
                HttpJsonResponse::new_message("invalid_telegram_init_data"),
            );
        }
    };

    match link_telegram_identity(
        profile.acc_id,
        telegram_user,
        Box::new(&*sql_app_module.resolve_ref() as &dyn AccountFetching),
        Box::new(&*sql_app_module.resolve_ref() as &dyn AccountUpdating),
    )
    .await
    {
        Ok(_) => HttpResponse::NoContent().finish(),
        Err(err) => handle_mapped_error(err),
    }
}

/// Unlink Telegram identity
///
/// Removes the Telegram identifier from the authenticated Mycelium account's
/// metadata.
///
#[utoipa::path(
    delete,
    path = "/auth/telegram/link",
    operation_id = "unlink_telegram_identity",
    responses(
        (
            status = 204,
            description = "Telegram identity unlinked successfully.",
        ),
        (
            status = 401,
            description = "Unauthorized.",
            body = HttpJsonResponse,
        ),
        (
            status = 404,
            description = "Telegram identity not linked.",
            body = HttpJsonResponse,
        ),
        (
            status = 500,
            description = "Unknown internal server error.",
            body = HttpJsonResponse,
        ),
    ),
)]
#[delete("/link")]
pub async fn unlink_telegram_url(
    profile: MyceliumProfileData,
    sql_app_module: web::Data<SqlAppModule>,
) -> impl Responder {
    match unlink_telegram_identity(
        profile.acc_id,
        Box::new(&*sql_app_module.resolve_ref() as &dyn AccountFetching),
        Box::new(&*sql_app_module.resolve_ref() as &dyn AccountDeletion),
    )
    .await
    {
        Ok(_) => HttpResponse::NoContent().finish(),
        Err(err) => handle_mapped_error(err),
    }
}

/// Login via Telegram
///
/// Verifies Telegram Mini App initData for the given tenant, resolves the
/// linked Mycelium account, and returns a connection string for subsequent
/// authenticated calls.
///
#[utoipa::path(
    post,
    path = "/auth/telegram/login/{tenant_id}",
    operation_id = "login_via_telegram",
    params(
        (
            "tenant_id" = Uuid,
            Path,
            description = "Tenant UUID that owns this Telegram bot.",
        )
    ),
    request_body = TelegramInitDataBody,
    responses(
        (
            status = 200,
            description = "Login successful — connection string issued.",
            body = TelegramLoginResponse,
        ),
        (
            status = 401,
            description = "Unauthorized — invalid or expired initData.",
            body = HttpJsonResponse,
        ),
        (
            status = 404,
            description = "Telegram ID not linked to any account in this tenant.",
            body = HttpJsonResponse,
        ),
        (
            status = 422,
            description = "Telegram not configured for this tenant.",
            body = HttpJsonResponse,
        ),
        (
            status = 500,
            description = "Unknown internal server error.",
            body = HttpJsonResponse,
        ),
    ),
    security(()),
)]
#[post("/login/{tenant_id}")]
pub async fn login_via_telegram_url(
    tenant_id: web::Path<Uuid>,
    body: web::Json<TelegramInitDataBody>,
    life_cycle_settings: web::Data<AccountLifeCycle>,
    sql_app_module: web::Data<SqlAppModule>,
) -> impl Responder {
    let tenant_id = tenant_id.into_inner();

    let tenant_record = match fetch_tenant(tenant_id, &sql_app_module).await {
        Ok(t) => t,
        Err(resp) => return resp,
    };

    let meta = match tenant_record.meta {
        Some(m) => m,
        None => {
            return HttpResponse::UnprocessableEntity().json(
                HttpJsonResponse::new_message(
                    "telegram_not_configured_for_tenant",
                ),
            )
        }
    };

    let config_repo = match TelegramConfigSvcRepo::from_tenant_meta(
        &meta,
        tenant_id,
        life_cycle_settings.get_ref().clone(),
        &*sql_app_module.resolve_ref(),
    )
    .await
    {
        Ok(r) => r,
        Err(err) => {
            warn!("telegram config missing: {:?}", err);
            return HttpResponse::UnprocessableEntity().json(
                HttpJsonResponse::new_message(
                    "telegram_not_configured_for_tenant",
                ),
            );
        }
    };

    let bot_token_str: String = match config_repo.get_bot_token(tenant_id).await
    {
        Ok(t) => t,
        Err(err) => {
            warn!("failed to resolve bot token: {:?}", err);
            return HttpResponse::InternalServerError().json(
                HttpJsonResponse::new_message("failed_to_resolve_bot_token"),
            );
        }
    };

    let bot_token = BotToken(SecretString::new(bot_token_str.into()));

    let telegram_user = match verify_init_data(
        &InitData(body.init_data.clone()),
        &bot_token,
        Utc::now(),
    ) {
        Ok(u) => u,
        Err(err) => {
            warn!("telegram initData verification failed: {:?}", err);
            return HttpResponse::Unauthorized().json(
                HttpJsonResponse::new_message("invalid_telegram_init_data"),
            );
        }
    };

    match login_via_telegram(
        tenant_id,
        telegram_user,
        Box::new(&*sql_app_module.resolve_ref() as &dyn AccountFetching),
        life_cycle_settings.get_ref().to_owned(),
    )
    .await
    {
        Ok((connection_string, expires_at)) => {
            HttpResponse::Ok().json(TelegramLoginResponse {
                connection_string: connection_string.to_string(),
                expires_at,
            })
        }
        Err(err) => handle_mapped_error(err),
    }
}

/// Telegram webhook
///
/// Receives Telegram update callbacks for the given tenant. Verifies the
/// `X-Telegram-Bot-Api-Secret-Token` header before accepting. Returns `200 OK`
/// immediately — Telegram retries on any other status code.
///
/// The update payload is accepted and validated here; forwarding to downstream
/// handlers uses Telegram update auth (`identity_source: Telegram` on the route).
///
#[utoipa::path(
    post,
    path = "/auth/telegram/webhook/{tenant_id}",
    operation_id = "telegram_webhook",
    params(
        (
            "tenant_id" = Uuid,
            Path,
            description = "Tenant UUID that owns this Telegram bot.",
        )
    ),
    request_body = serde_json::Value,
    responses(
        (
            status = 200,
            description = "Update accepted.",
        ),
        (
            status = 401,
            description = "Invalid webhook secret.",
            body = HttpJsonResponse,
        ),
        (
            status = 422,
            description = "Telegram not configured for this tenant.",
            body = HttpJsonResponse,
        ),
        (
            status = 500,
            description = "Unknown internal server error.",
            body = HttpJsonResponse,
        ),
    ),
    security(()),
)]
#[post("/webhook/{tenant_id}")]
pub async fn webhook_url(
    req: HttpRequest,
    tenant_id: web::Path<Uuid>,
    _body: web::Json<serde_json::Value>,
    life_cycle_settings: web::Data<AccountLifeCycle>,
    sql_app_module: web::Data<SqlAppModule>,
) -> impl Responder {
    let tenant_id = tenant_id.into_inner();

    let tenant_record = match fetch_tenant(tenant_id, &sql_app_module).await {
        Ok(t) => t,
        Err(resp) => return resp,
    };

    let meta = match tenant_record.meta {
        Some(m) => m,
        None => {
            return HttpResponse::UnprocessableEntity().json(
                HttpJsonResponse::new_message(
                    "telegram_not_configured_for_tenant",
                ),
            )
        }
    };

    let config_repo = match TelegramConfigSvcRepo::from_tenant_meta(
        &meta,
        tenant_id,
        life_cycle_settings.get_ref().clone(),
        &*sql_app_module.resolve_ref(),
    )
    .await
    {
        Ok(r) => r,
        Err(err) => {
            warn!("telegram config missing: {:?}", err);
            return HttpResponse::UnprocessableEntity().json(
                HttpJsonResponse::new_message(
                    "telegram_not_configured_for_tenant",
                ),
            );
        }
    };

    let webhook_secret_str: String =
        match config_repo.get_webhook_secret(tenant_id).await {
            Ok(s) => s,
            Err(err) => {
                warn!("failed to resolve webhook secret: {:?}", err);
                return HttpResponse::InternalServerError().json(
                    HttpJsonResponse::new_message(
                        "failed_to_resolve_webhook_secret",
                    ),
                );
            }
        };

    let expected_secret =
        WebhookSecret(SecretString::new(webhook_secret_str.into()));

    let header_value = req
        .headers()
        .get("X-Telegram-Bot-Api-Secret-Token")
        .and_then(|v| v.to_str().ok());

    if !verify_webhook_secret(header_value, &expected_secret) {
        return HttpResponse::Unauthorized()
            .json(HttpJsonResponse::new_message("invalid_webhook_secret"));
    }

    tracing::info!(
        tenant_id = %tenant_id,
        "telegram_webhook_received"
    );

    HttpResponse::Ok().finish()
}

// ? ---------------------------------------------------------------------------
// ? Private helpers
// ? ---------------------------------------------------------------------------

async fn fetch_tenant(
    tenant_id: Uuid,
    sql_app_module: &SqlAppModule,
) -> Result<myc_core::domain::dtos::tenant::Tenant, HttpResponse> {
    let repo: &dyn TenantFetching = sql_app_module.resolve_ref();

    match repo.get_tenant_public_by_id(tenant_id).await {
        Ok(FetchResponseKind::Found(t)) => Ok(t),
        Ok(FetchResponseKind::NotFound(_)) => Err(HttpResponse::NotFound()
            .json(HttpJsonResponse::new_message("tenant_not_found"))),
        Err(err) => {
            warn!("failed to fetch tenant: {:?}", err);
            Err(HttpResponse::InternalServerError()
                .json(HttpJsonResponse::new_message("failed_to_fetch_tenant")))
        }
    }
}