1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use async_graphql::{Context, MergedObject, Object, ID};

use crate::graphql::{
    model::{
        Anonymous, BrowserSession, CompatSession, Node, NodeType, OAuth2Client, OAuth2Session,
        SiteConfig, User, UserEmail,
    },
    state::ContextExt,
};

mod session;
mod upstream_oauth;
mod user;
mod viewer;

use self::{
    session::SessionQuery, upstream_oauth::UpstreamOAuthQuery, user::UserQuery, viewer::ViewerQuery,
};

/// The query root of the GraphQL interface.
#[derive(Default, MergedObject)]
pub struct Query(
    BaseQuery,
    UserQuery,
    UpstreamOAuthQuery,
    SessionQuery,
    ViewerQuery,
);

impl Query {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

#[derive(Default)]
struct BaseQuery;

// TODO: move the rest of the queries in separate modules
#[Object]
impl BaseQuery {
    /// Get the current logged in browser session
    #[graphql(deprecation = "Use `viewerSession` instead.")]
    async fn current_browser_session(
        &self,
        ctx: &Context<'_>,
    ) -> Result<Option<BrowserSession>, async_graphql::Error> {
        let requester = ctx.requester();
        Ok(requester
            .browser_session()
            .cloned()
            .map(BrowserSession::from))
    }

    /// Get the current logged in user
    #[graphql(deprecation = "Use `viewer` instead.")]
    async fn current_user(&self, ctx: &Context<'_>) -> Result<Option<User>, async_graphql::Error> {
        let requester = ctx.requester();
        Ok(requester.user().cloned().map(User::from))
    }

    /// Fetch an OAuth 2.0 client by its ID.
    async fn oauth2_client(
        &self,
        ctx: &Context<'_>,
        id: ID,
    ) -> Result<Option<OAuth2Client>, async_graphql::Error> {
        let state = ctx.state();
        let id = NodeType::OAuth2Client.extract_ulid(&id)?;

        let mut repo = state.repository().await?;
        let client = repo.oauth2_client().lookup(id).await?;
        repo.cancel().await?;

        Ok(client.map(OAuth2Client))
    }

    /// Fetch a browser session by its ID.
    async fn browser_session(
        &self,
        ctx: &Context<'_>,
        id: ID,
    ) -> Result<Option<BrowserSession>, async_graphql::Error> {
        let state = ctx.state();
        let id = NodeType::BrowserSession.extract_ulid(&id)?;
        let requester = ctx.requester();

        let mut repo = state.repository().await?;
        let browser_session = repo.browser_session().lookup(id).await?;
        repo.cancel().await?;

        let Some(browser_session) = browser_session else {
            return Ok(None);
        };

        if !requester.is_owner_or_admin(&browser_session) {
            return Ok(None);
        }

        Ok(Some(BrowserSession(browser_session)))
    }

    /// Fetch a compatible session by its ID.
    async fn compat_session(
        &self,
        ctx: &Context<'_>,
        id: ID,
    ) -> Result<Option<CompatSession>, async_graphql::Error> {
        let state = ctx.state();
        let id = NodeType::CompatSession.extract_ulid(&id)?;
        let requester = ctx.requester();

        let mut repo = state.repository().await?;
        let compat_session = repo.compat_session().lookup(id).await?;
        repo.cancel().await?;

        let Some(compat_session) = compat_session else {
            return Ok(None);
        };

        if !requester.is_owner_or_admin(&compat_session) {
            return Ok(None);
        }

        Ok(Some(CompatSession::new(compat_session)))
    }

    /// Fetch an OAuth 2.0 session by its ID.
    async fn oauth2_session(
        &self,
        ctx: &Context<'_>,
        id: ID,
    ) -> Result<Option<OAuth2Session>, async_graphql::Error> {
        let state = ctx.state();
        let id = NodeType::OAuth2Session.extract_ulid(&id)?;
        let requester = ctx.requester();

        let mut repo = state.repository().await?;
        let oauth2_session = repo.oauth2_session().lookup(id).await?;
        repo.cancel().await?;

        let Some(oauth2_session) = oauth2_session else {
            return Ok(None);
        };

        if !requester.is_owner_or_admin(&oauth2_session) {
            return Ok(None);
        }

        Ok(Some(OAuth2Session(oauth2_session)))
    }

    /// Fetch a user email by its ID.
    async fn user_email(
        &self,
        ctx: &Context<'_>,
        id: ID,
    ) -> Result<Option<UserEmail>, async_graphql::Error> {
        let state = ctx.state();
        let id = NodeType::UserEmail.extract_ulid(&id)?;
        let requester = ctx.requester();

        let mut repo = state.repository().await?;
        let user_email = repo.user_email().lookup(id).await?;
        repo.cancel().await?;

        let Some(user_email) = user_email else {
            return Ok(None);
        };

        if !requester.is_owner_or_admin(&user_email) {
            return Ok(None);
        }

        Ok(Some(UserEmail(user_email)))
    }

    /// Fetches an object given its ID.
    async fn node(&self, ctx: &Context<'_>, id: ID) -> Result<Option<Node>, async_graphql::Error> {
        // Special case for the anonymous user
        if id.as_str() == "anonymous" {
            return Ok(Some(Node::Anonymous(Box::new(Anonymous))));
        }

        if id.as_str() == crate::graphql::model::SITE_CONFIG_ID {
            return Ok(Some(Node::SiteConfig(Box::new(SiteConfig::new(
                ctx.state().site_config(),
            )))));
        }

        let (node_type, _id) = NodeType::from_id(&id)?;

        let ret = match node_type {
            // TODO
            NodeType::Authentication | NodeType::CompatSsoLogin => None,

            NodeType::UpstreamOAuth2Provider => UpstreamOAuthQuery
                .upstream_oauth2_provider(ctx, id)
                .await?
                .map(|c| Node::UpstreamOAuth2Provider(Box::new(c))),

            NodeType::UpstreamOAuth2Link => UpstreamOAuthQuery
                .upstream_oauth2_link(ctx, id)
                .await?
                .map(|c| Node::UpstreamOAuth2Link(Box::new(c))),

            NodeType::OAuth2Client => self
                .oauth2_client(ctx, id)
                .await?
                .map(|c| Node::OAuth2Client(Box::new(c))),

            NodeType::UserEmail => self
                .user_email(ctx, id)
                .await?
                .map(|e| Node::UserEmail(Box::new(e))),

            NodeType::CompatSession => self
                .compat_session(ctx, id)
                .await?
                .map(|s| Node::CompatSession(Box::new(s))),

            NodeType::OAuth2Session => self
                .oauth2_session(ctx, id)
                .await?
                .map(|s| Node::OAuth2Session(Box::new(s))),

            NodeType::BrowserSession => self
                .browser_session(ctx, id)
                .await?
                .map(|s| Node::BrowserSession(Box::new(s))),

            NodeType::User => UserQuery
                .user(ctx, id)
                .await?
                .map(|u| Node::User(Box::new(u))),
        };

        Ok(ret)
    }

    /// Get the current site configuration
    async fn site_config(&self, ctx: &Context<'_>) -> SiteConfig {
        SiteConfig::new(ctx.state().site_config())
    }
}