aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 7127922274792651faa5b981be08aae822ff9e02 (plain)
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use clap::Clap;
use controller::Controller;
use git2::Commit;
use git2::ObjectType;
use git2::Oid;
use git2::Repository;
use git2::Signature;
use git2::Tree;
use hyper::header;
use hyper::http::request::Parts;
use hyper::http::response::Builder;
use hyper::service::{make_service_fn, service_fn};
use hyper::Method;
use hyper::StatusCode;
use hyper::{Body, Server};
use percent_encoding::percent_decode_str;
use pulldown_cmark::html;
use pulldown_cmark::Options;
use pulldown_cmark::Parser;
use serde::Deserialize;
use sputnik::html_escape;
use sputnik::mime;
use sputnik::request::SputnikParts;
use sputnik::response::SputnikBuilder;
use std::convert::Infallible;
use std::env;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use url::Url;

#[cfg(unix)]
use {
    hyperlocal::UnixServerExt, std::fs, std::fs::Permissions,
    std::os::unix::prelude::PermissionsExt,
};

use crate::controller::MultiUserController;
use crate::controller::SoloController;
use crate::error::Error;

mod controller;
mod diff;
mod error;
mod forms;
mod get_routes;
mod post_routes;
mod shares;

pub enum Response {
    Raw(HyperResponse),
    Page(Page),
}

impl From<Page> for Response {
    fn from(page: Page) -> Self {
        Self::Page(page)
    }
}

impl From<HyperResponse> for Response {
    fn from(resp: HyperResponse) -> Self {
        Self::Raw(resp)
    }
}

pub(crate) type HyperResponse = hyper::Response<hyper::Body>;
pub(crate) type Request = hyper::Request<hyper::Body>;

#[derive(Clap, Debug)]
#[clap(name = "gitpad")]
struct Args {
    /// Enable mutliuser mode (requires a reverse-proxy that handles
    /// authentication and sets the Username header)
    #[clap(short)]
    multiuser: bool,

    #[clap(short, default_value = "8000")]
    port: u16,

    /// e.g. https://example.com (used to enforce Host and Origin headers)
    #[clap(long)]
    origin: Option<HttpOrigin>,

    /// Serve via the given Unix domain socket path.
    #[cfg(unix)]
    #[clap(long)]
    socket: Option<String>,
}

#[tokio::main]
async fn main() {
    let args = Args::parse();
    let repo = Repository::open_bare(env::current_dir().unwrap())
        .expect("expected current directory to be a bare Git repository");

    if args.multiuser {
        serve(MultiUserController::new(&repo), args).await;
    } else {
        serve(
            SoloController(Branch(
                repo.find_reference("HEAD")
                    .unwrap()
                    .symbolic_target()
                    .unwrap()
                    .strip_prefix("refs/heads/")
                    .unwrap()
                    .to_owned(),
            )),
            args,
        )
        .await;
    }
}

#[derive(Clone, Debug)]
struct HttpOrigin {
    origin: String,
    host_idx: usize,
}

impl HttpOrigin {
    /// Returns the Host header value (e.g. `example.com` for the origin `https://example.com`).
    fn host(&self) -> &str {
        &self.origin[self.host_idx..]
    }
}

impl FromStr for HttpOrigin {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let url = Url::parse(s).map_err(|_| "invalid URL")?;
        if url.scheme() != "http" && url.scheme() != "https" {
            return Err("expected http:// or https:// scheme");
        }
        if url.path() != "/" {
            return Err("path must be /".into());
        }
        Ok(HttpOrigin {
            origin: url.origin().ascii_serialization(),
            host_idx: url.scheme().len() + "://".len(),
        })
    }
}

async fn serve<C: Controller + Send + Sync + 'static>(controller: C, args: Args) {
    let controller = Arc::new(controller);

    #[cfg(unix)]
    if let Some(socket_path) = &args.socket {
        let origin: &'static HttpOrigin = Box::leak(Box::new(
            args.origin
                .expect("if you use --socket, you must specify an --origin"),
        ));

        // TODO: get rid of code duplication
        // we somehow need to specify the closure type or it gets too specific
        let service = make_service_fn(move |_| {
            let controller = controller.clone();

            async move {
                Ok::<_, hyper::Error>(service_fn(move |req| {
                    service(origin, controller.clone(), req)
                }))
            }
        });
        let path = Path::new(&socket_path);
        if path.exists() {
            fs::remove_file(path).unwrap();
        }
        let server = Server::bind_unix(path).unwrap();

        if fs::metadata(path.parent().unwrap())
            .unwrap()
            .permissions()
            .mode()
            & 0o001
            != 0
        {
            eprintln!("socket parent directory must not have x permission for others");
            std::process::exit(1);
        }

        fs::set_permissions(path, Permissions::from_mode(0o777))
            .expect("failed to set socket permissions");

        println!("Listening on unix socket {}", socket_path);
        server.serve(service).await.expect("server error");
        return;
    }

    eprint!(
        "[warning] Serving GitPad over a TCP socket. \
    If you use a reverse-proxy for access control, \
    it can be circumvented by anybody with a system account."
    );
    #[cfg(unix)]
    eprint!(
        " Use a Unix domain socket (with --socket) to restrict \
    access based on the socket parent directory permissions."
    );
    eprintln!();

    let addr = ([127, 0, 0, 1], args.port).into();
    let url = format!("http://{}", addr);
    let origin: &'static HttpOrigin = Box::leak(Box::new(
        args.origin.unwrap_or_else(|| url.parse().unwrap()),
    ));

    let service = make_service_fn(move |_| {
        let controller = controller.clone();

        async move {
            Ok::<_, hyper::Error>(service_fn(move |req| {
                service(&origin, controller.clone(), req)
            }))
        }
    });
    let server = Server::bind(&addr).serve(service);
    println!("Listening on {}", url);
    server.await.expect("server error");
}

async fn service<C: Controller>(
    origin: &HttpOrigin,
    controller: Arc<C>,
    request: Request,
) -> Result<HyperResponse, Infallible> {
    let (mut parts, body) = request.into_parts();

    let mut script_csp = "'none'".into();
    let mut frame_csp = "'none'".into();

    let mut resp = build_response(origin, &*controller, &mut parts, body)
        .await
        .map(|resp| match resp {
            Response::Raw(resp) => resp,
            Response::Page(page) => {
                if !page.script_src.is_empty() {
                    script_csp = page.script_src.join(" ");
                }
                if let Some(src) = page.frame_src {
                    frame_csp = src;
                }
                Builder::new()
                    .content_type(mime::TEXT_HTML)
                    .body(render_page(&page, &*controller, &parts).into())
                    .unwrap()
            }
        })
        .unwrap_or_else(|err| err.into());

    // we rely on CSP to thwart XSS attacks, all modern browsers support it
    resp.headers_mut()
        .entry(header::CONTENT_SECURITY_POLICY)
        .or_insert_with(|| {
            format!(
                "default-src 'self'; frame-src {}; script-src {}; style-src {}",
                frame_csp,
                script_csp,
                include_str!("static/style.css.sha"),
            )
            .parse()
            .unwrap()
        });
    Ok(resp)
}

#[derive(Default)]
pub struct Page {
    title: String,
    header: String,
    body: String,
    /// will be embedded as inline <script> tags
    scripts: Vec<&'static str>,
    /// for the Content Security Policy
    script_src: Vec<&'static str>,

    /// for the Content Security Policy
    frame_src: Option<&'static str>,
}

fn render_page<C: Controller>(page: &Page, controller: &C, parts: &Parts) -> String {
    let mut out = String::new();
    out.push_str("<!doctype html><html><head><meta charset=utf-8>");
    out.push_str(&format!("<title>{}</title>", html_escape(&page.title)));
    out.push_str("<meta name=viewport content=\"width=device-width, initial-scale=1\"><style>");
    out.push_str(include_str!("static/style.css"));
    out.push_str("</style></head><body><header id=header>");
    out.push_str(&page.header);
    out.push_str(
        &controller
            .user_info_html(parts)
            .map(|h| format!("<div class=user-info>{}</div>", h))
            .unwrap_or_default(),
    );
    out.push_str("</header>");
    out.push_str(&page.body);
    for script in &page.scripts {
        out.push_str(&format!("<script>{}</script>", script));
    }
    out.push_str("</body></html>");
    out
}

#[derive(Deserialize)]
struct ActionParam {
    #[serde(default = "default_action")]
    action: String,
}

fn default_action() -> String {
    "view".into()
}

#[derive(Eq, PartialEq, Hash, Clone)]
pub struct Branch(String);

impl Branch {
    fn rev_str(&self) -> String {
        format!("refs/heads/{}", self.0)
    }
}

async fn build_response<C: Controller>(
    origin: &HttpOrigin,
    controller: &C,
    parts: &mut Parts,
    body: Body,
) -> Result<Response, Error> {
    let host = parts
        .headers
        .get("Host")
        .ok_or_else(|| Error::BadRequest("Host header required".into()))?
        .to_str()
        .unwrap();
    if host != origin.host() {
        // We enforce an exact Host header to prevent DNS rebinding attacks.
        return Err(Error::BadRequest(format!("<h1>Bad Request: Unknown Host header</h1>\
        Received the header <pre>Host: {}</pre>
        But expected the header <pre>Host: {}</pre> \
        <p>If you want to serve GitPad under a different hostname you need to specify it on startup with <code>--origin</code>.</p>",
        html_escape(host), html_escape(origin.host()))));
    }

    let unsanitized_path = percent_decode_str(parts.uri.path())
        .decode_utf8()
        .map_err(|_| Error::BadRequest("failed to percent-decode path as UTF-8".into()))?
        .into_owned();

    let repo = Repository::open_bare(env::current_dir().unwrap()).unwrap();

    let (rev, unsanitized_path) = match controller.parse_url_path(&unsanitized_path, &parts, &repo)
    {
        Ok(parsed) => parsed,
        Err(res) => return res,
    };

    let mut comps = Vec::new();

    // prevent directory traversal attacks
    for comp in Path::new(&*unsanitized_path).components() {
        match comp {
            Component::Normal(name) => comps.push(name),
            Component::ParentDir => {
                return Err(Error::Forbidden("path traversal is forbidden".into()))
            }
            _ => {}
        }
    }

    let params: ActionParam = parts.query::<ActionParam>().unwrap();

    let url_path: PathBuf = comps.iter().collect();

    let ctx = Context {
        repo,
        path: url_path,
        branch: rev,
    };

    if !controller.may_read_path(&ctx, parts) {
        return Err(Error::Unauthorized(
            "you are not authorized to view this file".into(),
        ));
    }

    if parts.method == Method::POST {
        return post_routes::build_response(origin, &params, controller, ctx, body, parts).await;
    }

    let mut tree = ctx
        .repo
        .revparse_single(&ctx.branch.rev_str())
        .map(|r| r.into_commit().unwrap().tree().unwrap());

    if ctx.path.components().next().is_some() {
        let entr = match tree.and_then(|t| t.get_path(&ctx.path)) {
            Ok(entr) => entr,
            Err(_) => {
                if unsanitized_path.ends_with('/') {
                    return Err(Error::NotFound("directory not found".into()));
                }

                if controller.may_write_path(&ctx, parts) {
                    if params.action == "edit" {
                        return Ok(forms::edit_text_form(
                            &forms::EditForm::default(),
                            None,
                            controller,
                            &ctx,
                            parts,
                        )
                        .into());
                    } else if params.action == "upload" {
                        return Ok(forms::upload_form(false, controller, &ctx, parts).into());
                    } else {
                        return Err(Error::NotFound(
                            "file not found, but <a href=?action=edit>you can write it</a> or <a href=?action=upload>upload it</a>".into(),
                        ));
                    }
                } else {
                    return Err(Error::NotFound("file not found".into()));
                }
            }
        };

        if entr.kind().unwrap() == ObjectType::Blob {
            if unsanitized_path.ends_with('/') {
                return Ok(Builder::new()
                    .status(StatusCode::FOUND)
                    .header(
                        "location",
                        controller
                            .build_url_path(&ctx.branch, unsanitized_path.trim_end_matches('/')),
                    )
                    .body("redirecting".into())
                    .unwrap()
                    .into());
            }
            return get_routes::get_blob(entr, params, controller, ctx, &parts);
        }

        tree = ctx.repo.find_tree(entr.id());
        if !unsanitized_path.ends_with('/') {
            return Err(Error::MissingTrailingSlash(parts.uri.path().to_owned()));
        }
    }

    get_routes::view_tree(tree, controller, &ctx, &parts)
}

fn render_link(name: &str, label: &str, active_action: &str) -> String {
    format!(
        " <a {}{}>{}</a>",
        if name == active_action {
            "class=active".into()
        } else {
            format!("href=?action={}", name)
        },
        if name != label {
            format!(" title='{}'", name)
        } else {
            "".into()
        },
        label
    )
}

fn action_links<C: Controller>(
    active_action: &str,
    controller: &C,
    ctx: &Context,
    parts: &Parts,
) -> String {
    let mut out = String::new();

    out.push_str("<div class=actions>");
    out.push_str("<a href=. title='list parent directory'>ls</a>");
    out.push_str(&render_link("view", "view", active_action));
    if controller.may_write_path(ctx, parts) {
        out.push_str(&render_link("edit", "edit", active_action));
    }
    out.push_str(&render_link("log", "log", active_action));
    out.push_str(&render_link("raw", "raw", active_action));
    if controller.may_move_path(ctx, parts) {
        out.push_str(&render_link("move", "mv", active_action));
        out.push_str(&render_link("remove", "rm", active_action));
    }
    out.push_str("</div>");
    out
}

pub struct Context {
    repo: Repository,
    branch: Branch,
    path: PathBuf,
}

impl Context {
    fn branch_head(&self) -> Result<Commit, Error> {
        self.repo
            .revparse_single(&self.branch.rev_str())
            .map_err(|_| Error::NotFound("branch not found".into()))?
            .into_commit()
            .map_err(|_| Error::NotFound("branch not found".into()))
    }

    fn commit(
        &self,
        signature: &Signature,
        msg: &str,
        tree: &Tree,
        parent_commits: &[&Commit],
    ) -> Result<Oid, git2::Error> {
        self.repo.commit(
            Some(&self.branch.rev_str()),
            signature,
            signature,
            msg,
            tree,
            parent_commits,
        )
    }

    fn file_name(&self) -> Option<&str> {
        self.path.file_name().and_then(|x| x.to_str())
    }
}

#[derive(PartialEq)]
enum RenderMode {
    View,
    Preview,
}

fn render_markdown(input: &str, page: &mut Page, _mode: RenderMode) {
    let parser = Parser::new_ext(input, Options::all());
    page.body.push_str("<div class=markdown-output>");
    html::push_html(&mut page.body, parser);
    page.body.push_str("</div>");
}

fn embed_html_as_iframe(input: &str, page: &mut Page, mode: RenderMode) {
    if mode == RenderMode::View {
        page.body.push_str("<iframe src='?action=run'></iframe>");
        page.frame_src = Some("'self'");
    } else {
        page.body
            .push_str("<div class=note>Note that JavaScript does not work in the preview.</div>");
        // sandbox=allow-scripts wouldn't work because the strict parent page CSP still applies

        // The sandbox attribute makes browsers treat the embedded page as a unique origin.
        page.body.push_str(&format!(
            "<iframe srcdoc='{}' sandbox></iframe>",
            html_escape(input)
        ));
    }
}

fn get_renderer(path: &Path) -> Option<fn(&str, &mut Page, RenderMode)> {
    match path.extension().map(|e| e.to_str().unwrap()) {
        Some("md") => Some(render_markdown),
        Some("html") => Some(embed_html_as_iframe),
        _ => None,
    }
}