1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
Easily test new logos on Wikimedia sites
Copyright (C) 2021 Kunal Mehta <legoktm@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

use anyhow::{anyhow, Result};
use lazy_static::lazy_static;
use regex::Regex;
use rocket::response::content;
use rocket_dyn_templates::Template;
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[macro_use]
extern crate rocket;

const USER_AGENT: &str = toolforge::user_agent!("logo-test");

/// CSS copied from MediaWiki's output
const CSS: &str = r#"
<style type="text/css">
.mw-wiki-logo {
 background-image:url($logo)
}

@media (-webkit-min-device-pixel-ratio:1.5),(min--moz-device-pixel-ratio:1.5),(min-resolution:1.5dppx),(min-resolution:144dpi) {
 .mw-wiki-logo {
  background-image:url($logo_1_5x);
  background-size:135px auto
 }
}
@media (-webkit-min-device-pixel-ratio:2),(min--moz-device-pixel-ratio:2),(min-resolution:2dppx),(min-resolution:192dpi) {
 .mw-wiki-logo {
  background-image:url($logo_2x);
  background-size:135px auto;
 }
}
</style>
</head>
"#;

#[derive(Serialize)]
struct ErrorTemplate {
    error: String,
}

/// Build a HTTP client
fn client() -> Result<reqwest::Client> {
    Ok(reqwest::ClientBuilder::new()
        .user_agent(USER_AGENT)
        .build()?)
}

#[get("/?<wiki>&<logo>")]
async fn index(wiki: Option<String>, logo: Option<String>) -> Template {
    match build_index(wiki, logo).await {
        Ok(index) => Template::render("main", index),
        Err(err) => {
            dbg!(&err);
            Template::render(
                "error",
                ErrorTemplate {
                    error: err.to_string(),
                },
            )
        }
    }
}

#[derive(Serialize)]
struct IndexTemplate {
    wiki: Option<String>,
    logo: Option<String>,
}

/// Build the index template (`/`)
async fn build_index(wiki: Option<String>, logo: Option<String>) -> Result<IndexTemplate> {
    if let Some(wiki) = &wiki {
        validate_domain(wiki).await?;
    }
    if let Some(logo) = &logo {
        validate_logo(logo)?;
    }
    Ok(IndexTemplate { wiki, logo })
}

#[get("/test?<wiki>&<logo>&<useskin>")]
async fn test(
    wiki: String,
    logo: String,
    useskin: String,
) -> Result<content::RawHtml<String>, Template> {
    match build_test(&wiki, &logo, &useskin).await {
        Ok(text) => Ok(content::RawHtml(text)),
        Err(err) => {
            dbg!(&err);
            Err(Template::render(
                "error",
                ErrorTemplate {
                    error: err.to_string(),
                },
            ))
        }
    }
}

#[derive(Deserialize)]
struct ImageInfo {
    thumburl: String,
    #[serde(rename = "responsiveUrls")]
    responsive_urls: ResponsiveUrls,
}

#[derive(Deserialize)]
struct ResponsiveUrls {
    #[serde(rename = "1.5")]
    one_half: String,
    #[serde(rename = "2")]
    two: String,
}

fn validate_skin(skin: &str) -> Result<()> {
    if vec!["vector", "timeless", "monobook"].contains(&skin) {
        Ok(())
    } else {
        Err(anyhow!("Invalid skin specified"))
    }
}

async fn validate_domain(wiki: &str) -> Result<()> {
    use mysql_async::prelude::*;
    use mysql_async::Pool;
    let domain = if wiki.starts_with("https://") {
        let parsed = url::Url::parse(wiki)?;
        match parsed.host_str() {
            Some(domain) => domain.to_string(),
            None => return Err(anyhow!("Invalid domain specified")),
        }
    } else {
        wiki.to_string()
    };
    if domain == "upload.wikimedia.org" || domain == "people.wikimedia.org" {
        // Non-wiki, safe domains
        return Ok(());
    }
    let db_url = match toolforge::connection_info!("meta_p", WEB) {
        Ok(info) => info.to_string(),
        // If we're not on Toolforge, don't bother validating
        Err(toolforge::Error::NotToolforge(_)) => return Ok(()),
        Err(e) => return Err(e.into()),
    };
    let pool = Pool::new(db_url.as_str());
    let mut conn = pool.get_conn().await?;
    let full_domain = format!("https://{}", domain);
    let resp: Option<u32> = conn
        .exec_first("SELECT 1 FROM wiki WHERE url = ?", (full_domain,))
        .await?;
    drop(conn);
    pool.disconnect().await?;
    if resp.is_some() {
        Ok(())
    } else {
        Err(anyhow!("Invalid domain"))
    }
}

fn validate_logo(logo: &str) -> Result<()> {
    if !logo.ends_with(".svg") {
        Err(anyhow!("Logo must be a SVG"))
    } else if !logo.starts_with("File:") {
        Err(anyhow!("Logo must begin with File:"))
    } else {
        Ok(())
    }
}

/// Fetch thumbs from Commons and turn it into CSS
async fn commons_thumbs(logo: &str) -> Result<String> {
    let resp = client()?.get(
        &format!("https://commons.wikimedia.org/w/api.php?action=query&format=json&prop=imageinfo&titles={}&formatversion=2&iiprop=url&iiurlwidth=135", logo)
    ).send().await?;

    let data: Value = resp.json().await?;
    dbg!(&data);
    let info: ImageInfo =
        serde_json::from_value(data["query"]["pages"][0]["imageinfo"][0].clone())?;
    // Replace the URLs in:
    let css = CSS
        .to_string()
        .replace(
            "$logo_1_5x",
            &info.responsive_urls.one_half.replace("203", "202"),
        )
        .replace("$logo_2x", &info.responsive_urls.two)
        .replace("$logo", &info.thumburl);
    Ok(css)
}

async fn build_test(wiki: &str, logo: &str, useskin: &str) -> Result<String> {
    validate_skin(useskin)?;
    validate_domain(wiki).await?;
    validate_logo(logo)?;
    let resp = client()?
        .get(&format!("https://{}/?useskin={}", wiki, useskin))
        .send()
        .await?;
    let text = resp.text().await?;

    // Make some URLs absolute
    lazy_static! {
        static ref RE: Regex = Regex::new(r#"(?P<attr>(src|href))="/(?P<letter>[A-z])"#).unwrap();
    }
    let rep = format!(r#"$attr="//{}/$letter"#, wiki);
    let fixed = RE.replace_all(&text, rep.as_str());

    // Inject the Commmons logo CSS
    let css = commons_thumbs(logo).await?;
    let injected = fixed.replace("</head>", &css);
    Ok(injected)
}

#[derive(Serialize)]
struct DiffTemplate {
    logo1: Option<String>,
    logo2: Option<String>,
    logo1_safe: Option<String>,
    logo2_safe: Option<String>,
}

#[get("/diff?<logo1>&<logo2>")]
async fn diff(logo1: Option<String>, logo2: Option<String>) -> Template {
    match build_diff(logo1, logo2).await {
        Ok(diff) => Template::render("diff", diff),
        Err(err) => {
            dbg!(&err);
            Template::render(
                "error",
                ErrorTemplate {
                    error: err.to_string(),
                },
            )
        }
    }
}

/// Build the diff template (`/`)
async fn build_diff(logo1: Option<String>, logo2: Option<String>) -> Result<DiffTemplate> {
    let logo1_safe = if let Some(logo1) = &logo1 {
        validate_domain(logo1).await?;
        Some(serde_json::to_string(logo1)?)
    } else {
        None
    };
    let logo2_safe = if let Some(logo2) = &logo2 {
        validate_domain(logo2).await?;
        Some(serde_json::to_string(logo2)?)
    } else {
        None
    };
    Ok(DiffTemplate {
        logo1,
        logo2,
        logo1_safe,
        logo2_safe,
    })
}

#[get("/healthz")]
fn healthz() -> &'static str {
    "OK"
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(Template::fairing())
        .mount("/", routes![index, diff, healthz, test])
}

#[cfg(test)]
mod tests {
    use super::*;
    use rocket::http::Status;
    use rocket::local::blocking::Client;

    #[tokio::test]
    async fn test_commons_thumbs() {
        let resp = commons_thumbs("File:Wikipedia-logo-v2-wordmark.svg")
            .await
            .unwrap();
        assert_eq!(
            &resp,
            r#"
<style type="text/css">
.mw-wiki-logo {
 background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Wikipedia-logo-v2-wordmark.svg/135px-Wikipedia-logo-v2-wordmark.svg.png)
}

@media (-webkit-min-device-pixel-ratio:1.5),(min--moz-device-pixel-ratio:1.5),(min-resolution:1.5dppx),(min-resolution:144dpi) {
 .mw-wiki-logo {
  background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Wikipedia-logo-v2-wordmark.svg/202px-Wikipedia-logo-v2-wordmark.svg.png);
  background-size:135px auto
 }
}
@media (-webkit-min-device-pixel-ratio:2),(min--moz-device-pixel-ratio:2),(min-resolution:2dppx),(min-resolution:192dpi) {
 .mw-wiki-logo {
  background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Wikipedia-logo-v2-wordmark.svg/270px-Wikipedia-logo-v2-wordmark.svg.png);
  background-size:135px auto;
 }
}
</style>
</head>
"#
        );
    }

    #[test]
    fn test_validate_skin() {
        // No panic
        validate_skin("vector").unwrap()
    }

    #[test]
    #[should_panic]
    fn test_validate_skin_bad() {
        validate_skin("whatever").unwrap();
    }

    #[test]
    fn test_validate_logo() {
        // No panic
        validate_logo("File:Wiki.svg").unwrap();
    }

    #[test]
    #[should_panic]
    fn test_validate_logo_no_file() {
        validate_logo("Wiki.svg").unwrap();
    }

    #[test]
    #[should_panic]
    fn test_validate_logo_not_svg() {
        validate_logo("File:Wiki.png").unwrap();
    }

    #[test]
    fn test_index() {
        let client = Client::tracked(rocket()).unwrap();
        let response = client.get("/").dispatch();
        assert_eq!(response.status(), Status::Ok);
        assert!(response
            .into_string()
            .unwrap()
            .contains("The logo-test tool allows you"));

        let response = client
            .get("/?wiki=en.wikipedia.org&logo=File%3AUncyclomedia+blue+logo+notext.svg")
            .dispatch();
        assert_eq!(response.status(), Status::Ok);
        assert!(response
            .into_string()
            .unwrap()
            .contains("Using the vector skin"));

        // Error handling
        let response = client
            .get("/?wiki=en.wikipedia.org&logo=Bad_logo")
            .dispatch();
        assert_eq!(response.status(), Status::Ok);
        assert!(response.into_string().unwrap().contains("logo-test: error"))
    }

    #[test]
    fn test_test() {
        // the /test endpoint
        let client = Client::tracked(rocket()).unwrap();
        let response = client.get("/test").dispatch();
        assert_eq!(response.status(), Status::NotFound);

        let response = client
            .get("/test?wiki=en.wikipedia.org&logo=File%3AUncyclomedia+blue+logo+notext.svg&useskin=timeless")
            .dispatch();
        assert_eq!(response.status(), Status::Ok);
        assert!(response
            .into_string()
            .unwrap()
            // the 2x variant, good enough for an integration test
            .contains("270px-Uncyclomedia_blue_logo_notext.svg.png"));

        // Error handling
        let response = client
            .get("/test?wiki=en.wikipedia.org&logo=Bad_logo&useskin=timeless")
            .dispatch();
        assert_eq!(response.status(), Status::Ok);
        assert!(response.into_string().unwrap().contains("logo-test: error"))
    }

    #[tokio::test]
    async fn test_validate_domain() {
        validate_domain("upload.wikimedia.org").await.unwrap();
        validate_domain("people.wikmedia.org").await.unwrap();
        // TODO: why is this failing?
        // assert!(validate_domain("/foo/bar").await.err().is_some());
    }
}