mas_handlers/admin/v1/upstream_oauth_links/
get.rs

1// Copyright 2025 New Vector Ltd.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4// Please see LICENSE in the repository root for full details.
5
6use aide::{OperationIo, transform::TransformOperation};
7use axum::{Json, response::IntoResponse};
8use hyper::StatusCode;
9use ulid::Ulid;
10
11use crate::{
12    admin::{
13        call_context::CallContext,
14        model::UpstreamOAuthLink,
15        params::UlidPathParam,
16        response::{ErrorResponse, SingleResponse},
17    },
18    impl_from_error_for_route,
19};
20
21#[derive(Debug, thiserror::Error, OperationIo)]
22#[aide(output_with = "Json<ErrorResponse>")]
23pub enum RouteError {
24    #[error(transparent)]
25    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
26
27    #[error("Upstream OAuth 2.0 Link ID {0} not found")]
28    NotFound(Ulid),
29}
30
31impl_from_error_for_route!(mas_storage::RepositoryError);
32
33impl IntoResponse for RouteError {
34    fn into_response(self) -> axum::response::Response {
35        let error = ErrorResponse::from_error(&self);
36        let status = match self {
37            Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
38            Self::NotFound(_) => StatusCode::NOT_FOUND,
39        };
40        (status, Json(error)).into_response()
41    }
42}
43
44pub fn doc(operation: TransformOperation) -> TransformOperation {
45    operation
46        .id("getUpstreamOAuthLink")
47        .summary("Get an upstream OAuth 2.0 link")
48        .tag("upstream-oauth-link")
49        .response_with::<200, Json<SingleResponse<UpstreamOAuthLink>>, _>(|t| {
50            let [sample, ..] = UpstreamOAuthLink::samples();
51            let response = SingleResponse::new_canonical(sample);
52            t.description("Upstream OAuth 2.0 link was found")
53                .example(response)
54        })
55        .response_with::<404, RouteError, _>(|t| {
56            let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil()));
57            t.description("Upstream OAuth 2.0 link was not found")
58                .example(response)
59        })
60}
61
62#[tracing::instrument(name = "handler.admin.v1.upstream_oauth_links.get", skip_all, err)]
63pub async fn handler(
64    CallContext { mut repo, .. }: CallContext,
65    id: UlidPathParam,
66) -> Result<Json<SingleResponse<UpstreamOAuthLink>>, RouteError> {
67    let link = repo
68        .upstream_oauth_link()
69        .lookup(*id)
70        .await?
71        .ok_or(RouteError::NotFound(*id))?;
72
73    Ok(Json(SingleResponse::new_canonical(
74        UpstreamOAuthLink::from(link),
75    )))
76}
77
78#[cfg(test)]
79mod tests {
80    use hyper::{Request, StatusCode};
81    use insta::assert_json_snapshot;
82    use sqlx::PgPool;
83    use ulid::Ulid;
84
85    use super::super::test_utils;
86    use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup};
87
88    #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
89    async fn test_get(pool: PgPool) {
90        setup();
91        let mut state = TestState::from_pool(pool).await.unwrap();
92        let token = state.token_with_scope("urn:mas:admin").await;
93        let mut rng = state.rng();
94
95        // Provision a provider and a link
96        let mut repo = state.repository().await.unwrap();
97        let provider = repo
98            .upstream_oauth_provider()
99            .add(
100                &mut rng,
101                &state.clock,
102                test_utils::oidc_provider_params("provider1"),
103            )
104            .await
105            .unwrap();
106        let user = repo
107            .user()
108            .add(&mut rng, &state.clock, "alice".to_owned())
109            .await
110            .unwrap();
111        let link = repo
112            .upstream_oauth_link()
113            .add(
114                &mut rng,
115                &state.clock,
116                &provider,
117                "subject1".to_owned(),
118                None,
119            )
120            .await
121            .unwrap();
122        repo.upstream_oauth_link()
123            .associate_to_user(&link, &user)
124            .await
125            .unwrap();
126        repo.save().await.unwrap();
127
128        let link_id = link.id;
129        let request = Request::get(format!("/api/admin/v1/upstream-oauth-links/{link_id}"))
130            .bearer(&token)
131            .empty();
132        let response = state.request(request).await;
133        response.assert_status(StatusCode::OK);
134        let body: serde_json::Value = response.json();
135        assert_json_snapshot!(body, @r###"
136        {
137          "data": {
138            "type": "upstream-oauth-link",
139            "id": "01FSHN9AG09NMZYX8MFYH578R9",
140            "attributes": {
141              "created_at": "2022-01-16T14:40:00Z",
142              "provider_id": "01FSHN9AG0MZAA6S4AF7CTV32E",
143              "subject": "subject1",
144              "user_id": "01FSHN9AG0AJ6AC5HQ9X6H4RP4",
145              "human_account_name": null
146            },
147            "links": {
148              "self": "/api/admin/v1/upstream-oauth-links/01FSHN9AG09NMZYX8MFYH578R9"
149            }
150          },
151          "links": {
152            "self": "/api/admin/v1/upstream-oauth-links/01FSHN9AG09NMZYX8MFYH578R9"
153          }
154        }
155        "###);
156    }
157
158    #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
159    async fn test_not_found(pool: PgPool) {
160        setup();
161        let mut state = TestState::from_pool(pool).await.unwrap();
162        let token = state.token_with_scope("urn:mas:admin").await;
163
164        let link_id = Ulid::nil();
165        let request = Request::get(format!("/api/admin/v1/upstream-oauth-links/{link_id}"))
166            .bearer(&token)
167            .empty();
168        let response = state.request(request).await;
169        response.assert_status(StatusCode::NOT_FOUND);
170    }
171}