1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use std::sync::Arc;

use axum::{
    extract::{Path, RequestParts},
    middleware::Next,
};
use serde::Deserialize;

use adapter::client::Locked;
use primitives::{campaign::Campaign, CampaignId, ChainOf};

use crate::{db::fetch_campaign, response::ResponseError, Application, Auth};

/// This struct is required because of routes that have more parameters
/// apart from the `CampaignId`
#[derive(Debug, Deserialize)]
struct CampaignParam {
    pub id: CampaignId,
}

pub async fn campaign_load<C: Locked + 'static, B>(
    request: axum::http::Request<B>,
    next: Next<B>,
) -> Result<axum::response::Response, ResponseError>
where
    B: Send,
{
    let (config, pool) = {
        let app = request
            .extensions()
            .get::<Arc<Application<C>>>()
            .expect("Application should always be present");

        (app.config.clone(), app.pool.clone())
    };

    // running extractors requires a `RequestParts`
    let mut request_parts = RequestParts::new(request);

    let campaign_id = request_parts
        .extract::<Path<CampaignParam>>()
        .await
        .map_err(|_| ResponseError::BadRequest("Bad Campaign Id".to_string()))?
        .id;

    let campaign = fetch_campaign(pool.clone(), &campaign_id)
        .await?
        .ok_or(ResponseError::NotFound)?;

    let campaign_context = config
        .find_chain_of(campaign.channel.token)
        .ok_or_else(|| ResponseError::BadRequest("Channel token not whitelisted".to_string()))?
        .with_campaign(campaign);

    // If this is an authenticated call
    // Check if the Campaign's Channel context (Chain Id) aligns with the Authentication token Chain id
    match request_parts.extensions().get::<Auth>() {
            // If Chain Ids differ, the requester hasn't generated Auth token
            // to access the Channel in it's Chain Id.
            Some(auth) if auth.chain.chain_id != campaign_context.chain.chain_id => {
                return Err(ResponseError::Forbidden("Authentication token is generated for different Chain and differs from the Campaign's Channel Chain".into()))
            }
            _ => {},
        }

    request_parts.extensions_mut().insert(campaign_context);

    let request = request_parts.try_into_request().expect("Body extracted");

    Ok(next.run(request).await)
}

pub async fn called_by_creator<C: Locked + 'static, B>(
    request: axum::http::Request<B>,
    next: Next<B>,
) -> Result<axum::response::Response, ResponseError>
where
    B: Send,
{
    let campaign_context = request
        .extensions()
        .get::<ChainOf<Campaign>>()
        .expect("We must have a Campaign in extensions");

    let auth = request
        .extensions()
        .get::<Auth>()
        .expect("request should have an Authentication");

    if auth.uid.to_address() != campaign_context.context.creator {
        return Err(ResponseError::Forbidden(
            "Request not sent by Campaign's creator".to_string(),
        ));
    }

    Ok(next.run(request).await)
}

#[cfg(test)]
mod test {
    use axum::{
        body::Body,
        http::{Request, StatusCode},
        middleware::from_fn,
        routing::get,
        Extension, Router,
    };
    use tower::Service;

    use adapter::{ethereum::test_util::GANACHE_1, Dummy};
    use primitives::{
        test_util::{CAMPAIGNS, CREATOR, IDS, PUBLISHER},
        Campaign, ChainOf,
    };

    use crate::{
        db::{insert_campaign, insert_channel},
        test_util::setup_dummy_app,
    };

    use super::*;

    #[tokio::test]
    async fn test_campaign_loading() {
        let app_guard = setup_dummy_app().await;
        let app = Arc::new(app_guard.app);

        let campaign_context = CAMPAIGNS[0].clone();

        let build_request = || {
            Request::builder()
                .uri(format!("/{id}/test", id = campaign_context.context.id))
                .extension(app.clone())
                .body(Body::empty())
                .expect("Should build Request")
        };

        async fn handle(
            Extension(campaign_context): Extension<ChainOf<Campaign>>,
            Path((id, another)): Path<(CampaignId, String)>,
        ) -> String {
            assert_eq!(id, campaign_context.context.id);
            assert_eq!(another, "test");
            "Ok".into()
        }

        let mut router = Router::new()
            .route("/:id/:another", get(handle))
            .layer(from_fn(campaign_load::<Dummy, _>));

        // bad CampaignId
        {
            let mut request = build_request();
            *request.uri_mut() = "/WrongCampaignId".parse().unwrap();

            let response = router
                .call(request)
                .await
                .expect("Should make request to Router");

            assert_eq!(
                StatusCode::BAD_REQUEST,
                // ResponseError::BadRequest("Wrong Campaign Id".to_string()),
                response.status()
            );
        }

        // non-existent Campaign
        {
            let request = build_request();

            let response = router
                .call(request)
                .await
                .expect("Should make request to Router");

            assert_eq!(response.status(), StatusCode::NOT_FOUND);
        }

        // existing Campaign
        {
            let channel_context = campaign_context.of_channel();

            // insert Channel
            insert_channel(&app.pool, &channel_context)
                .await
                .expect("Should insert Channel");
            // insert Campaign
            assert!(insert_campaign(&app.pool, &campaign_context.context)
                .await
                .expect("Should insert Campaign"));

            let request = build_request();

            let response = router
                .call(request)
                .await
                .expect("Should make request to Router");

            assert_eq!(response.status(), StatusCode::OK);
        }
    }

    #[tokio::test]
    async fn test_called_by_creator() {
        let app_guard = setup_dummy_app().await;
        let app = Arc::new(app_guard.app);

        let campaign_context = CAMPAIGNS[0].clone();

        // insert Channel
        insert_channel(&app.pool, &campaign_context.of_channel())
            .await
            .expect("Should insert Channel");
        // insert Campaign
        assert!(insert_campaign(&app.pool, &campaign_context.context)
            .await
            .expect("Should insert Campaign"));

        let build_request = |auth: Auth| {
            Request::builder()
                .extension(app.clone())
                .extension(campaign_context.clone())
                .extension(auth)
                .body(Body::empty())
                .expect("Should build Request")
        };

        async fn handle(Extension(_campaign_context): Extension<ChainOf<Campaign>>) -> String {
            "Ok".into()
        }

        let mut router = Router::new()
            .route("/", get(handle))
            .layer(from_fn(called_by_creator::<Dummy, _>));

        // Not the Creator - Forbidden
        {
            let not_creator = Auth {
                era: 1,
                uid: IDS[&PUBLISHER],
                chain: campaign_context.chain.clone(),
            };
            assert_ne!(
                not_creator.uid.to_address(),
                campaign_context.context.creator,
                "The Auth address should not be the Campaign creator for this test!"
            );
            let request = build_request(not_creator);

            let response = router
                .call(request)
                .await
                .expect("Should make request to Router");

            assert_eq!(response.status(), StatusCode::FORBIDDEN);
        }

        // The Campaign Creator - Ok
        {
            let the_creator = Auth {
                era: 1,
                uid: IDS[&campaign_context.context.creator],
                chain: campaign_context.chain.clone(),
            };

            assert_eq!(
                the_creator.uid.to_address(),
                campaign_context.context.creator,
                "The Auth address should be the Campaign creator for this test!"
            );
            let request = build_request(the_creator);

            let response = router
                .call(request)
                .await
                .expect("Should make request to Router");

            assert_eq!(response.status(), StatusCode::OK);
        }
    }

    #[tokio::test]
    #[should_panic]
    async fn test_called_by_creator_no_auth() {
        let app_guard = setup_dummy_app().await;
        let app = Arc::new(app_guard.app);

        let campaign_context = CAMPAIGNS[0].clone();

        async fn handle(Extension(_campaign_context): Extension<ChainOf<Campaign>>) -> String {
            "Ok".into()
        }

        let mut router = Router::new()
            .route("/", get(handle))
            .layer(from_fn(called_by_creator::<Dummy, _>));

        // No Auth - Unauthorized
        let request = Request::builder()
            .extension(app.clone())
            .extension(campaign_context.clone())
            .body(Body::empty())
            .expect("Should build Request");

        let _response = router
            .call(request)
            .await
            .expect("Should make request to Router");
    }

    #[tokio::test]
    #[should_panic]
    async fn test_called_by_creator_no_campaign() {
        let app_guard = setup_dummy_app().await;
        let app = Arc::new(app_guard.app);

        let auth = Auth {
            era: 1,
            uid: IDS[&CREATOR],
            chain: GANACHE_1.clone(),
        };

        let request = Request::builder()
            .extension(app.clone())
            .extension(auth)
            .body(Body::empty())
            .expect("Should build Request");

        async fn handle(Extension(_campaign_context): Extension<ChainOf<Campaign>>) -> String {
            "Ok".into()
        }

        let mut router = Router::new()
            .route("/", get(handle))
            .layer(from_fn(called_by_creator::<Dummy, _>));

        let _response = router
            .call(request)
            .await
            .expect("Should make request to Router");
    }
}