mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(server): add calendar sync service, GraphQL resolvers, and webhook REST routes
This commit is contained in:
1 parent
3304aaa4cf
commit
55adbc6080
13 files changed
+5344
-33
No files matched your search
@@ -1093,6 +1093,27 @@ where
|
||||
)
|
||||
.await;
|
||||
|
||||
let cal_svc = built.state.calendar.clone();
|
||||
server_worker::spawn_locked_periodic_task(
|
||||
&built.supervisor,
|
||||
built.session_mutex.clone(),
|
||||
"calendar:sync-poll",
|
||||
"calendar-sync",
|
||||
Duration::from_secs(60),
|
||||
120,
|
||||
move |lease_cancel| {
|
||||
let svc = cal_svc.clone();
|
||||
async move {
|
||||
if !lease_cancel.is_cancelled()
|
||||
&& let Err(err) = server_domain::calendar::sync::poll_due_calendar_subscriptions(&svc).await
|
||||
{
|
||||
tracing::warn!(error = %err, "calendar sync poll tick failed");
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
if built.state.config.load().deployment_mode == DeploymentMode::Selfhosted {
|
||||
let startup_licenses = built.state.licenses.clone();
|
||||
built
|
||||
|
||||
@@ -12,6 +12,7 @@ argon2.workspace = true
|
||||
async-trait.workspace = true
|
||||
base64.workspace = true
|
||||
chrono.workspace = true
|
||||
futures-util.workspace = true
|
||||
hex.workspace = true
|
||||
hickory-resolver.workspace = true
|
||||
hkdf.workspace = true
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,957 @@
|
||||
//! Calendar subscription synchronization and periodic polling.
|
||||
//!
|
||||
//! Enforces strict separation between short PostgreSQL transactions and
|
||||
//! external provider HTTP requests so `PgPool` connections are never held
|
||||
//! across network I/O (verified with `max_connections = 1`).
|
||||
use super::caldav::CaldavCalendarProvider;
|
||||
use super::crypto::decrypt_token;
|
||||
use super::google::GoogleCalendarProvider;
|
||||
use super::ical::{parse_js_iso_datetime, try_offset_at_utc_guess_ymd_f64};
|
||||
use super::{
|
||||
CalendarAccountRecord, CalendarError, CalendarProviderEvent, CalendarProviderEventTime,
|
||||
CalendarProviderListEventsResult, CalendarProviderName, CalendarService, CalendarSubscriptionRecord, TokenPatch,
|
||||
internal_err, truncate_calendar_error,
|
||||
};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use futures_util::{FutureExt as _, StreamExt as _};
|
||||
use server_db::WorkloadTier;
|
||||
use sqlx::Row;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use uuid::Uuid;
|
||||
const TOKEN_REFRESH_SKEW_SECS: i64 = 60;
|
||||
const DEFAULT_PAST_DAYS: i64 = 90;
|
||||
const DEFAULT_FUTURE_DAYS: i64 = 180;
|
||||
const SYNC_CLAIM_SECS: i64 = 30 * 60;
|
||||
const SYNC_FAILURE_BACKOFF_BASE_SECS: i64 = 5 * 60;
|
||||
const SYNC_FAILURE_BACKOFF_MAX_SECS: i64 = 6 * 3600;
|
||||
const CHANNEL_RENEW_RETRY_SECS: i64 = 15 * 60;
|
||||
pub const CALENDAR_SYNC_CONCURRENCY: usize = 8;
|
||||
pub const CALENDAR_POLL_BATCHES: usize = 25;
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SyncSubscriptionOptions {
|
||||
pub force_full: bool,
|
||||
pub claimed_until: Option<DateTime<Utc>>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ClaimedSubscription {
|
||||
pub id: String,
|
||||
pub claimed_until: DateTime<Utc>,
|
||||
}
|
||||
async fn run_sync_batch(service: &CalendarService, items: Vec<(String, Option<DateTime<Utc>>)>) {
|
||||
futures_util::stream::iter(items)
|
||||
.map(|(id, claimed_until)| {
|
||||
let svc = service.clone();
|
||||
async move {
|
||||
let opts = SyncSubscriptionOptions {
|
||||
force_full: false,
|
||||
claimed_until,
|
||||
};
|
||||
let _ = AssertUnwindSafe(sync_subscription(&svc, &id, opts))
|
||||
.catch_unwind()
|
||||
.await;
|
||||
}
|
||||
})
|
||||
.buffer_unordered(CALENDAR_SYNC_CONCURRENCY)
|
||||
.collect::<Vec<()>>()
|
||||
.await;
|
||||
}
|
||||
pub async fn poll_due_calendar_subscriptions(service: &CalendarService) -> Result<usize, CalendarError> {
|
||||
let mut total = 0usize;
|
||||
for _ in 0..CALENDAR_POLL_BATCHES {
|
||||
let claimed = claim_due_for_sync(service, CALENDAR_SYNC_CONCURRENCY as i64, None).await?;
|
||||
let count = claimed.len();
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
run_sync_batch(
|
||||
service,
|
||||
claimed.into_iter().map(|i| (i.id, Some(i.claimed_until))).collect(),
|
||||
)
|
||||
.await;
|
||||
total += count;
|
||||
if count < CALENDAR_SYNC_CONCURRENCY {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
pub async fn sync_due_subscription_ids(service: &CalendarService, ids: &[String]) -> Result<(), CalendarError> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut tx = service
|
||||
.begin_tx(WorkloadTier::InteractiveWrite, "enqueue due workspace calendar sync")
|
||||
.await?;
|
||||
sqlx::query(
|
||||
r#"UPDATE calendar_subscriptions
|
||||
SET next_sync_at = LEAST(COALESCE(next_sync_at, clock_timestamp()), clock_timestamp()),
|
||||
updated_at = clock_timestamp()
|
||||
WHERE id = ANY($1) AND enabled = true AND next_sync_at <= clock_timestamp()"#,
|
||||
)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("enqueue due workspace calendar sync"))?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(internal_err("commit enqueue due workspace calendar sync"))?;
|
||||
run_sync_batch(service, ids.iter().cloned().map(|id| (id, None)).collect()).await;
|
||||
Ok(())
|
||||
}
|
||||
/// Claims up to `limit` due subscriptions using PostgreSQL `clock_timestamp()`
|
||||
/// and `FOR UPDATE SKIP LOCKED` in a short transaction, then releases the DB connection.
|
||||
pub async fn claim_due_for_sync(
|
||||
service: &CalendarService,
|
||||
limit: i64,
|
||||
subscription_id: Option<&str>,
|
||||
) -> Result<Vec<ClaimedSubscription>, CalendarError> {
|
||||
let mut tx = service
|
||||
.begin_tx(WorkloadTier::InteractiveWrite, "begin claim_due_for_sync")
|
||||
.await?;
|
||||
let rows = sqlx::query(
|
||||
r#"WITH now_ts AS (SELECT clock_timestamp() AS t),
|
||||
candidates AS (
|
||||
SELECT subscription.id
|
||||
FROM calendar_subscriptions subscription
|
||||
JOIN calendar_accounts account ON account.id = subscription.account_id
|
||||
CROSS JOIN now_ts
|
||||
WHERE subscription.enabled
|
||||
AND subscription.next_sync_at <= now_ts.t
|
||||
AND ($1::text IS NULL OR subscription.id = $1)
|
||||
AND (subscription.sync_claimed_until IS NULL OR subscription.sync_claimed_until <= now_ts.t)
|
||||
AND account.status = 'active'
|
||||
ORDER BY subscription.next_sync_at ASC, subscription.id ASC
|
||||
FOR UPDATE OF subscription SKIP LOCKED
|
||||
LIMIT $2
|
||||
)
|
||||
UPDATE calendar_subscriptions subscription
|
||||
SET next_sync_at = now_ts.t + make_interval(secs => $3),
|
||||
sync_claimed_until = now_ts.t + make_interval(secs => $3),
|
||||
updated_at = now_ts.t
|
||||
FROM candidates, now_ts
|
||||
WHERE subscription.id = candidates.id
|
||||
RETURNING subscription.id, subscription.sync_claimed_until"#,
|
||||
)
|
||||
.bind(subscription_id)
|
||||
.bind(limit)
|
||||
.bind(SYNC_CLAIM_SECS as f64)
|
||||
.fetch_all(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("claim_due_for_sync query"))?;
|
||||
tx.commit().await.map_err(internal_err("commit claim_due_for_sync"))?;
|
||||
Ok(
|
||||
rows
|
||||
.into_iter()
|
||||
.map(|r| ClaimedSubscription {
|
||||
id: r.get("id"),
|
||||
claimed_until: r.get("sync_claimed_until"),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
async fn db_clock_timestamp(service: &CalendarService) -> Result<DateTime<Utc>, CalendarError> {
|
||||
let mut conn = service.read_conn("acquire db clock_timestamp").await?;
|
||||
sqlx::query_scalar("SELECT clock_timestamp()")
|
||||
.fetch_one(&mut *conn)
|
||||
.await
|
||||
.map_err(internal_err("read clock_timestamp"))
|
||||
}
|
||||
/// Synchronizes a single subscription with its upstream provider.
|
||||
/// Releases all PostgreSQL connections before every external HTTP request.
|
||||
pub async fn sync_subscription(
|
||||
service: &CalendarService,
|
||||
subscription_id: &str,
|
||||
options: SyncSubscriptionOptions,
|
||||
) -> Result<(), CalendarError> {
|
||||
let claimed_until = match options.claimed_until {
|
||||
Some(c) => c,
|
||||
None => match claim_due_for_sync(service, 1, Some(subscription_id))
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
{
|
||||
Some(c) => c.claimed_until,
|
||||
None => return Ok(()),
|
||||
},
|
||||
};
|
||||
let db_now = db_clock_timestamp(service).await?;
|
||||
let Some((subscription, account)) = service.load_subscription_with_account(subscription_id).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if !subscription.enabled
|
||||
|| subscription.sync_claimed_until != Some(claimed_until)
|
||||
|| claimed_until <= db_now
|
||||
|| account.status != "active"
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let configs = service.load_configs().await?;
|
||||
let provider = account.provider;
|
||||
// Step 1: Ensure a fresh access token (external HTTP runs with zero DB conn held).
|
||||
let access_token = match ensure_access_token(
|
||||
service,
|
||||
&account,
|
||||
&configs.google,
|
||||
Some((&subscription.id, claimed_until)),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(token)) => token,
|
||||
Ok(None) => return Ok(()),
|
||||
Err(err) => {
|
||||
handle_sync_failure(service, &subscription, &account, claimed_until, &err, None, false).await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let time_min = (db_now - Duration::days(DEFAULT_PAST_DAYS)).to_rfc3339();
|
||||
let time_max = (db_now + Duration::days(DEFAULT_FUTURE_DAYS)).to_rfc3339();
|
||||
let use_sync_token = subscription.sync_token.is_some() && !options.force_full;
|
||||
// Step 2: Fetch events from upstream provider (zero DB conn held).
|
||||
let fetch_res = fetch_events_from_provider(
|
||||
provider,
|
||||
&configs,
|
||||
&account,
|
||||
&access_token,
|
||||
&subscription.external_calendar_id,
|
||||
if use_sync_token {
|
||||
subscription.sync_token.as_deref()
|
||||
} else {
|
||||
None
|
||||
},
|
||||
if use_sync_token { None } else { Some(&time_min) },
|
||||
if use_sync_token { None } else { Some(&time_max) },
|
||||
)
|
||||
.await;
|
||||
let events_result = match fetch_res {
|
||||
Ok(res) => res,
|
||||
Err(CalendarError::SyncTokenInvalid(_)) => {
|
||||
let reset = reset_sync_token_under_claim(service, &subscription.id, claimed_until).await?;
|
||||
if !reset {
|
||||
return Ok(());
|
||||
}
|
||||
match fetch_events_from_provider(
|
||||
provider,
|
||||
&configs,
|
||||
&account,
|
||||
&access_token,
|
||||
&subscription.external_calendar_id,
|
||||
None,
|
||||
Some(&time_min),
|
||||
Some(&time_max),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(res) => res,
|
||||
Err(retry_err) => {
|
||||
handle_sync_failure(
|
||||
service,
|
||||
&subscription,
|
||||
&account,
|
||||
claimed_until,
|
||||
&retry_err,
|
||||
Some(&access_token),
|
||||
true,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
handle_sync_failure(
|
||||
service,
|
||||
&subscription,
|
||||
&account,
|
||||
claimed_until,
|
||||
&err,
|
||||
Some(&access_token),
|
||||
true,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
// Step 3: Persist events and next_sync_token inside a LongQuery transaction.
|
||||
let saved = match persist_events_under_claim(
|
||||
service,
|
||||
&subscription.id,
|
||||
claimed_until,
|
||||
subscription.timezone.as_deref(),
|
||||
&events_result,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(saved) => saved,
|
||||
Err(err) => {
|
||||
handle_sync_failure(
|
||||
service,
|
||||
&subscription,
|
||||
&account,
|
||||
claimed_until,
|
||||
&err,
|
||||
Some(&access_token),
|
||||
true,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
if !saved {
|
||||
return Ok(());
|
||||
}
|
||||
let synced_at = db_clock_timestamp(service).await?;
|
||||
let mut next_sync_at = synced_at + Duration::minutes(i64::from(account.refresh_interval_minutes.max(1)));
|
||||
// Step 4: Ensure Google webhook channel if configured (HTTP outside DB tx).
|
||||
if provider == CalendarProviderName::Google
|
||||
&& let Some(webhook_addr) = service.webhook_address_from_config(&configs.google, "google")
|
||||
&& let Err(_err) = ensure_google_webhook_channel(
|
||||
service,
|
||||
&configs.google,
|
||||
&subscription,
|
||||
&access_token,
|
||||
&webhook_addr,
|
||||
claimed_until,
|
||||
)
|
||||
.await
|
||||
{
|
||||
let retry_at = db_clock_timestamp(service).await? + Duration::seconds(CHANNEL_RENEW_RETRY_SECS);
|
||||
if retry_at < next_sync_at {
|
||||
next_sync_at = retry_at;
|
||||
}
|
||||
}
|
||||
complete_sync(
|
||||
service,
|
||||
&subscription.id,
|
||||
claimed_until,
|
||||
Some(synced_at),
|
||||
next_sync_at,
|
||||
0,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) async fn ensure_access_token(
|
||||
service: &CalendarService,
|
||||
account: &CalendarAccountRecord,
|
||||
google_cfg: &super::google::CalendarGoogleConfig,
|
||||
claim: Option<(&str, DateTime<Utc>)>,
|
||||
) -> Result<Option<String>, CalendarError> {
|
||||
let access_token = match account.access_token_encrypted.as_deref() {
|
||||
Some(enc) => Some(decrypt_token(service.private_key(), enc).map_err(CalendarError::Domain)?),
|
||||
None => None,
|
||||
};
|
||||
let refresh_token = match account.refresh_token_encrypted.as_deref() {
|
||||
Some(enc) => Some(decrypt_token(service.private_key(), enc).map_err(CalendarError::Domain)?),
|
||||
None => None,
|
||||
};
|
||||
if let Some(ref token) = access_token
|
||||
&& account
|
||||
.expires_at
|
||||
.is_some_and(|exp| exp > Utc::now() + Duration::seconds(TOKEN_REFRESH_SKEW_SECS))
|
||||
{
|
||||
return Ok(Some(token.clone()));
|
||||
}
|
||||
let Some(refresh) = refresh_token else {
|
||||
return Ok(access_token);
|
||||
};
|
||||
if account.provider != CalendarProviderName::Google {
|
||||
return Ok(access_token);
|
||||
}
|
||||
let provider = GoogleCalendarProvider::new(google_cfg.clone());
|
||||
let refreshed = provider.refresh_tokens(&refresh).await?;
|
||||
let saved = if let Some((sub_id, claimed_until)) = claim {
|
||||
update_tokens_under_claim(
|
||||
service,
|
||||
sub_id,
|
||||
claimed_until,
|
||||
&account.id,
|
||||
&refreshed.access_token,
|
||||
refreshed.refresh_token.as_deref().unwrap_or(&refresh),
|
||||
refreshed.expires_at,
|
||||
refreshed.scope.as_deref(),
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
service
|
||||
.update_account_tokens(
|
||||
&account.id,
|
||||
TokenPatch::Set(refreshed.access_token.clone()),
|
||||
TokenPatch::Set(refreshed.refresh_token.unwrap_or(refresh)),
|
||||
Some(refreshed.expires_at),
|
||||
Some(refreshed.scope),
|
||||
Some("active".to_owned()),
|
||||
Some(None),
|
||||
)
|
||||
.await?;
|
||||
true
|
||||
};
|
||||
if !saved {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(refreshed.access_token))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn fetch_events_from_provider(
|
||||
provider: CalendarProviderName,
|
||||
configs: &super::EffectiveCalendarConfigs,
|
||||
account: &CalendarAccountRecord,
|
||||
access_token: &str,
|
||||
calendar_id: &str,
|
||||
sync_token: Option<&str>,
|
||||
time_min: Option<&str>,
|
||||
time_max: Option<&str>,
|
||||
) -> Result<CalendarProviderListEventsResult, CalendarError> {
|
||||
match provider {
|
||||
CalendarProviderName::Google => {
|
||||
let g = GoogleCalendarProvider::new(configs.google.clone());
|
||||
g.list_events(access_token, calendar_id, sync_token, time_min, time_max)
|
||||
.await
|
||||
}
|
||||
CalendarProviderName::CalDAV => {
|
||||
let c = CaldavCalendarProvider::new(configs.caldav.clone());
|
||||
c.list_events(account, access_token, calendar_id, sync_token, time_min, time_max)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn reset_sync_token_under_claim(
|
||||
service: &CalendarService,
|
||||
subscription_id: &str,
|
||||
claimed_until: DateTime<Utc>,
|
||||
) -> Result<bool, CalendarError> {
|
||||
let mut tx = service
|
||||
.begin_tx(WorkloadTier::InteractiveWrite, "begin reset sync_token")
|
||||
.await?;
|
||||
if !lock_and_verify_claim(tx.tx_mut(), subscription_id, claimed_until).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
sqlx::query("UPDATE calendar_subscriptions SET sync_token = NULL, updated_at = clock_timestamp() WHERE id = $1")
|
||||
.bind(subscription_id)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("reset sync_token"))?;
|
||||
tx.commit().await.map_err(internal_err("commit reset sync_token"))?;
|
||||
Ok(true)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn update_tokens_under_claim(
|
||||
service: &CalendarService,
|
||||
subscription_id: &str,
|
||||
claimed_until: DateTime<Utc>,
|
||||
account_id: &str,
|
||||
access_token: &str,
|
||||
refresh_token: &str,
|
||||
expires_at: Option<DateTime<Utc>>,
|
||||
scope: Option<&str>,
|
||||
) -> Result<bool, CalendarError> {
|
||||
let enc_access = super::crypto::encrypt_token(service.private_key(), access_token).map_err(CalendarError::Domain)?;
|
||||
let enc_refresh =
|
||||
super::crypto::encrypt_token(service.private_key(), refresh_token).map_err(CalendarError::Domain)?;
|
||||
let mut tx = service
|
||||
.begin_tx(WorkloadTier::InteractiveWrite, "begin update_tokens_under_claim")
|
||||
.await?;
|
||||
if !lock_and_verify_claim(tx.tx_mut(), subscription_id, claimed_until).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
sqlx::query(
|
||||
r#"UPDATE calendar_accounts
|
||||
SET access_token = $2, refresh_token = $3, expires_at = $4, scope = $5,
|
||||
status = 'active', last_error = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1"#,
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(&enc_access)
|
||||
.bind(&enc_refresh)
|
||||
.bind(expires_at)
|
||||
.bind(scope)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("update account tokens"))?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(internal_err("commit update_tokens_under_claim"))?;
|
||||
Ok(true)
|
||||
}
|
||||
async fn persist_events_under_claim(
|
||||
service: &CalendarService,
|
||||
subscription_id: &str,
|
||||
claimed_until: DateTime<Utc>,
|
||||
fallback_tz: Option<&str>,
|
||||
result: &CalendarProviderListEventsResult,
|
||||
) -> Result<bool, CalendarError> {
|
||||
let mut tx = service
|
||||
.begin_tx(WorkloadTier::LongQuery, "begin persist_events_under_claim")
|
||||
.await?;
|
||||
if !lock_and_verify_claim(tx.tx_mut(), subscription_id, claimed_until).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut cancelled_ids: Vec<String> = Vec::new();
|
||||
let mut failed_event_ids: Vec<String> = Vec::new();
|
||||
for event in &result.events {
|
||||
if event.status.as_deref() == Some("cancelled") {
|
||||
cancelled_ids.push(event.id.clone());
|
||||
continue;
|
||||
}
|
||||
let Some(ResolvedEventTimes {
|
||||
start_at_utc,
|
||||
end_at_utc,
|
||||
all_day,
|
||||
orig_tz,
|
||||
}) = resolve_event_times(event, fallback_tz)?
|
||||
else {
|
||||
failed_event_ids.push(event.id.clone());
|
||||
continue;
|
||||
};
|
||||
let recurrence_id = event
|
||||
.original_start_time
|
||||
.as_ref()
|
||||
.and_then(|t| {
|
||||
t.date_time
|
||||
.as_deref()
|
||||
.filter(|s| !s.is_empty())
|
||||
.or_else(|| t.date.as_deref().filter(|s| !s.is_empty()))
|
||||
})
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| event.id.clone());
|
||||
let provider_updated_at = event
|
||||
.updated
|
||||
.as_deref()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|u| parse_js_iso_datetime(u).ok_or_else(|| CalendarError::Internal("Invalid time value".to_owned())))
|
||||
.transpose()?;
|
||||
sqlx::query(
|
||||
r#"INSERT INTO calendar_events (
|
||||
id, subscription_id, external_event_id, recurrence_id, etag, status,
|
||||
title, description, location, start_at_utc, end_at_utc, original_timezone,
|
||||
all_day, provider_updated_at, raw, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, clock_timestamp(), clock_timestamp())
|
||||
ON CONFLICT (subscription_id, external_event_id, recurrence_id) DO UPDATE SET
|
||||
etag = EXCLUDED.etag, status = EXCLUDED.status, title = EXCLUDED.title,
|
||||
description = EXCLUDED.description, location = EXCLUDED.location,
|
||||
start_at_utc = EXCLUDED.start_at_utc, end_at_utc = EXCLUDED.end_at_utc,
|
||||
original_timezone = EXCLUDED.original_timezone, all_day = EXCLUDED.all_day,
|
||||
provider_updated_at = EXCLUDED.provider_updated_at, raw = EXCLUDED.raw, updated_at = clock_timestamp()"#,
|
||||
)
|
||||
.bind(Uuid::new_v4().to_string())
|
||||
.bind(subscription_id)
|
||||
.bind(&event.id)
|
||||
.bind(&recurrence_id)
|
||||
.bind(&event.etag)
|
||||
.bind(&event.status)
|
||||
.bind(&event.summary)
|
||||
.bind(&event.description)
|
||||
.bind(&event.location)
|
||||
.bind(start_at_utc)
|
||||
.bind(end_at_utc)
|
||||
.bind(&orig_tz)
|
||||
.bind(all_day)
|
||||
.bind(provider_updated_at)
|
||||
.bind(event.raw.to_json_value())
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("upsert calendar_event"))?;
|
||||
}
|
||||
if !failed_event_ids.is_empty() {
|
||||
tracing::warn!(subscription_id = %subscription_id, failed_count = failed_event_ids.len(), "skipped unmappable calendar events");
|
||||
}
|
||||
if !cancelled_ids.is_empty() {
|
||||
sqlx::query("DELETE FROM calendar_events WHERE subscription_id = $1 AND external_event_id = ANY($2)")
|
||||
.bind(subscription_id)
|
||||
.bind(&cancelled_ids)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("delete cancelled calendar_events"))?;
|
||||
}
|
||||
if let Some(ref next_token) = result.next_sync_token {
|
||||
sqlx::query("UPDATE calendar_subscriptions SET sync_token = $2, updated_at = clock_timestamp() WHERE id = $1")
|
||||
.bind(subscription_id)
|
||||
.bind(next_token)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("update sync_token"))?;
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(internal_err("commit persist_events_under_claim"))?;
|
||||
Ok(true)
|
||||
}
|
||||
async fn is_claim_still_valid(
|
||||
service: &CalendarService,
|
||||
subscription_id: &str,
|
||||
claimed_until: DateTime<Utc>,
|
||||
) -> Result<bool, CalendarError> {
|
||||
let mut conn = service.read_conn("check calendar claim active").await?;
|
||||
let exists: bool = sqlx::query_scalar(
|
||||
r#"SELECT EXISTS(
|
||||
SELECT 1 FROM calendar_subscriptions s
|
||||
JOIN calendar_accounts a ON a.id = s.account_id
|
||||
WHERE s.id = $1 AND s.enabled AND a.status = 'active'
|
||||
AND s.sync_claimed_until = $2 AND s.sync_claimed_until > clock_timestamp()
|
||||
)"#,
|
||||
)
|
||||
.bind(subscription_id)
|
||||
.bind(claimed_until)
|
||||
.fetch_one(&mut *conn)
|
||||
.await
|
||||
.map_err(internal_err("check calendar claim active"))?;
|
||||
Ok(exists)
|
||||
}
|
||||
async fn ensure_google_webhook_channel(
|
||||
service: &CalendarService,
|
||||
google_cfg: &super::google::CalendarGoogleConfig,
|
||||
subscription: &CalendarSubscriptionRecord,
|
||||
access_token: &str,
|
||||
address: &str,
|
||||
claimed_until: DateTime<Utc>,
|
||||
) -> Result<(), CalendarError> {
|
||||
let db_now = db_clock_timestamp(service).await?;
|
||||
if subscription
|
||||
.channel_expiration
|
||||
.is_some_and(|exp| exp > db_now + Duration::hours(24))
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if !is_claim_still_valid(service, &subscription.id, claimed_until).await? {
|
||||
return Ok(());
|
||||
}
|
||||
let provider = GoogleCalendarProvider::new(google_cfg.clone());
|
||||
if let (Some(ch_id), Some(res_id)) = (
|
||||
subscription.custom_channel_id.as_deref(),
|
||||
subscription.custom_resource_id.as_deref(),
|
||||
) {
|
||||
if let Err(err) = provider.stop_channel(access_token, ch_id, res_id).await
|
||||
&& !matches!(err, CalendarError::ProviderRequest { status: 404, .. })
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
if !update_channel_under_claim(service, &subscription.id, claimed_until, None, None, None).await? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let channel_id = Uuid::new_v4().to_string();
|
||||
let token = service.webhook_token_from_config(google_cfg);
|
||||
match provider
|
||||
.watch_calendar(
|
||||
access_token,
|
||||
&subscription.external_calendar_id,
|
||||
address,
|
||||
Some(&token),
|
||||
&channel_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(res) => {
|
||||
let saved = update_channel_under_claim(
|
||||
service,
|
||||
&subscription.id,
|
||||
claimed_until,
|
||||
Some(&res.channel_id),
|
||||
Some(&res.resource_id),
|
||||
res.expiration,
|
||||
)
|
||||
.await?;
|
||||
if !saved {
|
||||
let _ = provider
|
||||
.stop_channel(access_token, &res.channel_id, &res.resource_id)
|
||||
.await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(CalendarError::ProviderRequest {
|
||||
status: 400,
|
||||
ref message,
|
||||
}) if message.contains("pushNotSupportedForRequestedResource") => {
|
||||
let far_future = DateTime::parse_from_rfc3339("9999-12-31T23:59:59.999Z")
|
||||
.ok()
|
||||
.map(|d| d.with_timezone(&Utc));
|
||||
let _ = update_channel_under_claim(service, &subscription.id, claimed_until, None, None, far_future).await?;
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
async fn update_channel_under_claim(
|
||||
service: &CalendarService,
|
||||
subscription_id: &str,
|
||||
claimed_until: DateTime<Utc>,
|
||||
channel_id: Option<&str>,
|
||||
resource_id: Option<&str>,
|
||||
expiration: Option<DateTime<Utc>>,
|
||||
) -> Result<bool, CalendarError> {
|
||||
let mut tx = service
|
||||
.begin_tx(WorkloadTier::InteractiveWrite, "begin update_channel")
|
||||
.await?;
|
||||
if !lock_and_verify_claim(tx.tx_mut(), subscription_id, claimed_until).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE calendar_subscriptions SET custom_channel_id = $2, custom_resource_id = $3, channel_expiration = $4, updated_at = clock_timestamp() WHERE id = $1",
|
||||
)
|
||||
.bind(subscription_id)
|
||||
.bind(channel_id)
|
||||
.bind(resource_id)
|
||||
.bind(expiration)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("update_channel"))?;
|
||||
tx.commit().await.map_err(internal_err("commit update_channel"))?;
|
||||
Ok(true)
|
||||
}
|
||||
async fn handle_sync_failure(
|
||||
service: &CalendarService,
|
||||
subscription: &CalendarSubscriptionRecord,
|
||||
account: &CalendarAccountRecord,
|
||||
claimed_until: DateTime<Utc>,
|
||||
err: &CalendarError,
|
||||
access_token: Option<&str>,
|
||||
disable_on_not_found: bool,
|
||||
) -> Result<(), CalendarError> {
|
||||
if disable_on_not_found && matches!(err, CalendarError::ProviderRequest { status: 404, .. }) {
|
||||
if account.provider == CalendarProviderName::Google
|
||||
&& let (Some(token), Some(ch_id), Some(res_id)) = (
|
||||
access_token,
|
||||
subscription.custom_channel_id.as_deref(),
|
||||
subscription.custom_resource_id.as_deref(),
|
||||
)
|
||||
&& let Ok(configs) = service.load_configs().await
|
||||
{
|
||||
let _ = GoogleCalendarProvider::new(configs.google)
|
||||
.stop_channel(token, ch_id, res_id)
|
||||
.await;
|
||||
}
|
||||
let mut tx = service
|
||||
.begin_tx(WorkloadTier::InteractiveWrite, "begin disable_and_purge")
|
||||
.await?;
|
||||
if lock_and_verify_claim(tx.tx_mut(), &subscription.id, claimed_until).await? {
|
||||
sqlx::query(
|
||||
r#"UPDATE calendar_subscriptions
|
||||
SET enabled = false, sync_token = NULL, sync_retry_count = 0, custom_channel_id = NULL,
|
||||
custom_resource_id = NULL, channel_expiration = NULL, sync_claimed_until = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1"#,
|
||||
)
|
||||
.bind(&subscription.id)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("disable subscription"))?;
|
||||
sqlx::query("DELETE FROM calendar_events WHERE subscription_id = $1")
|
||||
.bind(&subscription.id)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("purge subscription events"))?;
|
||||
tx.commit().await.map_err(internal_err("commit disable_and_purge"))?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let is_token_invalid =
|
||||
matches!(err, CalendarError::ProviderRequest { status: 401, .. }) || err.to_string().contains("invalid_grant");
|
||||
if is_token_invalid {
|
||||
let mut tx = service
|
||||
.begin_tx(WorkloadTier::InteractiveWrite, "begin invalidate_and_purge")
|
||||
.await?;
|
||||
if lock_and_verify_claim(tx.tx_mut(), &subscription.id, claimed_until).await? {
|
||||
let truncated = truncate_calendar_error(&err.to_string());
|
||||
sqlx::query("UPDATE calendar_accounts SET status = 'invalid', last_error = $2, updated_at = clock_timestamp() WHERE id = $1")
|
||||
.bind(&account.id)
|
||||
.bind(&truncated)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("invalidate account"))?;
|
||||
sqlx::query("SELECT id FROM calendar_subscriptions WHERE account_id = $1 ORDER BY id ASC FOR UPDATE")
|
||||
.bind(&account.id)
|
||||
.fetch_all(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("lock account subscriptions"))?;
|
||||
sqlx::query("DELETE FROM calendar_events WHERE subscription_id IN (SELECT id FROM calendar_subscriptions WHERE account_id = $1)")
|
||||
.bind(&account.id)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("purge account events"))?;
|
||||
sqlx::query("UPDATE calendar_subscriptions SET sync_token = NULL, sync_claimed_until = NULL, updated_at = clock_timestamp() WHERE account_id = $1")
|
||||
.bind(&account.id)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(internal_err("clear account sync tokens"))?;
|
||||
tx.commit().await.map_err(internal_err("commit invalidate_and_purge"))?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let attempt = subscription.sync_retry_count.saturating_add(1);
|
||||
let shift = u32::try_from(attempt.saturating_sub(1)).unwrap_or(0).min(10);
|
||||
let delay_secs = SYNC_FAILURE_BACKOFF_BASE_SECS
|
||||
.saturating_mul(1i64 << shift)
|
||||
.min(SYNC_FAILURE_BACKOFF_MAX_SECS);
|
||||
let next_retry = db_clock_timestamp(service).await? + Duration::seconds(delay_secs);
|
||||
complete_sync(
|
||||
service,
|
||||
&subscription.id,
|
||||
claimed_until,
|
||||
subscription.last_sync_at,
|
||||
next_retry,
|
||||
attempt,
|
||||
)
|
||||
.await
|
||||
}
|
||||
async fn complete_sync(
|
||||
service: &CalendarService,
|
||||
subscription_id: &str,
|
||||
claimed_until: DateTime<Utc>,
|
||||
last_sync_at: Option<DateTime<Utc>>,
|
||||
next_sync_at: DateTime<Utc>,
|
||||
sync_retry_count: i32,
|
||||
) -> Result<(), CalendarError> {
|
||||
let mut conn = service.write_conn("acquire complete_sync").await?;
|
||||
sqlx::query(
|
||||
r#"UPDATE calendar_subscriptions
|
||||
SET last_sync_at = $2,
|
||||
next_sync_at = CASE WHEN sync_claimed_until IS NOT NULL AND next_sync_at < sync_claimed_until THEN next_sync_at ELSE $3 END,
|
||||
sync_retry_count = $4, sync_claimed_until = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND sync_claimed_until = $5 AND sync_claimed_until > clock_timestamp()"#,
|
||||
)
|
||||
.bind(subscription_id)
|
||||
.bind(last_sync_at)
|
||||
.bind(next_sync_at)
|
||||
.bind(sync_retry_count)
|
||||
.bind(claimed_until)
|
||||
.execute(&mut *conn)
|
||||
.await
|
||||
.map_err(internal_err("complete_sync"))?;
|
||||
Ok(())
|
||||
}
|
||||
async fn lock_and_verify_claim(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
subscription_id: &str,
|
||||
claimed_until: DateTime<Utc>,
|
||||
) -> Result<bool, CalendarError> {
|
||||
let active_account: Option<String> = sqlx::query_scalar(
|
||||
r#"SELECT account.id FROM calendar_accounts account
|
||||
JOIN calendar_subscriptions subscription ON subscription.account_id = account.id
|
||||
WHERE subscription.id = $1 AND account.status = 'active' FOR UPDATE OF account"#,
|
||||
)
|
||||
.bind(subscription_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(internal_err("lock calendar account"))?;
|
||||
if active_account.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let valid_claim: Option<String> = sqlx::query_scalar(
|
||||
"SELECT id FROM calendar_subscriptions WHERE id = $1 AND enabled AND sync_claimed_until = $2 AND sync_claimed_until > clock_timestamp() FOR UPDATE",
|
||||
)
|
||||
.bind(subscription_id)
|
||||
.bind(claimed_until)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(internal_err("lock calendar subscription claim"))?;
|
||||
Ok(valid_claim.is_some())
|
||||
}
|
||||
fn resolve_event_time(
|
||||
time: &CalendarProviderEventTime,
|
||||
fallback_tz: Option<&str>,
|
||||
) -> Result<Option<(DateTime<Utc>, bool)>, CalendarError> {
|
||||
let inv = || CalendarError::Internal("Invalid time value".to_owned());
|
||||
if let Some(dt_str) = time.date_time.as_deref().filter(|s| !s.is_empty()) {
|
||||
let dt = parse_js_iso_datetime(dt_str).ok_or_else(inv)?;
|
||||
return Ok(Some((dt, false)));
|
||||
}
|
||||
let Some(date_str) = time.date.as_deref().filter(|s| !s.is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let parse_js_num = |seg: &str| -> Option<f64> {
|
||||
let t = seg.trim_matches(|c: char| {
|
||||
matches!(
|
||||
c,
|
||||
'\u{0009}'..='\u{000D}'
|
||||
| '\u{0020}'
|
||||
| '\u{00A0}'
|
||||
| '\u{1680}'
|
||||
| '\u{2000}'..='\u{200A}'
|
||||
| '\u{2028}'
|
||||
| '\u{2029}'
|
||||
| '\u{202F}'
|
||||
| '\u{205F}'
|
||||
| '\u{3000}'
|
||||
| '\u{FEFF}'
|
||||
)
|
||||
});
|
||||
if t.is_empty() {
|
||||
return Some(0.0);
|
||||
}
|
||||
if !t.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
for (p1, p2, radix) in [("0x", "0X", 16u32), ("0b", "0B", 2u32), ("0o", "0O", 8u32)] {
|
||||
if let Some(rest) = t.strip_prefix(p1).or_else(|| t.strip_prefix(p2)) {
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut acc = 0.0f64;
|
||||
for b in rest.bytes() {
|
||||
let digit = (b as char).to_digit(radix)?;
|
||||
acc = acc * f64::from(radix) + f64::from(digit);
|
||||
}
|
||||
return acc.is_finite().then_some(acc);
|
||||
}
|
||||
}
|
||||
let body = t.strip_prefix(['+', '-']).unwrap_or(t);
|
||||
let mant = if let Some(idx) = body.find(['e', 'E']) {
|
||||
let ed = body[idx + 1..].strip_prefix(['+', '-']).unwrap_or(&body[idx + 1..]);
|
||||
if ed.is_empty() || !ed.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
&body[..idx]
|
||||
} else {
|
||||
body
|
||||
};
|
||||
let valid_mant = if let Some((l, r)) = mant.split_once('.') {
|
||||
!(l.is_empty() && r.is_empty()) && l.bytes().all(|b| b.is_ascii_digit()) && r.bytes().all(|b| b.is_ascii_digit())
|
||||
} else {
|
||||
!mant.is_empty() && mant.bytes().all(|b| b.is_ascii_digit())
|
||||
};
|
||||
if !valid_mant {
|
||||
return None;
|
||||
}
|
||||
t.parse::<f64>().ok().filter(|f| f.is_finite())
|
||||
};
|
||||
let mut parts = date_str.split('-');
|
||||
let (Some(y), Some(m), Some(d)) = (
|
||||
parts.next().and_then(parse_js_num),
|
||||
parts.next().and_then(parse_js_num),
|
||||
parts.next().and_then(parse_js_num),
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let tz = time.time_zone.as_deref().or(fallback_tz).unwrap_or("UTC");
|
||||
let Ok(Some(dt)) = try_offset_at_utc_guess_ymd_f64(y, m - 1.0, d, Some(tz)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some((dt, true)))
|
||||
}
|
||||
struct ResolvedEventTimes {
|
||||
start_at_utc: DateTime<Utc>,
|
||||
end_at_utc: DateTime<Utc>,
|
||||
all_day: bool,
|
||||
orig_tz: Option<String>,
|
||||
}
|
||||
fn resolve_event_times(
|
||||
event: &CalendarProviderEvent,
|
||||
fallback_tz: Option<&str>,
|
||||
) -> Result<Option<ResolvedEventTimes>, CalendarError> {
|
||||
let Some((start_at_utc, start_all_day)) = resolve_event_time(&event.start, fallback_tz)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some((end_at_utc, end_all_day)) = resolve_event_time(&event.end, fallback_tz)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let orig_tz = event
|
||||
.start
|
||||
.time_zone
|
||||
.clone()
|
||||
.or_else(|| event.end.time_zone.clone())
|
||||
.or_else(|| fallback_tz.map(str::to_owned));
|
||||
Ok(Some(ResolvedEventTimes {
|
||||
start_at_utc,
|
||||
end_at_utc,
|
||||
all_day: start_all_day || end_all_day,
|
||||
orig_tz,
|
||||
}))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -15,6 +15,9 @@ use server_domain::safe_fetch::{SafeFetchPolicy, SafeFetchRequest, safe_fetch};
|
||||
use server_mail::{MailSendResult, MailTemplate, SmtpConfig, SmtpMailer, TestMailProps};
|
||||
use server_types::{DeploymentMode, DomainError};
|
||||
|
||||
use super::calendar::{
|
||||
CalendarCalDAVProviderPresetObjectType, resolve_server_caldav_providers, resolve_server_calendar_providers,
|
||||
};
|
||||
use super::doc::{PageInfo, PaginationInput};
|
||||
use super::user::{
|
||||
CreateUserInput, ImportUsersInput, ListUserInput, ManageUserInput, UserImportResultType, UserType, WorkspaceUserType,
|
||||
@@ -119,7 +122,6 @@ pub struct ServerConfigType {
|
||||
pub initialized: bool,
|
||||
pub base_url: String,
|
||||
pub features: Vec<ServerFeature>,
|
||||
pub calendar_providers: Vec<CalendarProviderType>,
|
||||
pub credentials_requirement: CredentialsRequirementType,
|
||||
pub available_user_features: Vec<FeatureType>,
|
||||
pub oauth_providers: Vec<OAuthProviderType>,
|
||||
@@ -205,6 +207,15 @@ impl ServerConfigType {
|
||||
}
|
||||
computed
|
||||
}
|
||||
|
||||
async fn calendar_providers(&self, ctx: &Context<'_>) -> Result<Vec<CalendarProviderType>> {
|
||||
resolve_server_calendar_providers(ctx).await
|
||||
}
|
||||
|
||||
#[graphql(name = "calendarCalDAVProviders")]
|
||||
async fn calendar_caldav_providers(&self, ctx: &Context<'_>) -> Result<Vec<CalendarCalDAVProviderPresetObjectType>> {
|
||||
resolve_server_caldav_providers(ctx).await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(InputObject, Clone, Debug)]
|
||||
@@ -777,7 +788,6 @@ pub(crate) async fn resolve_server_config(ctx: &Context<'_>) -> Result<ServerCon
|
||||
initialized,
|
||||
base_url: cfg.external_url.clone(),
|
||||
features,
|
||||
calendar_providers: Vec::new(),
|
||||
credentials_requirement: CredentialsRequirementType {
|
||||
password: PasswordLimitsType {
|
||||
min_length: password_min,
|
||||
|
||||
@@ -1,6 +1,520 @@
|
||||
//! Calendar GraphQL root extensions.
|
||||
|
||||
use async_graphql::{EmptyMutation, MergedObject};
|
||||
|
||||
#[derive(MergedObject, Default)]
|
||||
pub struct CalendarMutation(EmptyMutation);
|
||||
//! Calendar GraphQL types, nested resolvers, and root mutations aligned with
|
||||
//! `v0.27.5` `schema.gql`.
|
||||
use super::admin::CalendarProviderType;
|
||||
use super::{current_authenticated_user, require_authenticated_user};
|
||||
use crate::AppState;
|
||||
use crate::legacy_compat::errors::{LegacyErrorEnvelope, domain_error_to_graphql, envelope_to_graphql};
|
||||
use async_graphql::{Context, Error, InputObject, Object, Result, SimpleObject};
|
||||
use chrono::{DateTime, Utc};
|
||||
use server_domain::calendar::caldav::CalendarCaldavProviderPreset;
|
||||
use server_domain::calendar::oauth::{CalendarOAuthState, CalendarOAuthStore};
|
||||
use server_domain::calendar::{
|
||||
CalendarAccountRecord, CalendarError, CalendarEventRecord, CalendarProviderName, CalendarService,
|
||||
CalendarSubscriptionRecord, LinkCaldavInput, WorkspaceCalendarItemPatch, WorkspaceCalendarItemRecord,
|
||||
WorkspaceCalendarRecord, truncate_calendar_error,
|
||||
};
|
||||
use server_types::DomainError;
|
||||
use std::sync::Arc;
|
||||
pub(crate) fn calendar_service_from_state(state: &AppState) -> &CalendarService {
|
||||
&state.calendar
|
||||
}
|
||||
pub(crate) fn calendar_oauth_store_from_state(
|
||||
state: &AppState,
|
||||
) -> std::result::Result<&CalendarOAuthStore, DomainError> {
|
||||
state
|
||||
.calendar_oauth
|
||||
.as_ref()
|
||||
.ok_or_else(|| DomainError::Unavailable("session redis is not configured".to_owned()))
|
||||
}
|
||||
pub(crate) fn calendar_error_to_envelope(err: &CalendarError) -> LegacyErrorEnvelope {
|
||||
match err {
|
||||
CalendarError::BadRequest { code, message } => LegacyErrorEnvelope {
|
||||
status: 400,
|
||||
code: "Bad Request".to_owned(),
|
||||
error_type: "BAD_REQUEST".to_owned(),
|
||||
name: "GRAPHQL_BAD_REQUEST".to_owned(),
|
||||
message: message.clone(),
|
||||
data: Some(serde_json::json!({ "code": code, "message": message })),
|
||||
},
|
||||
CalendarError::ProviderRequest { status, message } => {
|
||||
let msg = truncate_calendar_error(message);
|
||||
LegacyErrorEnvelope {
|
||||
status: 500,
|
||||
code: "Internal Server Error".to_owned(),
|
||||
error_type: "INTERNAL_SERVER_ERROR".to_owned(),
|
||||
name: "CALENDAR_PROVIDER_REQUEST_ERROR".to_owned(),
|
||||
message: format!("Calendar provider request error, status: {status}, message: {msg}"),
|
||||
data: Some(serde_json::json!({ "status": status, "message": msg })),
|
||||
}
|
||||
}
|
||||
CalendarError::SyncTokenInvalid(msg) => LegacyErrorEnvelope {
|
||||
status: 400,
|
||||
code: "Bad Request".to_owned(),
|
||||
error_type: "BAD_REQUEST".to_owned(),
|
||||
name: "GRAPHQL_BAD_REQUEST".to_owned(),
|
||||
message: msg.clone(),
|
||||
data: Some(serde_json::json!({ "code": "calendar_sync_token_invalid", "message": msg })),
|
||||
},
|
||||
CalendarError::Domain(dom) => crate::legacy_compat::errors::domain_error_to_envelope(dom),
|
||||
CalendarError::Internal(msg) => {
|
||||
crate::legacy_compat::errors::domain_error_to_envelope(&DomainError::Internal(msg.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) fn calendar_error_to_graphql(err: CalendarError) -> Error {
|
||||
envelope_to_graphql(calendar_error_to_envelope(&err))
|
||||
}
|
||||
impl From<CalendarProviderName> for CalendarProviderType {
|
||||
fn from(value: CalendarProviderName) -> Self {
|
||||
match value {
|
||||
CalendarProviderName::Google => Self::Google,
|
||||
CalendarProviderName::CalDAV => Self::CalDAV,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<CalendarProviderType> for CalendarProviderName {
|
||||
fn from(value: CalendarProviderType) -> Self {
|
||||
match value {
|
||||
CalendarProviderType::Google => Self::Google,
|
||||
CalendarProviderType::CalDAV => Self::CalDAV,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(SimpleObject, Clone, Debug, Eq, PartialEq)]
|
||||
#[graphql(name = "CalendarCalDAVProviderPresetObjectType")]
|
||||
pub struct CalendarCalDAVProviderPresetObjectType {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub requires_app_password: Option<bool>,
|
||||
pub docs_url: Option<String>,
|
||||
}
|
||||
impl From<CalendarCaldavProviderPreset> for CalendarCalDAVProviderPresetObjectType {
|
||||
fn from(v: CalendarCaldavProviderPreset) -> Self {
|
||||
Self {
|
||||
id: v.id,
|
||||
label: v.label,
|
||||
requires_app_password: v.requires_app_password,
|
||||
docs_url: v.docs_url,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(SimpleObject, Clone, Debug)]
|
||||
#[graphql(name = "CalendarSubscriptionObjectType")]
|
||||
pub struct CalendarSubscriptionObjectType {
|
||||
pub id: String,
|
||||
pub account_id: String,
|
||||
pub provider: CalendarProviderType,
|
||||
pub external_calendar_id: String,
|
||||
pub display_name: Option<String>,
|
||||
pub timezone: Option<String>,
|
||||
pub color: Option<String>,
|
||||
pub enabled: bool,
|
||||
pub last_sync_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
impl From<CalendarSubscriptionRecord> for CalendarSubscriptionObjectType {
|
||||
fn from(value: CalendarSubscriptionRecord) -> Self {
|
||||
Self {
|
||||
id: value.id,
|
||||
account_id: value.account_id,
|
||||
provider: value.provider.into(),
|
||||
external_calendar_id: value.external_calendar_id,
|
||||
display_name: value.display_name,
|
||||
timezone: value.timezone,
|
||||
color: value.color,
|
||||
enabled: value.enabled,
|
||||
last_sync_at: value.last_sync_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CalendarAccountObjectType {
|
||||
record: CalendarAccountRecord,
|
||||
}
|
||||
impl From<CalendarAccountRecord> for CalendarAccountObjectType {
|
||||
fn from(record: CalendarAccountRecord) -> Self {
|
||||
Self { record }
|
||||
}
|
||||
}
|
||||
#[Object(name = "CalendarAccountObjectType")]
|
||||
impl CalendarAccountObjectType {
|
||||
async fn id(&self) -> &str {
|
||||
&self.record.id
|
||||
}
|
||||
async fn provider(&self) -> CalendarProviderType {
|
||||
self.record.provider.into()
|
||||
}
|
||||
async fn provider_account_id(&self) -> &str {
|
||||
&self.record.provider_account_id
|
||||
}
|
||||
async fn display_name(&self) -> Option<&str> {
|
||||
self.record.display_name.as_deref()
|
||||
}
|
||||
async fn email(&self) -> Option<&str> {
|
||||
self.record.email.as_deref()
|
||||
}
|
||||
async fn status(&self) -> &str {
|
||||
&self.record.status
|
||||
}
|
||||
async fn last_error(&self) -> Option<&str> {
|
||||
self.record.last_error.as_deref()
|
||||
}
|
||||
async fn refresh_interval_minutes(&self) -> i32 {
|
||||
self.record.refresh_interval_minutes
|
||||
}
|
||||
async fn calendars_count(&self) -> i32 {
|
||||
self.record.calendars_count
|
||||
}
|
||||
async fn created_at(&self) -> DateTime<Utc> {
|
||||
self.record.created_at
|
||||
}
|
||||
async fn updated_at(&self) -> DateTime<Utc> {
|
||||
self.record.updated_at
|
||||
}
|
||||
async fn calendars(&self, ctx: &Context<'_>) -> Result<Vec<CalendarSubscriptionObjectType>> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
let subs = ctx
|
||||
.data_unchecked::<Arc<AppState>>()
|
||||
.calendar
|
||||
.list_account_calendars(&user.id, &self.record.id)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(subs.into_iter().map(Into::into).collect())
|
||||
}
|
||||
}
|
||||
#[derive(SimpleObject, Clone, Debug)]
|
||||
#[graphql(name = "WorkspaceCalendarItemObjectType")]
|
||||
pub struct WorkspaceCalendarItemObjectType {
|
||||
pub id: String,
|
||||
pub subscription_id: String,
|
||||
pub sort_order: Option<i32>,
|
||||
pub color_override: Option<String>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
impl From<WorkspaceCalendarItemRecord> for WorkspaceCalendarItemObjectType {
|
||||
fn from(value: WorkspaceCalendarItemRecord) -> Self {
|
||||
Self {
|
||||
id: value.id,
|
||||
subscription_id: value.subscription_id,
|
||||
sort_order: value.sort_order,
|
||||
color_override: value.color_override,
|
||||
enabled: value.enabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(SimpleObject, Clone, Debug)]
|
||||
#[graphql(name = "CalendarEventObjectType")]
|
||||
pub struct CalendarEventObjectType {
|
||||
pub id: String,
|
||||
pub subscription_id: String,
|
||||
pub external_event_id: String,
|
||||
pub recurrence_id: Option<String>,
|
||||
pub status: Option<String>,
|
||||
pub title: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub location: Option<String>,
|
||||
pub start_at_utc: DateTime<Utc>,
|
||||
pub end_at_utc: DateTime<Utc>,
|
||||
pub original_timezone: Option<String>,
|
||||
pub all_day: bool,
|
||||
}
|
||||
impl From<CalendarEventRecord> for CalendarEventObjectType {
|
||||
fn from(value: CalendarEventRecord) -> Self {
|
||||
Self {
|
||||
id: value.id,
|
||||
subscription_id: value.subscription_id,
|
||||
external_event_id: value.external_event_id,
|
||||
recurrence_id: value.recurrence_id,
|
||||
status: value.status,
|
||||
title: value.title,
|
||||
description: value.description,
|
||||
location: value.location,
|
||||
start_at_utc: value.start_at_utc,
|
||||
end_at_utc: value.end_at_utc,
|
||||
original_timezone: value.original_timezone,
|
||||
all_day: value.all_day,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WorkspaceCalendarObjectType {
|
||||
record: WorkspaceCalendarRecord,
|
||||
}
|
||||
impl From<WorkspaceCalendarRecord> for WorkspaceCalendarObjectType {
|
||||
fn from(record: WorkspaceCalendarRecord) -> Self {
|
||||
Self { record }
|
||||
}
|
||||
}
|
||||
#[Object(name = "WorkspaceCalendarObjectType")]
|
||||
impl WorkspaceCalendarObjectType {
|
||||
async fn id(&self) -> &str {
|
||||
&self.record.id
|
||||
}
|
||||
async fn workspace_id(&self) -> &str {
|
||||
&self.record.workspace_id
|
||||
}
|
||||
async fn created_by_user_id(&self) -> &str {
|
||||
&self.record.created_by_user_id
|
||||
}
|
||||
async fn display_name_override(&self) -> Option<&str> {
|
||||
self.record.display_name_override.as_deref()
|
||||
}
|
||||
async fn color_override(&self) -> Option<&str> {
|
||||
self.record.color_override.as_deref()
|
||||
}
|
||||
async fn enabled(&self) -> bool {
|
||||
self.record.enabled
|
||||
}
|
||||
async fn items(&self) -> Vec<WorkspaceCalendarItemObjectType> {
|
||||
self.record.items.iter().cloned().map(Into::into).collect()
|
||||
}
|
||||
async fn events(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
from: DateTime<Utc>,
|
||||
to: DateTime<Utc>,
|
||||
) -> Result<Vec<CalendarEventObjectType>> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
let perms = state
|
||||
.workspaces
|
||||
.resolve_workspace_permissions(&user.id, &self.record.workspace_id)
|
||||
.await
|
||||
.map_err(|e| domain_error_to_graphql(&e))?;
|
||||
if !perms.settings_read {
|
||||
return Err(domain_error_to_graphql(&DomainError::Forbidden(
|
||||
"Workspace.Settings.Read permission required".to_owned(),
|
||||
)));
|
||||
}
|
||||
let events = state
|
||||
.calendar
|
||||
.list_workspace_events(&self.record.id, from, to)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(events.into_iter().map(Into::into).collect())
|
||||
}
|
||||
}
|
||||
#[derive(InputObject, Clone, Debug)]
|
||||
#[graphql(name = "LinkCalendarAccountInput")]
|
||||
pub struct LinkCalendarAccountInput {
|
||||
pub provider: CalendarProviderType,
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
#[derive(InputObject, Clone, Debug)]
|
||||
#[graphql(name = "LinkCalDAVAccountInput")]
|
||||
pub struct LinkCalDAVAccountInput {
|
||||
pub provider_preset_id: String,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
pub display_name: Option<String>,
|
||||
}
|
||||
#[derive(InputObject, Clone, Debug)]
|
||||
#[graphql(name = "WorkspaceCalendarItemInput")]
|
||||
pub struct WorkspaceCalendarItemInput {
|
||||
pub subscription_id: String,
|
||||
pub sort_order: Option<i32>,
|
||||
pub color_override: Option<String>,
|
||||
}
|
||||
#[derive(InputObject, Clone, Debug)]
|
||||
#[graphql(name = "UpdateWorkspaceCalendarsInput")]
|
||||
pub struct UpdateWorkspaceCalendarsInput {
|
||||
pub workspace_id: String,
|
||||
pub items: Vec<WorkspaceCalendarItemInput>,
|
||||
}
|
||||
pub(crate) async fn resolve_server_calendar_providers(ctx: &Context<'_>) -> Result<Vec<CalendarProviderType>> {
|
||||
let user_id = current_authenticated_user(ctx).map(|u| u.user_id);
|
||||
let providers = ctx
|
||||
.data_unchecked::<Arc<AppState>>()
|
||||
.calendar
|
||||
.list_available_providers(user_id.as_deref())
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(providers.into_iter().map(Into::into).collect())
|
||||
}
|
||||
pub(crate) async fn resolve_server_caldav_providers(
|
||||
ctx: &Context<'_>,
|
||||
) -> Result<Vec<CalendarCalDAVProviderPresetObjectType>> {
|
||||
let presets = ctx
|
||||
.data_unchecked::<Arc<AppState>>()
|
||||
.calendar
|
||||
.list_caldav_presets()
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(presets.into_iter().map(Into::into).collect())
|
||||
}
|
||||
pub(crate) async fn resolve_user_calendar_accounts(
|
||||
ctx: &Context<'_>,
|
||||
target_user_id: &str,
|
||||
) -> Result<Vec<CalendarAccountObjectType>> {
|
||||
let caller = require_authenticated_user(ctx).await?;
|
||||
if caller.id != target_user_id {
|
||||
return Err(domain_error_to_graphql(&DomainError::Forbidden(
|
||||
"Cannot read another user's calendar accounts".to_owned(),
|
||||
)));
|
||||
}
|
||||
let accounts = ctx
|
||||
.data_unchecked::<Arc<AppState>>()
|
||||
.calendar
|
||||
.list_accounts(target_user_id)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(accounts.into_iter().map(Into::into).collect())
|
||||
}
|
||||
pub(crate) async fn resolve_workspace_calendars(
|
||||
ctx: &Context<'_>,
|
||||
workspace_id: &str,
|
||||
) -> Result<Vec<WorkspaceCalendarObjectType>> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
let perms = state
|
||||
.workspaces
|
||||
.resolve_workspace_permissions(&user.id, workspace_id)
|
||||
.await
|
||||
.map_err(|e| domain_error_to_graphql(&e))?;
|
||||
if !perms.settings_read {
|
||||
return Err(domain_error_to_graphql(&DomainError::Forbidden(
|
||||
"Workspace.Settings.Read permission required".to_owned(),
|
||||
)));
|
||||
}
|
||||
let calendars = state
|
||||
.calendar
|
||||
.get_workspace_calendars(workspace_id)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(calendars.into_iter().map(Into::into).collect())
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct CalendarMutation;
|
||||
#[Object]
|
||||
impl CalendarMutation {
|
||||
async fn link_calendar_account(&self, ctx: &Context<'_>, input: LinkCalendarAccountInput) -> Result<String> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
let provider: CalendarProviderName = input.provider.into();
|
||||
state
|
||||
.calendar
|
||||
.assert_can_link_provider(&user.id, provider)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
let req_host = ctx
|
||||
.data_opt::<axum::http::HeaderMap>()
|
||||
.and_then(|h| h.get(axum::http::header::HOST))
|
||||
.and_then(|v| v.to_str().ok());
|
||||
let cfg = state.config.load();
|
||||
let redirect_uri = match input.redirect_uri {
|
||||
Some(raw) if !raw.is_empty() => Some(
|
||||
crate::rest::validate_and_build_calendar_redirect_uri(
|
||||
&raw,
|
||||
&cfg.external_url,
|
||||
&cfg.app_config_baseline.server.hosts,
|
||||
cfg.app_config_baseline.server.port,
|
||||
req_host,
|
||||
&[],
|
||||
)
|
||||
.map_err(|e| domain_error_to_graphql(&e))?,
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let oauth = calendar_oauth_store_from_state(state).map_err(|e| domain_error_to_graphql(&e))?;
|
||||
let state_token = oauth
|
||||
.save_oauth_state(CalendarOAuthState {
|
||||
provider,
|
||||
user_id: user.id,
|
||||
redirect_uri,
|
||||
token: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| domain_error_to_graphql(&e))?;
|
||||
let cb_origin = crate::rest::calendar_callback_origin(
|
||||
&cfg.external_url,
|
||||
&cfg.app_config_baseline.server.hosts,
|
||||
cfg.app_config_baseline.server.port,
|
||||
req_host,
|
||||
);
|
||||
let callback_url = state.calendar.callback_url_for(&cb_origin);
|
||||
state
|
||||
.calendar
|
||||
.get_auth_url(provider, &state_token, &callback_url)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)
|
||||
}
|
||||
#[graphql(name = "linkCalDAVAccount")]
|
||||
async fn link_caldav_account(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
input: LinkCalDAVAccountInput,
|
||||
) -> Result<CalendarAccountObjectType> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
let account = ctx
|
||||
.data_unchecked::<Arc<AppState>>()
|
||||
.calendar
|
||||
.link_caldav_account(
|
||||
&user.id,
|
||||
LinkCaldavInput {
|
||||
provider_preset_id: input.provider_preset_id,
|
||||
username: input.username,
|
||||
password: input.password,
|
||||
display_name: input.display_name,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(account.into())
|
||||
}
|
||||
async fn update_calendar_account(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
account_id: String,
|
||||
refresh_interval_minutes: i32,
|
||||
) -> Result<Option<CalendarAccountObjectType>> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
let updated = ctx
|
||||
.data_unchecked::<Arc<AppState>>()
|
||||
.calendar
|
||||
.update_account_refresh_interval(&user.id, &account_id, refresh_interval_minutes)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(updated.map(Into::into))
|
||||
}
|
||||
async fn unlink_calendar_account(&self, ctx: &Context<'_>, account_id: String) -> Result<bool> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
ctx
|
||||
.data_unchecked::<Arc<AppState>>()
|
||||
.calendar
|
||||
.unlink_account(&user.id, &account_id)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)
|
||||
}
|
||||
async fn update_workspace_calendars(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
input: UpdateWorkspaceCalendarsInput,
|
||||
) -> Result<WorkspaceCalendarObjectType> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
let perms = state
|
||||
.workspaces
|
||||
.resolve_workspace_permissions(&user.id, &input.workspace_id)
|
||||
.await
|
||||
.map_err(|e| domain_error_to_graphql(&e))?;
|
||||
if !perms.settings_update {
|
||||
return Err(domain_error_to_graphql(&DomainError::Forbidden(
|
||||
"Workspace.Settings.Update permission required".to_owned(),
|
||||
)));
|
||||
}
|
||||
let patches: Vec<WorkspaceCalendarItemPatch> = input
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| WorkspaceCalendarItemPatch {
|
||||
subscription_id: item.subscription_id,
|
||||
sort_order: item.sort_order,
|
||||
color_override: item.color_override,
|
||||
})
|
||||
.collect();
|
||||
let calendar = state
|
||||
.calendar
|
||||
.update_workspace_calendars(&input.workspace_id, &user.id, &patches)
|
||||
.await
|
||||
.map_err(calendar_error_to_graphql)?;
|
||||
Ok(calendar.into())
|
||||
}
|
||||
}
|
||||
@@ -291,6 +291,10 @@ impl UserType {
|
||||
refresh: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn calendar_accounts(&self, ctx: &Context<'_>) -> Result<Vec<super::calendar::CalendarAccountObjectType>> {
|
||||
super::calendar::resolve_user_calendar_accounts(ctx, &self.view.id).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_current_user(ctx: &Context<'_>) -> Option<UserType> {
|
||||
|
||||
@@ -514,6 +514,10 @@ impl WorkspaceType {
|
||||
super::search::resolve_workspace_search_docs(ctx, &self.record.id, input).await
|
||||
}
|
||||
|
||||
async fn calendars(&self, ctx: &Context<'_>) -> Result<Vec<super::calendar::WorkspaceCalendarObjectType>> {
|
||||
super::calendar::resolve_workspace_calendars(ctx, &self.record.id).await
|
||||
}
|
||||
|
||||
async fn public_docs(&self, ctx: &Context<'_>) -> Result<Vec<super::doc::DocType>> {
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
let actor = current_authenticated_user(ctx).map(|a| a.user_id);
|
||||
|
||||
@@ -21,6 +21,8 @@ use server_db::ServerDb;
|
||||
use server_db::phase_a_compat::sessions::PhaseASessionRepository;
|
||||
use server_domain::app_config::{AppConfigService, RuntimeAppConfigBaseline};
|
||||
use server_domain::auth::{AuthConfig, AuthService};
|
||||
use server_domain::calendar::CalendarService;
|
||||
use server_domain::calendar::oauth::CalendarOAuthStore;
|
||||
use server_domain::comments::CommentService;
|
||||
use server_domain::doc_sharing::DocSharingService;
|
||||
use server_domain::events::{EventBusPublisher, InvalidationPublisher, NoopEventPublisher};
|
||||
@@ -121,6 +123,9 @@ pub struct AppState {
|
||||
pub event_bus: Arc<dyn EventBusPublisher>,
|
||||
pub avatar_transcode_sem: Arc<tokio::sync::Semaphore>,
|
||||
pub strict_throttler: Arc<rest::throttle::StrictThrottler>,
|
||||
pub calendar_webhook_token: Arc<std::sync::Mutex<Option<String>>>,
|
||||
pub calendar: CalendarService,
|
||||
pub calendar_oauth: Option<CalendarOAuthStore>,
|
||||
}
|
||||
|
||||
/// Pre-wired domain services passed into [`AppState::with_services`].
|
||||
@@ -240,6 +245,14 @@ impl AppState {
|
||||
services: AppServices,
|
||||
) -> Arc<Self> {
|
||||
let admin = server_domain::admin::AdminService::new(db.clone());
|
||||
let calendar_webhook_token = Arc::new(std::sync::Mutex::new(None));
|
||||
let calendar = CalendarService::new(
|
||||
db.clone(),
|
||||
services.auth.config().private_key.clone(),
|
||||
config.external_url.clone(),
|
||||
)
|
||||
.with_shared_webhook_token(Arc::clone(&calendar_webhook_token));
|
||||
let calendar_oauth = CalendarOAuthStore::new(redis.clone(), config.session_redis_db_index).ok();
|
||||
Arc::new(Self {
|
||||
db,
|
||||
redis,
|
||||
@@ -263,6 +276,9 @@ impl AppState {
|
||||
event_bus: services.event_bus,
|
||||
avatar_transcode_sem: Arc::new(tokio::sync::Semaphore::new(4)),
|
||||
strict_throttler: Arc::new(rest::throttle::StrictThrottler::new()),
|
||||
calendar_webhook_token,
|
||||
calendar,
|
||||
calendar_oauth,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,330 @@
|
||||
//! Calendar REST route mount point.
|
||||
|
||||
use axum::Router;
|
||||
|
||||
//! Calendar REST routes (`/api/calendar/oauth/{preflight,callback}` and
|
||||
//! `/api/calendar/webhook/google`) aligned with `v0.27.5`
|
||||
//! `plugins/calendar/controller.ts`.
|
||||
use crate::RouterState;
|
||||
|
||||
use crate::graphql::calendar::{
|
||||
calendar_error_to_envelope, calendar_oauth_store_from_state, calendar_service_from_state,
|
||||
};
|
||||
use crate::legacy_compat::errors::LegacyErrorEnvelope;
|
||||
use crate::rest::{
|
||||
PrincipalCookieAction, calendar_callback_origin, calendar_request_origin, domain_error_to_http_response,
|
||||
envelope_to_http_response, json_utf8_response, resolve_request_principal_with_policy,
|
||||
validate_and_build_calendar_redirect_uri,
|
||||
};
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use server_domain::calendar::oauth::{CalendarOAuthState, is_valid_oauth_state};
|
||||
use server_domain::calendar::{CalendarError, CalendarProviderName};
|
||||
use server_types::DomainError;
|
||||
pub(crate) fn router() -> Router<RouterState> {
|
||||
Router::new()
|
||||
.route("/api/calendar/oauth/preflight", post(handle_oauth_preflight))
|
||||
.route(
|
||||
"/api/calendar/oauth/callback",
|
||||
get(handle_oauth_callback_get).post(handle_oauth_callback_post),
|
||||
)
|
||||
.route("/api/calendar/webhook/google", post(handle_google_webhook))
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct PreflightBody {
|
||||
provider: Option<String>,
|
||||
redirect_uri: Option<String>,
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CallbackParams {
|
||||
code: Option<String>,
|
||||
state: Option<String>,
|
||||
}
|
||||
fn cal_err_resp(err: &CalendarError) -> Response {
|
||||
envelope_to_http_response(calendar_error_to_envelope(err))
|
||||
}
|
||||
fn with_cookies(mut resp: Response, action: &PrincipalCookieAction, https: bool) -> Response {
|
||||
action.apply_to(resp.headers_mut(), https);
|
||||
resp
|
||||
}
|
||||
fn oauth_bad_request(error_type: &str, name: &str, message: String, data: Option<serde_json::Value>) -> Response {
|
||||
envelope_to_http_response(LegacyErrorEnvelope {
|
||||
status: StatusCode::BAD_REQUEST.as_u16(),
|
||||
code: "Bad Request".to_owned(),
|
||||
error_type: error_type.to_owned(),
|
||||
name: name.to_owned(),
|
||||
message,
|
||||
data,
|
||||
})
|
||||
}
|
||||
fn missing_oauth_param(name: &str) -> Response {
|
||||
let msg = format!("Missing query parameter `{name}`.");
|
||||
oauth_bad_request(
|
||||
"BAD_REQUEST",
|
||||
"MISSING_OAUTH_QUERY_PARAMETER",
|
||||
msg,
|
||||
Some(json!({ "name": name })),
|
||||
)
|
||||
}
|
||||
fn unknown_oauth_provider(name: &str) -> Response {
|
||||
let msg = format!("Unknown authentication provider {name}.");
|
||||
oauth_bad_request(
|
||||
"INVALID_INPUT",
|
||||
"UNKNOWN_OAUTH_PROVIDER",
|
||||
msg,
|
||||
Some(json!({ "name": name })),
|
||||
)
|
||||
}
|
||||
fn safe_redirect_response(state: &RouterState, headers: &HeaderMap, raw_location: &str) -> Response {
|
||||
let cfg = state.app.config.load();
|
||||
let fallback = cfg.external_url.trim_end_matches('/');
|
||||
let req_host = headers.get(header::HOST).and_then(|v| v.to_str().ok());
|
||||
let matches_base = |target: &url::Url, base: &url::Url| {
|
||||
let bp = base.path().trim_end_matches('/');
|
||||
target.origin() == base.origin()
|
||||
&& (bp.is_empty() || target.path() == bp || target.path().starts_with(&format!("{bp}/")))
|
||||
};
|
||||
let canonical = url::Url::parse(fallback)
|
||||
.ok()
|
||||
.and_then(|ext_base| {
|
||||
let (origin, path) = calendar_request_origin(
|
||||
&cfg.external_url,
|
||||
&cfg.app_config_baseline.server.hosts,
|
||||
cfg.app_config_baseline.server.port,
|
||||
req_host,
|
||||
)?;
|
||||
let req_base = url::Url::parse(&format!("{origin}{path}")).ok()?;
|
||||
let target = req_base.join(raw_location).ok()?;
|
||||
let ok_scheme =
|
||||
matches!(target.scheme(), "http" | "https") && target.username().is_empty() && target.password().is_none();
|
||||
(ok_scheme && matches_base(&target, &ext_base)).then(|| target.to_string())
|
||||
})
|
||||
.unwrap_or_else(|| fallback.to_owned());
|
||||
let mut resp = StatusCode::FOUND.into_response();
|
||||
if let Ok(val) = HeaderValue::from_str(&canonical) {
|
||||
resp.headers_mut().insert(header::LOCATION, val);
|
||||
}
|
||||
resp
|
||||
}
|
||||
fn callback_error_message(err: &CalendarError) -> String {
|
||||
match err {
|
||||
CalendarError::ProviderRequest { status: 403, .. } => {
|
||||
"Calendar authorization failed: insufficient permissions. Please reauthorize and allow Calendar access."
|
||||
.to_owned()
|
||||
}
|
||||
CalendarError::BadRequest { message, .. } if !message.is_empty() => message.clone(),
|
||||
CalendarError::BadRequest { .. } => "Calendar authorization failed.".to_owned(),
|
||||
_ => "Calendar authorization failed. Please try again.".to_owned(),
|
||||
}
|
||||
}
|
||||
async fn handle_oauth_preflight(
|
||||
State(state): State<RouterState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<PreflightBody>,
|
||||
) -> Response {
|
||||
let https = state.app.config.load().https;
|
||||
let resolved = match resolve_request_principal_with_policy(&state, &headers, false).await {
|
||||
Ok(r) => r,
|
||||
Err(err) => return err.into_http_response(),
|
||||
};
|
||||
let cookie_action = resolved.cookie_action;
|
||||
let Some(principal) = resolved.principal else {
|
||||
return with_cookies(
|
||||
domain_error_to_http_response(&DomainError::Unauthorized("Authentication required".to_owned())),
|
||||
&cookie_action,
|
||||
https,
|
||||
);
|
||||
};
|
||||
let user = principal.into_user();
|
||||
let Some(provider_raw) = body.provider.as_deref().filter(|s| !s.trim().is_empty()) else {
|
||||
return with_cookies(missing_oauth_param("provider"), &cookie_action, https);
|
||||
};
|
||||
let Some(provider) = CalendarProviderName::parse(provider_raw) else {
|
||||
return with_cookies(unknown_oauth_provider(provider_raw), &cookie_action, https);
|
||||
};
|
||||
let svc = calendar_service_from_state(&state.app);
|
||||
match svc.is_oauth_provider_available(provider).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => return with_cookies(unknown_oauth_provider(provider_raw), &cookie_action, https),
|
||||
Err(err) => return with_cookies(cal_err_resp(&err), &cookie_action, https),
|
||||
}
|
||||
if let Err(err) = svc.assert_can_link_provider(&user.id, provider).await {
|
||||
return with_cookies(cal_err_resp(&err), &cookie_action, https);
|
||||
}
|
||||
let req_host = headers.get(header::HOST).and_then(|v| v.to_str().ok());
|
||||
let cfg = state.app.config.load();
|
||||
let canonical_redirect = match body.redirect_uri.as_deref().filter(|s| !s.is_empty()) {
|
||||
Some(raw) => match validate_and_build_calendar_redirect_uri(
|
||||
raw,
|
||||
&cfg.external_url,
|
||||
&cfg.app_config_baseline.server.hosts,
|
||||
cfg.app_config_baseline.server.port,
|
||||
req_host,
|
||||
&[],
|
||||
) {
|
||||
Ok(url) => Some(url),
|
||||
Err(err) => return with_cookies(domain_error_to_http_response(&err), &cookie_action, https),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let oauth = match calendar_oauth_store_from_state(&state.app) {
|
||||
Ok(store) => store,
|
||||
Err(err) => return with_cookies(domain_error_to_http_response(&err), &cookie_action, https),
|
||||
};
|
||||
let state_token = match oauth
|
||||
.save_oauth_state(CalendarOAuthState {
|
||||
provider,
|
||||
user_id: user.id,
|
||||
redirect_uri: canonical_redirect,
|
||||
token: None,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(t) => t,
|
||||
Err(err) => return with_cookies(domain_error_to_http_response(&err), &cookie_action, https),
|
||||
};
|
||||
let cb_origin = calendar_callback_origin(
|
||||
&cfg.external_url,
|
||||
&cfg.app_config_baseline.server.hosts,
|
||||
cfg.app_config_baseline.server.port,
|
||||
req_host,
|
||||
);
|
||||
let callback_url = svc.callback_url_for(&cb_origin);
|
||||
let resp = match svc.get_auth_url(provider, &state_token, &callback_url).await {
|
||||
Ok(auth_url) => json_utf8_response(StatusCode::OK, json!({ "url": auth_url }), true),
|
||||
Err(err) => envelope_to_http_response(calendar_error_to_envelope(&err)),
|
||||
};
|
||||
with_cookies(resp, &cookie_action, https)
|
||||
}
|
||||
async fn handle_oauth_callback_get(
|
||||
State(state): State<RouterState>,
|
||||
headers: HeaderMap,
|
||||
Query(params): Query<CallbackParams>,
|
||||
) -> Response {
|
||||
handle_oauth_callback(&state, &headers, params.code, params.state).await
|
||||
}
|
||||
async fn handle_oauth_callback_post(
|
||||
State(state): State<RouterState>,
|
||||
headers: HeaderMap,
|
||||
Json(params): Json<CallbackParams>,
|
||||
) -> Response {
|
||||
handle_oauth_callback(&state, &headers, params.code, params.state).await
|
||||
}
|
||||
async fn handle_oauth_callback(
|
||||
state: &RouterState,
|
||||
headers: &HeaderMap,
|
||||
code: Option<String>,
|
||||
state_str: Option<String>,
|
||||
) -> Response {
|
||||
let https = state.app.config.load().https;
|
||||
let cookie_action = match resolve_request_principal_with_policy(state, headers, true).await {
|
||||
Ok(r) => r.cookie_action,
|
||||
Err(err) => return err.into_http_response(),
|
||||
};
|
||||
let Some(code) = code.filter(|c| !c.is_empty()) else {
|
||||
return with_cookies(missing_oauth_param("code"), &cookie_action, https);
|
||||
};
|
||||
let Some(state_str) = state_str.filter(|s| !s.is_empty()) else {
|
||||
return with_cookies(missing_oauth_param("state"), &cookie_action, https);
|
||||
};
|
||||
if !is_valid_oauth_state(&state_str) {
|
||||
return with_cookies(missing_oauth_param("state"), &cookie_action, https);
|
||||
}
|
||||
let oauth = match calendar_oauth_store_from_state(&state.app) {
|
||||
Ok(store) => store,
|
||||
Err(err) => return with_cookies(domain_error_to_http_response(&err), &cookie_action, https),
|
||||
};
|
||||
// Non-destructive read so transient upstream failures remain retryable within TTL.
|
||||
let Some(oauth_state) = (match oauth.get_oauth_state(&state_str).await {
|
||||
Ok(val) => val,
|
||||
Err(err) => return with_cookies(domain_error_to_http_response(&err), &cookie_action, https),
|
||||
}) else {
|
||||
let msg = "OAuth state expired, please try again.".to_owned();
|
||||
return with_cookies(
|
||||
oauth_bad_request("BAD_REQUEST", "OAUTH_STATE_EXPIRED", msg, None),
|
||||
&cookie_action,
|
||||
https,
|
||||
);
|
||||
};
|
||||
let svc = calendar_service_from_state(&state.app);
|
||||
let cfg = state.app.config.load();
|
||||
let req_host = headers.get(header::HOST).and_then(|v| v.to_str().ok());
|
||||
let cb_origin = calendar_callback_origin(
|
||||
&cfg.external_url,
|
||||
&cfg.app_config_baseline.server.hosts,
|
||||
cfg.app_config_baseline.server.port,
|
||||
req_host,
|
||||
);
|
||||
let callback_url = svc.callback_url_for(&cb_origin);
|
||||
if let Err(err) = svc
|
||||
.handle_oauth_callback(oauth_state.provider, &code, &callback_url, &oauth_state.user_id)
|
||||
.await
|
||||
{
|
||||
if let Some(ref redirect_uri) = oauth_state.redirect_uri {
|
||||
let msg = callback_error_message(&err);
|
||||
let canonical = match validate_and_build_calendar_redirect_uri(
|
||||
redirect_uri,
|
||||
&cfg.external_url,
|
||||
&cfg.app_config_baseline.server.hosts,
|
||||
cfg.app_config_baseline.server.port,
|
||||
req_host,
|
||||
&[("error", msg.as_str())],
|
||||
) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return with_cookies(domain_error_to_http_response(&e), &cookie_action, https),
|
||||
};
|
||||
return with_cookies(
|
||||
safe_redirect_response(state, headers, &canonical),
|
||||
&cookie_action,
|
||||
https,
|
||||
);
|
||||
}
|
||||
return with_cookies(cal_err_resp(&err), &cookie_action, https);
|
||||
}
|
||||
if let Some(ref redirect_uri) = oauth_state.redirect_uri {
|
||||
return with_cookies(
|
||||
safe_redirect_response(state, headers, redirect_uri),
|
||||
&cookie_action,
|
||||
https,
|
||||
);
|
||||
}
|
||||
with_cookies(
|
||||
json_utf8_response(StatusCode::OK, json!({ "ok": true }), true),
|
||||
&cookie_action,
|
||||
https,
|
||||
)
|
||||
}
|
||||
async fn handle_google_webhook(State(state): State<RouterState>, headers: HeaderMap) -> Response {
|
||||
let https = state.app.config.load().https;
|
||||
let cookie_action = match resolve_request_principal_with_policy(&state, &headers, true).await {
|
||||
Ok(r) => r.cookie_action,
|
||||
Err(err) => return err.into_http_response(),
|
||||
};
|
||||
let svc = calendar_service_from_state(&state.app);
|
||||
let configs = match svc.load_configs().await {
|
||||
Ok(cfg) => cfg,
|
||||
Err(err) => return with_cookies(cal_err_resp(&err), &cookie_action, https),
|
||||
};
|
||||
if svc.webhook_address_from_config(&configs.google, "google").is_none() {
|
||||
return with_cookies(StatusCode::OK.into_response(), &cookie_action, https);
|
||||
}
|
||||
let Some(channel_id) = headers
|
||||
.get("x-goog-channel-id")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
else {
|
||||
return with_cookies(StatusCode::OK.into_response(), &cookie_action, https);
|
||||
};
|
||||
let token = headers
|
||||
.get("x-goog-channel-token")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or_default();
|
||||
if !svc.verify_webhook_token(&configs.google, token) {
|
||||
return with_cookies(StatusCode::UNAUTHORIZED.into_response(), &cookie_action, https);
|
||||
}
|
||||
match svc.handle_webhook(CalendarProviderName::Google, channel_id).await {
|
||||
Ok(()) => with_cookies(StatusCode::OK.into_response(), &cookie_action, https),
|
||||
Err(err) => with_cookies(cal_err_resp(&err), &cookie_action, https),
|
||||
}
|
||||
}
|
||||
@@ -476,24 +476,51 @@ pub(crate) async fn enforce_named_version_guard(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn build_allowed_origins(external_url: &str, server_hosts: &[String]) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if let Ok(parsed) = url::Url::parse(external_url) {
|
||||
let scheme = parsed.scheme().to_owned();
|
||||
out.push(parsed.origin().ascii_serialization());
|
||||
for host in server_hosts {
|
||||
let host = host.trim().trim_end_matches('/');
|
||||
if host.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if host.starts_with("http://") || host.starts_with("https://") {
|
||||
out.push(host.to_owned());
|
||||
} else {
|
||||
out.push(format!("{scheme}://{host}"));
|
||||
}
|
||||
}
|
||||
fn extract_hostname(raw: &str) -> Option<String> {
|
||||
let t = raw.trim();
|
||||
if t.is_empty() {
|
||||
return None;
|
||||
}
|
||||
out
|
||||
if let Some(rest) = t.strip_prefix('[') {
|
||||
let inner = rest[..rest.find(']')?].trim();
|
||||
return (!inner.is_empty()).then(|| inner.to_owned());
|
||||
}
|
||||
let h = match t.split_once(':') {
|
||||
Some((h, tail)) if !tail.contains(':') => h.trim(),
|
||||
_ => t,
|
||||
};
|
||||
(!h.is_empty()).then(|| h.to_owned())
|
||||
}
|
||||
fn convert_host_to_origin(scheme: &str, host: &str, port: Option<u16>) -> String {
|
||||
let host = host.trim().trim_end_matches('/');
|
||||
if host.starts_with("http://") || host.starts_with("https://") {
|
||||
return host.to_owned();
|
||||
}
|
||||
let is_v6 = host.parse::<std::net::Ipv6Addr>().is_ok();
|
||||
let is_local = host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok();
|
||||
let fmt_host = if is_v6 { format!("[{host}]") } else { host.to_owned() };
|
||||
match port {
|
||||
Some(p) if p != 0 && is_local => format!("{scheme}://{fmt_host}:{p}"),
|
||||
_ => format!("{scheme}://{fmt_host}"),
|
||||
}
|
||||
}
|
||||
pub(crate) fn build_allowed_origins_with_port(ext: &str, hosts: &[String], port: Option<u16>) -> Vec<String> {
|
||||
let Ok(parsed) = url::Url::parse(ext) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let scheme = parsed.scheme();
|
||||
std::iter::once(parsed.origin().ascii_serialization())
|
||||
.chain(
|
||||
hosts
|
||||
.iter()
|
||||
.map(|h| h.trim().trim_end_matches('/'))
|
||||
.filter(|h| !h.is_empty())
|
||||
.map(|h| convert_host_to_origin(scheme, h, port)),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
pub(crate) fn build_allowed_origins(external_url: &str, server_hosts: &[String]) -> Vec<String> {
|
||||
build_allowed_origins_with_port(external_url, server_hosts, None)
|
||||
}
|
||||
|
||||
fn parse_http_url_with_base(input: &str, base_url: &str) -> Result<url::Url, DomainError> {
|
||||
@@ -532,6 +559,75 @@ fn matches_trusted_redirect_domain(url: &url::Url) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn calendar_request_origin(
|
||||
external_url: &str,
|
||||
server_hosts: &[String],
|
||||
server_port: u16,
|
||||
request_host: Option<&str>,
|
||||
) -> Option<(String, String)> {
|
||||
let ext = url::Url::parse(external_url).ok()?;
|
||||
let path = ext.path().trim_end_matches('/').to_owned();
|
||||
let origin = if !server_hosts.is_empty()
|
||||
&& let Some(req_hostname) = request_host.and_then(extract_hostname)
|
||||
&& let Some(matched) = server_hosts
|
||||
.iter()
|
||||
.map(|h| h.trim())
|
||||
.find(|h| !h.is_empty() && h.eq_ignore_ascii_case(&req_hostname))
|
||||
{
|
||||
convert_host_to_origin(ext.scheme(), matched, Some(server_port))
|
||||
} else {
|
||||
ext.origin().ascii_serialization()
|
||||
};
|
||||
Some((origin, path))
|
||||
}
|
||||
|
||||
pub(crate) fn calendar_callback_origin(
|
||||
external_url: &str,
|
||||
server_hosts: &[String],
|
||||
server_port: u16,
|
||||
request_host: Option<&str>,
|
||||
) -> String {
|
||||
calendar_request_origin(external_url, server_hosts, server_port, request_host)
|
||||
.map(|(origin, _)| origin)
|
||||
.unwrap_or_else(|| external_url.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_and_build_calendar_redirect_uri(
|
||||
raw: &str,
|
||||
external_url: &str,
|
||||
server_hosts: &[String],
|
||||
server_port: u16,
|
||||
request_host: Option<&str>,
|
||||
extra_query: &[(&str, &str)],
|
||||
) -> Result<String, DomainError> {
|
||||
let forbid = || DomainError::Forbidden("URL is not allowed".to_owned());
|
||||
if raw.is_empty() {
|
||||
return Err(forbid());
|
||||
}
|
||||
let (req_origin, _) =
|
||||
calendar_request_origin(external_url, server_hosts, server_port, request_host).ok_or_else(forbid)?;
|
||||
let base = url::Url::parse(&req_origin).map_err(|_| forbid())?;
|
||||
let mut parsed = base.join(raw).map_err(|_| forbid())?;
|
||||
let allowed = build_allowed_origins_with_port(external_url, server_hosts, Some(server_port));
|
||||
if !matches!(parsed.scheme(), "http" | "https")
|
||||
|| !parsed.username().is_empty()
|
||||
|| parsed.password().is_some()
|
||||
|| (!has_allowed_origin(&parsed, &allowed) && !matches_trusted_redirect_domain(&parsed))
|
||||
{
|
||||
return Err(forbid());
|
||||
}
|
||||
if !extra_query.is_empty() {
|
||||
let mut kept: Vec<(String, String)> = parsed
|
||||
.query_pairs()
|
||||
.filter(|(k, _)| !extra_query.iter().any(|(ek, _)| ek == k))
|
||||
.map(|(k, v)| (k.into_owned(), v.into_owned()))
|
||||
.collect();
|
||||
kept.extend(extra_query.iter().map(|&(k, v)| (k.to_owned(), v.to_owned())));
|
||||
parsed.query_pairs_mut().clear().extend_pairs(kept);
|
||||
}
|
||||
Ok(parsed.into())
|
||||
}
|
||||
|
||||
pub fn validate_and_build_magic_link_callback_url(
|
||||
callback_url: &str,
|
||||
external_url: &str,
|
||||
|
||||
@@ -0,0 +1,907 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use http::{Request, StatusCode};
|
||||
use serde_json::Value;
|
||||
use server_db::{DbConfig, ServerDb};
|
||||
use server_http::{AppState, RuntimeConfig, build_router};
|
||||
use server_spi::CommunityExtension;
|
||||
use server_types::{DeploymentMode, ServerRole};
|
||||
use test_db_harness::{pg::PgCluster, redis::TestRedis};
|
||||
use tower::ServiceExt as _;
|
||||
use uuid::Uuid;
|
||||
|
||||
fn test_runtime() -> tokio::runtime::Runtime {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("build tokio runtime")
|
||||
}
|
||||
|
||||
fn lease_test_db(cluster: &PgCluster) -> test_db_harness::pg::DbLease {
|
||||
let migrations_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
|
||||
let migrations = test_db_harness::migrations::MigrationSet::load(&migrations_dir).expect("load prisma migrations");
|
||||
let template = cluster.ensure_template(&migrations).expect("ensure migrated template");
|
||||
cluster
|
||||
.lease(&template, test_db_harness::pg::DEFAULT_LEASE_TTL)
|
||||
.expect("lease test database")
|
||||
}
|
||||
|
||||
async fn setup_http_state(db_url: &str, redis_url: &str) -> (Arc<AppState>, axum::Router) {
|
||||
let mut db_cfg = DbConfig::new(db_url);
|
||||
db_cfg.max_connections = 4;
|
||||
let db = ServerDb::connect(db_cfg).await.expect("connect db");
|
||||
let redis = redis::Client::open(redis_url).expect("open redis");
|
||||
let cfg = RuntimeConfig {
|
||||
deployment_mode: DeploymentMode::Selfhosted,
|
||||
role: ServerRole::Allinone,
|
||||
dev_mode: false,
|
||||
..RuntimeConfig::default()
|
||||
};
|
||||
let state = AppState::new(db, Some(redis), cfg, Arc::new(CommunityExtension::new()));
|
||||
let router = build_router(Arc::clone(&state));
|
||||
(state, router)
|
||||
}
|
||||
|
||||
async fn read_json(resp: axum::response::Response) -> Value {
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
|
||||
.await
|
||||
.expect("read body");
|
||||
serde_json::from_slice(&bytes).expect("parse json")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendar_rest_webhook_and_oauth_callback_validation() {
|
||||
let cluster = PgCluster::from_env_or_docker().expect("pg cluster");
|
||||
let lease = lease_test_db(&cluster);
|
||||
let db_url = lease.url().to_owned();
|
||||
let redis = TestRedis::from_env_or_docker().expect("test redis");
|
||||
let redis_url = redis.url().to_owned();
|
||||
let rt = test_runtime();
|
||||
rt.block_on(async {
|
||||
let (state, router) = setup_http_state(&db_url, &redis_url).await;
|
||||
|
||||
sqlx::query(
|
||||
r#"INSERT INTO app_configs (id, value, created_at, updated_at)
|
||||
VALUES (
|
||||
'calendar.google',
|
||||
'{"enabled":true,"clientId":"cid","clientSecret":"csec","externalWebhookUrl":"https://hook.example.com","webhookVerificationToken":"expected-secret"}'::jsonb,
|
||||
clock_timestamp(),
|
||||
clock_timestamp()
|
||||
)"#,
|
||||
)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.expect("seed google calendar config");
|
||||
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri("/api/calendar/oauth/callback")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
let missing_body = read_json(resp).await;
|
||||
assert_eq!(missing_body["name"], "MISSING_OAUTH_QUERY_PARAMETER");
|
||||
assert_eq!(missing_body["type"], "BAD_REQUEST");
|
||||
assert_eq!(missing_body["message"], "Missing query parameter `code`.");
|
||||
assert_eq!(missing_body["data"]["name"], "code");
|
||||
|
||||
let unknown_state = Uuid::new_v4().to_string();
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=abc&state={unknown_state}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
let expired_body = read_json(resp).await;
|
||||
assert_eq!(expired_body["name"], "OAUTH_STATE_EXPIRED");
|
||||
assert_eq!(expired_body["type"], "BAD_REQUEST");
|
||||
assert_eq!(expired_body["message"], "OAuth state expired, please try again.");
|
||||
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/webhook/google")
|
||||
.header("x-goog-channel-id", "chan-1")
|
||||
.header("x-goog-channel-token", "wrong-secret")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/webhook/google")
|
||||
.header("x-goog-channel-id", "chan-1")
|
||||
.header("x-goog-channel-token", "expected-secret")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
// When webhookVerificationToken is not configured, AppState shares one generated token across requests.
|
||||
sqlx::query(
|
||||
r#"UPDATE app_configs
|
||||
SET value = '{"enabled":true,"clientId":"cid","clientSecret":"csec","externalWebhookUrl":"https://hook.example.com"}'::jsonb
|
||||
WHERE id = 'calendar.google'"#,
|
||||
)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.expect("clear explicit webhook token");
|
||||
let generated_token = {
|
||||
let mut guard = state.calendar_webhook_token.lock().unwrap();
|
||||
let tok = Uuid::new_v4().to_string();
|
||||
*guard = Some(tok.clone());
|
||||
tok
|
||||
};
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/webhook/google")
|
||||
.header("x-goog-channel-id", "chan-1")
|
||||
.header("x-goog-channel-token", &generated_token)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
// @Public() callback and webhook with an unsupported client version session cookie
|
||||
// must clear auth cookies and continue anonymously instead of returning 403.
|
||||
let user_id = Uuid::new_v4().to_string();
|
||||
sqlx::query(
|
||||
r#"INSERT INTO users (id, name, email, registered, disabled, email_verified, created_at)
|
||||
VALUES ($1, 'Cal User', 'cal-ver@example.com', true, false, clock_timestamp(), clock_timestamp())"#,
|
||||
)
|
||||
.bind(&user_id)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.expect("insert user");
|
||||
let session_id = Uuid::new_v4().to_string();
|
||||
sqlx::query("INSERT INTO multiple_users_sessions (id, created_at) VALUES ($1, clock_timestamp())")
|
||||
.bind(&session_id)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.expect("insert multiple_users_session");
|
||||
sqlx::query(
|
||||
r#"INSERT INTO user_sessions (id, session_id, user_id, expires_at, created_at)
|
||||
VALUES ($1, $2, $3, clock_timestamp() + interval '1 day', clock_timestamp())"#,
|
||||
)
|
||||
.bind(Uuid::new_v4().to_string())
|
||||
.bind(&session_id)
|
||||
.bind(&user_id)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.expect("insert user_session");
|
||||
sqlx::query(
|
||||
r#"INSERT INTO app_configs (id, value, created_at, updated_at)
|
||||
VALUES ('client.versionControl', '{"enabled":true,"requiredVersion":"99.0.0"}'::jsonb, clock_timestamp(), clock_timestamp())
|
||||
ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value, updated_at = clock_timestamp()"#,
|
||||
)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.expect("seed versionControl");
|
||||
state.app_config.invalidate_cache();
|
||||
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/webhook/google")
|
||||
.header("cookie", format!("affine_session={session_id}"))
|
||||
.header("x-affine-version", "0.1.0")
|
||||
.header("x-goog-channel-id", "chan-1")
|
||||
.header("x-goog-channel-token", &generated_token)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let set_cookies: Vec<String> = resp
|
||||
.headers()
|
||||
.get_all(axum::http::header::SET_COOKIE)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok().map(str::to_owned))
|
||||
.collect();
|
||||
assert!(set_cookies.iter().any(|c| c.starts_with("affine_session=;")));
|
||||
assert!(set_cookies.iter().any(|c| c.starts_with("affine_user_id=;")));
|
||||
assert!(set_cookies.iter().any(|c| c.starts_with("affine_csrf_token=;")));
|
||||
|
||||
// Disallowed redirect_uri on provider failure returns 403 ACTION_FORBIDDEN (not 302).
|
||||
let oauth_store = state.calendar_oauth.as_ref().expect("oauth store");
|
||||
let bad_redir_token = oauth_store
|
||||
.save_oauth_state(server_domain::calendar::oauth::CalendarOAuthState {
|
||||
provider: server_domain::calendar::CalendarProviderName::Google,
|
||||
user_id: user_id.clone(),
|
||||
redirect_uri: Some("https://evil.example.net/steal".to_owned()),
|
||||
token: None,
|
||||
})
|
||||
.await
|
||||
.expect("save state");
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={bad_redir_token}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
|
||||
let forbidden_body = read_json(resp).await;
|
||||
assert_eq!(forbidden_body["name"], "ACTION_FORBIDDEN");
|
||||
assert_eq!(forbidden_body["type"], "ACTION_FORBIDDEN");
|
||||
|
||||
// Relative redirect_uri with existing query params (?keep=1&error=old) replaces old error and preserves keep=1.
|
||||
let rel_redir_token = oauth_store
|
||||
.save_oauth_state(server_domain::calendar::oauth::CalendarOAuthState {
|
||||
provider: server_domain::calendar::CalendarProviderName::Google,
|
||||
user_id: user_id.clone(),
|
||||
redirect_uri: Some("/calendar?keep=1&error=old".to_owned()),
|
||||
token: None,
|
||||
})
|
||||
.await
|
||||
.expect("save rel state");
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={rel_redir_token}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||
let rel_loc = resp.headers().get(axum::http::header::LOCATION).unwrap().to_str().unwrap();
|
||||
let parsed_rel = url::Url::parse(rel_loc).expect("parse rel location");
|
||||
let rel_pairs: Vec<(String, String)> = parsed_rel
|
||||
.query_pairs()
|
||||
.map(|(k, v)| (k.into_owned(), v.into_owned()))
|
||||
.collect();
|
||||
assert_eq!(parsed_rel.path(), "/calendar");
|
||||
assert_eq!(rel_pairs.iter().filter(|(k, _)| k == "keep").count(), 1);
|
||||
assert_eq!(
|
||||
rel_pairs.iter().find(|(k, _)| k == "keep").map(|(_, v)| v.as_str()),
|
||||
Some("1")
|
||||
);
|
||||
let err_vals: Vec<&str> = rel_pairs
|
||||
.iter()
|
||||
.filter(|(k, _)| k == "error")
|
||||
.map(|(_, v)| v.as_str())
|
||||
.collect();
|
||||
assert_eq!(err_vals.len(), 1, "expected single error param, got {rel_loc}");
|
||||
assert_ne!(err_vals[0], "old");
|
||||
|
||||
// Trusted external domain (affine.pro) passes canonical check and downgrades via safe_redirect_response to baseUrl.
|
||||
let trusted_ext_token = oauth_store
|
||||
.save_oauth_state(server_domain::calendar::oauth::CalendarOAuthState {
|
||||
provider: server_domain::calendar::CalendarProviderName::Google,
|
||||
user_id: user_id.clone(),
|
||||
redirect_uri: Some("https://affine.pro/cb".to_owned()),
|
||||
token: None,
|
||||
})
|
||||
.await
|
||||
.expect("save trusted ext state");
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={trusted_ext_token}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||
assert_eq!(
|
||||
resp.headers().get(axum::http::header::LOCATION).unwrap(),
|
||||
"http://localhost:3010"
|
||||
);
|
||||
|
||||
// Subpath deployment (/app): same-origin path outside /app falls back to full external_url (/app).
|
||||
let mut subpath_cfg = (**state.config.load()).clone();
|
||||
subpath_cfg.external_url = "https://app.example.com/app".to_owned();
|
||||
state.config.store(Arc::new(subpath_cfg));
|
||||
|
||||
let outside_token = oauth_store
|
||||
.save_oauth_state(server_domain::calendar::oauth::CalendarOAuthState {
|
||||
provider: server_domain::calendar::CalendarProviderName::Google,
|
||||
user_id: user_id.clone(),
|
||||
redirect_uri: Some("https://app.example.com/outside".to_owned()),
|
||||
token: None,
|
||||
})
|
||||
.await
|
||||
.expect("save outside state");
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={outside_token}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||
assert_eq!(
|
||||
resp.headers().get(axum::http::header::LOCATION).unwrap(),
|
||||
"https://app.example.com/app"
|
||||
);
|
||||
|
||||
let inside_token = oauth_store
|
||||
.save_oauth_state(server_domain::calendar::oauth::CalendarOAuthState {
|
||||
provider: server_domain::calendar::CalendarProviderName::Google,
|
||||
user_id: user_id.clone(),
|
||||
redirect_uri: Some("https://app.example.com/app/calendar".to_owned()),
|
||||
token: None,
|
||||
})
|
||||
.await
|
||||
.expect("save inside state");
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={inside_token}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||
let inside_loc = resp.headers().get(axum::http::header::LOCATION).unwrap().to_str().unwrap();
|
||||
assert!(
|
||||
inside_loc.starts_with("https://app.example.com/app/calendar?error="),
|
||||
"unexpected subpath redirect location: {inside_loc}"
|
||||
);
|
||||
|
||||
// Round 6: subpath deployment (http://localhost:3010/app) resolves ?view=calendar against origin (not /app),
|
||||
// allows same-origin protocol-relative //localhost:3010/app/cb, and rejects //evil.example/cb with 403.
|
||||
let mut local_subpath_cfg = (**state.config.load()).clone();
|
||||
local_subpath_cfg.external_url = "http://localhost:3010/app".to_owned();
|
||||
state.config.store(Arc::new(local_subpath_cfg));
|
||||
let session = state
|
||||
.auth
|
||||
.issue_cookie_session_for_user(&user_id)
|
||||
.await
|
||||
.expect("issue cookie session");
|
||||
let cookie_hdr = format!("affine_session={}", session.session_id);
|
||||
|
||||
// 1) REST preflight with ?view=calendar stores http://localhost:3010/?view=calendar, callback failure falls back to /app.
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/oauth/preflight")
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.header(axum::http::header::COOKIE, &cookie_hdr)
|
||||
.header("x-affine-version", "99.0.0")
|
||||
.body(Body::from(r#"{"provider":"google","redirect_uri":"?view=calendar"}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let pf_status = resp.status();
|
||||
let pf_body = read_json(resp).await;
|
||||
assert_eq!(pf_status, StatusCode::OK, "preflight failed: {pf_body}");
|
||||
let auth_url = url::Url::parse(pf_body["url"].as_str().unwrap()).expect("parse auth url");
|
||||
let state_tok = auth_url
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "state")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.expect("state query param");
|
||||
let saved_state = oauth_store
|
||||
.get_oauth_state(&state_tok)
|
||||
.await
|
||||
.expect("get saved oauth state")
|
||||
.expect("saved oauth state exists");
|
||||
assert_eq!(
|
||||
saved_state.redirect_uri.as_deref(),
|
||||
Some("http://localhost:3010/?view=calendar")
|
||||
);
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={state_tok}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||
assert_eq!(
|
||||
resp.headers().get(axum::http::header::LOCATION).unwrap(),
|
||||
"http://localhost:3010/app"
|
||||
);
|
||||
|
||||
// 2) GraphQL linkCalendarAccount with ?view=calendar stores identical origin-resolved canonical URI.
|
||||
let gql_schema = server_http::graphql::build_schema(Arc::clone(&state));
|
||||
let gql_resp = gql_schema
|
||||
.execute(
|
||||
async_graphql::Request::new(
|
||||
r#"mutation { linkCalendarAccount(input: { provider: Google, redirectUri: "?view=calendar" }) }"#,
|
||||
)
|
||||
.data(server_http::graphql::AuthenticatedUser {
|
||||
user_id: user_id.clone(),
|
||||
user: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert!(gql_resp.errors.is_empty(), "gql errors: {:?}", gql_resp.errors);
|
||||
let gql_json = serde_json::to_value(&gql_resp.data).unwrap();
|
||||
let gql_auth_url = url::Url::parse(gql_json["linkCalendarAccount"].as_str().unwrap()).unwrap();
|
||||
let gql_state_tok = gql_auth_url
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "state")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.unwrap();
|
||||
let gql_saved = oauth_store.get_oauth_state(&gql_state_tok).await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
gql_saved.redirect_uri.as_deref(),
|
||||
Some("http://localhost:3010/?view=calendar")
|
||||
);
|
||||
|
||||
// 3) Same-origin protocol-relative //localhost:3010/app/cb passes preflight and redirects with ?error=.
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/oauth/preflight")
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.header(axum::http::header::COOKIE, &cookie_hdr)
|
||||
.header("x-affine-version", "99.0.0")
|
||||
.body(Body::from(
|
||||
r#"{"provider":"google","redirect_uri":"//localhost:3010/app/cb"}"#,
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let pf_rel = read_json(resp).await;
|
||||
let rel_state_tok = url::Url::parse(pf_rel["url"].as_str().unwrap())
|
||||
.unwrap()
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "state")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.unwrap();
|
||||
let rel_saved = oauth_store.get_oauth_state(&rel_state_tok).await.unwrap().unwrap();
|
||||
assert_eq!(rel_saved.redirect_uri.as_deref(), Some("http://localhost:3010/app/cb"));
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={rel_state_tok}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||
let proto_rel_loc = resp.headers().get(axum::http::header::LOCATION).unwrap().to_str().unwrap();
|
||||
assert!(
|
||||
proto_rel_loc.starts_with("http://localhost:3010/app/cb?error="),
|
||||
"unexpected protocol-relative location: {proto_rel_loc}"
|
||||
);
|
||||
|
||||
// 4) Untrusted protocol-relative //evil.example/cb returns 403 ACTION_FORBIDDEN.
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/oauth/preflight")
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.header(axum::http::header::COOKIE, &cookie_hdr)
|
||||
.header("x-affine-version", "99.0.0")
|
||||
.body(Body::from(r#"{"provider":"google","redirect_uri":"//evil.example/cb"}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
|
||||
assert_eq!(read_json(resp).await["name"], "ACTION_FORBIDDEN");
|
||||
|
||||
// 5) Multi-host Host: app2.affine.local:3010 strips :port to match server.hosts, stores http://app2.affine.local/cb,
|
||||
// and callback safe_redirect_response falls back 302 to primary baseUrl (http://localhost:3010/app).
|
||||
let mut multi_host_cfg = (**state.config.load()).clone();
|
||||
multi_host_cfg.app_config_baseline.server.hosts = vec!["app2.affine.local".to_owned()];
|
||||
multi_host_cfg.app_config_baseline.server.port = 3010;
|
||||
state.config.store(Arc::new(multi_host_cfg));
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/oauth/preflight")
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.header(axum::http::header::COOKIE, &cookie_hdr)
|
||||
.header(axum::http::header::HOST, "app2.affine.local:3010")
|
||||
.header("x-affine-version", "99.0.0")
|
||||
.body(Body::from(r#"{"provider":"google","redirect_uri":"/cb"}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let mh_body = read_json(resp).await;
|
||||
let mh_auth_url = url::Url::parse(mh_body["url"].as_str().unwrap()).unwrap();
|
||||
let mh_cb_uri = mh_auth_url
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "redirect_uri")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.unwrap();
|
||||
assert_eq!(mh_cb_uri, "http://app2.affine.local/api/calendar/oauth/callback");
|
||||
let mh_state_tok = mh_auth_url
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "state")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.unwrap();
|
||||
let mh_saved = oauth_store.get_oauth_state(&mh_state_tok).await.unwrap().unwrap();
|
||||
assert_eq!(mh_saved.redirect_uri.as_deref(), Some("http://app2.affine.local/cb"));
|
||||
let mut gql_headers = axum::http::HeaderMap::new();
|
||||
gql_headers.insert(
|
||||
axum::http::header::HOST,
|
||||
axum::http::HeaderValue::from_static("app2.affine.local:3010"),
|
||||
);
|
||||
let gql_mh = gql_schema
|
||||
.execute(
|
||||
async_graphql::Request::new(r#"mutation { linkCalendarAccount(input: { provider: Google }) }"#)
|
||||
.data(server_http::graphql::AuthenticatedUser {
|
||||
user_id: user_id.clone(),
|
||||
user: None,
|
||||
})
|
||||
.data(gql_headers),
|
||||
)
|
||||
.await;
|
||||
assert!(gql_mh.errors.is_empty(), "gql mh errors: {:?}", gql_mh.errors);
|
||||
let gql_mh_url = url::Url::parse(
|
||||
serde_json::to_value(&gql_mh.data).unwrap()["linkCalendarAccount"]
|
||||
.as_str()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
gql_mh_url
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "redirect_uri")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.as_deref(),
|
||||
Some("http://app2.affine.local/api/calendar/oauth/callback")
|
||||
);
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={mh_state_tok}"))
|
||||
.header(axum::http::header::HOST, "app2.affine.local:3010")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||
assert_eq!(
|
||||
resp.headers().get(axum::http::header::LOCATION).unwrap(),
|
||||
"http://localhost:3010/app"
|
||||
);
|
||||
|
||||
// 6) Omitted and empty redirect_uri store None (JSON response on callback), while single-space " "
|
||||
// is truthy like JS and resolves to requestOrigin + "/" (302 redirect on callback).
|
||||
let mut root_cfg = (**state.config.load()).clone();
|
||||
root_cfg.external_url = "http://localhost:3010".to_owned();
|
||||
root_cfg.app_config_baseline.server.hosts.clear();
|
||||
state.config.store(Arc::new(root_cfg));
|
||||
for (body_json, expected_uri, expect_redirect) in [
|
||||
(r#"{"provider":"google"}"#, None, false),
|
||||
(r#"{"provider":"google","redirect_uri":""}"#, None, false),
|
||||
(
|
||||
r#"{"provider":"google","redirect_uri":" "}"#,
|
||||
Some("http://localhost:3010/"),
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/oauth/preflight")
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.header(axum::http::header::COOKIE, &cookie_hdr)
|
||||
.header("x-affine-version", "99.0.0")
|
||||
.body(Body::from(body_json))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let tok = url::Url::parse(read_json(resp).await["url"].as_str().unwrap())
|
||||
.unwrap()
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "state")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.unwrap();
|
||||
let st = oauth_store.get_oauth_state(&tok).await.unwrap().unwrap();
|
||||
assert_eq!(st.redirect_uri.as_deref(), expected_uri);
|
||||
let cb = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=bad&state={tok}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
if expect_redirect {
|
||||
assert_eq!(cb.status(), StatusCode::FOUND);
|
||||
let loc = cb.headers().get(axum::http::header::LOCATION).unwrap().to_str().unwrap();
|
||||
assert!(loc.starts_with("http://localhost:3010/?error="), "loc: {loc}");
|
||||
} else {
|
||||
assert_ne!(cb.status(), StatusCode::FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
state.db.pool().close().await;
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendar_oauth_success_callback_redirect_and_token_exchange() {
|
||||
let cluster = PgCluster::from_env_or_docker().expect("pg cluster");
|
||||
let lease = lease_test_db(&cluster);
|
||||
let db_url = lease.url().to_owned();
|
||||
let redis = TestRedis::from_env_or_docker().expect("test redis");
|
||||
let redis_url = redis.url().to_owned();
|
||||
let rt = test_runtime();
|
||||
rt.block_on(async {
|
||||
let seen_redirect_uris: Arc<std::sync::Mutex<Vec<String>>> = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let seen_for_srv = Arc::clone(&seen_redirect_uris);
|
||||
let mock_google = axum::Router::new()
|
||||
.route(
|
||||
"/token",
|
||||
axum::routing::post(move |body: String| {
|
||||
let seen = Arc::clone(&seen_for_srv);
|
||||
async move {
|
||||
if let Some(uri) = url::Url::parse(&format!("http://x/?{body}")).ok().and_then(|u| {
|
||||
u.query_pairs()
|
||||
.find(|(k, _)| k == "redirect_uri")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
}) {
|
||||
seen.lock().unwrap().push(uri);
|
||||
}
|
||||
axum::Json(serde_json::json!({
|
||||
"access_token": "at-ok",
|
||||
"refresh_token": "rt-ok",
|
||||
"expires_in": 3600,
|
||||
"token_type": "Bearer",
|
||||
"scope": "https://www.googleapis.com/auth/calendar.readonly"
|
||||
}))
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/userinfo",
|
||||
axum::routing::get(|| async {
|
||||
axum::Json(serde_json::json!({
|
||||
"id": "goog-user-1",
|
||||
"email": "goog@example.com",
|
||||
"name": "Google User"
|
||||
}))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/users/me/calendarList",
|
||||
axum::routing::get(|| async { axum::Json(serde_json::json!({ "items": [] })) }),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind mock google");
|
||||
let mock_addr = listener.local_addr().expect("mock google addr");
|
||||
let mock_srv = tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, mock_google).await;
|
||||
});
|
||||
|
||||
let mut db_cfg = DbConfig::new(&db_url);
|
||||
db_cfg.max_connections = 4;
|
||||
let db = ServerDb::connect(db_cfg).await.expect("connect db");
|
||||
let redis_client = redis::Client::open(redis_url.as_str()).expect("open redis");
|
||||
let mut cfg = RuntimeConfig {
|
||||
deployment_mode: DeploymentMode::Selfhosted,
|
||||
role: ServerRole::Allinone,
|
||||
dev_mode: false,
|
||||
external_url: "http://localhost:3010/app".to_owned(),
|
||||
..RuntimeConfig::default()
|
||||
};
|
||||
cfg.app_config_baseline.server.hosts = vec!["app2.affine.local".to_owned()];
|
||||
cfg.app_config_baseline.server.port = 3010;
|
||||
let mut state = AppState::new(db.clone(), Some(redis_client), cfg, Arc::new(CommunityExtension::new()));
|
||||
let google_override = server_domain::calendar::google::CalendarGoogleConfig {
|
||||
enabled: true,
|
||||
allow_new_accounts: Some(true),
|
||||
client_id: "cid".to_owned(),
|
||||
client_secret: "csec".to_owned(),
|
||||
token_endpoint_override: Some(format!("http://{mock_addr}/token")),
|
||||
userinfo_endpoint_override: Some(format!("http://{mock_addr}/userinfo")),
|
||||
api_base_override: Some(format!("http://{mock_addr}")),
|
||||
..Default::default()
|
||||
};
|
||||
Arc::get_mut(&mut state).expect("unique app state").calendar = server_domain::calendar::CalendarService::new(
|
||||
db,
|
||||
"ephemeral-test-calendar-key".to_owned(),
|
||||
"http://localhost:3010/app".to_owned(),
|
||||
)
|
||||
.with_config_override(server_domain::calendar::EffectiveCalendarConfigs {
|
||||
google: google_override,
|
||||
caldav: Default::default(),
|
||||
});
|
||||
let router = build_router(Arc::clone(&state));
|
||||
let oauth_store = state.calendar_oauth.as_ref().expect("calendar oauth store");
|
||||
|
||||
let user_id = Uuid::new_v4().to_string();
|
||||
sqlx::query(
|
||||
r#"INSERT INTO users (id, name, email, registered, disabled, email_verified, created_at)
|
||||
VALUES ($1, 'Cal Ok', 'cal-ok@example.com', true, false, clock_timestamp(), clock_timestamp())"#,
|
||||
)
|
||||
.bind(&user_id)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.expect("insert user");
|
||||
let session = state
|
||||
.auth
|
||||
.issue_cookie_session_for_user(&user_id)
|
||||
.await
|
||||
.expect("issue session");
|
||||
let cookie_hdr = format!("affine_session={}", session.session_id);
|
||||
|
||||
// 1) Multi-host subpath callback exchanges token using http://app2.affine.local/api/calendar/oauth/callback.
|
||||
let resp = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/oauth/preflight")
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.header(axum::http::header::COOKIE, &cookie_hdr)
|
||||
.header(axum::http::header::HOST, "app2.affine.local:3010")
|
||||
.body(Body::from(r#"{"provider":"google"}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let mh_tok = url::Url::parse(read_json(resp).await["url"].as_str().unwrap())
|
||||
.unwrap()
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "state")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.unwrap();
|
||||
let cb = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=good-1&state={mh_tok}"))
|
||||
.header(axum::http::header::HOST, "app2.affine.local:3010")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(cb.status(), StatusCode::OK);
|
||||
assert_eq!(read_json(cb).await, serde_json::json!({ "ok": true }));
|
||||
assert_eq!(
|
||||
seen_redirect_uris.lock().unwrap().as_slice(),
|
||||
&["http://app2.affine.local/api/calendar/oauth/callback"]
|
||||
);
|
||||
|
||||
// 2) Root deployment: omitted & "" -> 200 {"ok":true}; " " & "\t" -> stored Some("http://localhost:3010/") and 302 Location: http://localhost:3010/ (no error).
|
||||
let mut root_cfg = (**state.config.load()).clone();
|
||||
root_cfg.external_url = "http://localhost:3010".to_owned();
|
||||
root_cfg.app_config_baseline.server.hosts.clear();
|
||||
state.config.store(Arc::new(root_cfg));
|
||||
for (body_json, expected_uri, expect_302) in [
|
||||
(r#"{"provider":"google"}"#, None, false),
|
||||
(r#"{"provider":"google","redirect_uri":""}"#, None, false),
|
||||
(
|
||||
r#"{"provider":"google","redirect_uri":" "}"#,
|
||||
Some("http://localhost:3010/"),
|
||||
true,
|
||||
),
|
||||
(
|
||||
r#"{"provider":"google","redirect_uri":"\t"}"#,
|
||||
Some("http://localhost:3010/"),
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let pf = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/calendar/oauth/preflight")
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.header(axum::http::header::COOKIE, &cookie_hdr)
|
||||
.body(Body::from(body_json))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pf.status(), StatusCode::OK, "preflight failed for {body_json}");
|
||||
let tok = url::Url::parse(read_json(pf).await["url"].as_str().unwrap())
|
||||
.unwrap()
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "state")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.unwrap();
|
||||
let st = oauth_store.get_oauth_state(&tok).await.unwrap().unwrap();
|
||||
assert_eq!(st.redirect_uri.as_deref(), expected_uri, "for {body_json}");
|
||||
let cb = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("/api/calendar/oauth/callback?code=good&state={tok}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
if expect_302 {
|
||||
assert_eq!(cb.status(), StatusCode::FOUND, "for {body_json}");
|
||||
assert_eq!(
|
||||
cb.headers().get(axum::http::header::LOCATION).unwrap(),
|
||||
"http://localhost:3010/",
|
||||
"for {body_json}"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(cb.status(), StatusCode::OK, "for {body_json}");
|
||||
assert_eq!(read_json(cb).await, serde_json::json!({ "ok": true }));
|
||||
}
|
||||
}
|
||||
|
||||
mock_srv.abort();
|
||||
state.db.pool().close().await;
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user