aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 01a893e7128c986601b0ae1118d6579762ec60df (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
use camino::Utf8Component;
use camino::Utf8Path;
use camino::Utf8PathBuf;
use clap::Parser as ClapParser;
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 origins::HttpOrigin;
use percent_encoding::percent_decode_str;
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::marker::PhantomData;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

#[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 origins;
mod post_routes;
mod tests;

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(ClapParser, 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_path = env::current_dir().unwrap();
    let repo = Repository::open_bare(&repo_path)
        .expect("expected current directory to be a bare Git repository");

    if args.multiuser {
        serve(repo_path, MultiUserController::new(&repo), args).await;
    } else {
        serve(repo_path, SoloController::new(&repo), args).await;
    }
}

struct StaticContext {
    repo_path: PathBuf,
    origin: HttpOrigin,
}

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

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

        // 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_wrapper(context, 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 context: &'static _ = Box::leak(Box::new(StaticContext {
        origin: args.origin.unwrap_or_else(|| url.parse().unwrap()),
        repo_path,
    }));

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

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

async fn service_wrapper<C: Controller>(
    context: &StaticContext,
    controller: Arc<C>,
    request: Request,
) -> Result<HyperResponse, Infallible> {
    Ok(service(context, &*controller, request).await)
}

async fn service<C: Controller>(
    context: &StaticContext,
    controller: &C,
    request: Request,
) -> HyperResponse {
    let (mut parts, body) = request.into_parts();

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

    let mut resp = build_response(context, 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()
        });

    // don't leak the hostname of the GitPad instance when following external links
    resp.headers_mut()
        .insert(header::REFERRER_POLICY, "same-origin".parse().unwrap());
    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>(
    StaticContext { repo_path, origin }: &StaticContext,
    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(repo_path).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 Utf8Path::new(unsanitized_path).components() {
        match comp {
            Utf8Component::Normal(name) => comps.push(name),
            Utf8Component::ParentDir => {
                return Err(Error::Forbidden("path traversal is forbidden".into()))
            }
            _ => {}
        }
    }

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

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

    let ctx = Context {
        repo,
        path: url_path,
        branch: rev,
        __: PhantomData::default(),
    };

    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 tree = ctx.branch_head().ok().and_then(|c| c.tree().ok());

    if ctx.path.components().next().is_none() {
        return get_routes::view_tree(tree, controller, &ctx, parts);
    }

    match tree.and_then(|t| t.get_path(ctx.path.as_ref()).ok()) {
        Some(entr) => match 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());
                }
                get_routes::get_blob(entr, params, controller, ctx, parts)
            }
            ObjectType::Tree => {
                if !unsanitized_path.ends_with('/') {
                    return Err(Error::MissingTrailingSlash(parts.uri.path().to_owned()));
                }
                get_routes::view_tree(ctx.repo.find_tree(entr.id()).ok(), controller, &ctx, parts)
            }
            _other => panic!("unexpected object type"),
        },
        None => {
            if unsanitized_path.ends_with('/') {
                return Err(Error::NotFound("directory not found".into()));
            }

            if controller.may_write_path(&ctx, parts) {
                if params.action == "edit" {
                    Ok(forms::edit_text_form(
                        &forms::EditForm::default(),
                        None,
                        controller,
                        &ctx,
                        parts,
                    )
                    .into())
                } else if params.action == "upload" {
                    Ok(forms::upload_form(false, controller, &ctx, parts).into())
                } else {
                    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 {
                Err(Error::NotFound("file not found".into()))
            }
        }
    }
}

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("<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
}

pub struct Context<'a> {
    repo: Repository,
    branch: Branch,
    path: Utf8PathBuf,
    __: PhantomData<&'a ()>,
}

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,
        )
    }
}

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

#[cfg(feature = "md")]
fn render_markdown(input: &str, page: &mut Page, _mode: RenderMode) {
    use pulldown_cmark::html;
    use pulldown_cmark::Options;
    use pulldown_cmark::Parser;

    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: &Utf8Path) -> Option<fn(&str, &mut Page, RenderMode)> {
    match path.extension() {
        #[cfg(feature = "md")]
        Some("md") => Some(render_markdown),
        Some("html") => Some(embed_html_as_iframe),
        _ => None,
    }
}