]> git.scottworley.com Git - voter/blame_incremental - src/main.rs
Make cookies
[voter] / src / main.rs
... / ...
CommitLineData
1use rand::prelude::*;
2use std::io::prelude::*;
3use std::path::{Path, PathBuf};
4
5const DATA_PATH: &str = "/var/lib/voter";
6const COOKIE_NAME: &[u8] = b"__Secure-id";
7const COOKIE_LENGTH: usize = 32;
8
9fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
10 let invalid_path = || cgi::text_response(404, "Invalid path");
11 if path == "/" {
12 return Err(cgi::text_response(404, "(This is the voting place. You should have been given a more specific URL for the specific thing you've been invited to vote on.)"));
13 }
14 if path.contains("..") || !path.starts_with("/") {
15 return Err(invalid_path());
16 }
17 let dir = Path::new(&format!("{DATA_PATH}{path}")).to_path_buf();
18 if !dir
19 .canonicalize()
20 .map_err(|_| invalid_path())?
21 .starts_with(DATA_PATH)
22 {
23 return Err(invalid_path());
24 }
25 if !dir.is_dir() {
26 return Err(invalid_path());
27 }
28 Ok(dir)
29}
30
31fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
32 // Expect exactly one cookie, exactly as we generate it.
33 let cookie = request
34 .headers()
35 .get(cgi::http::header::COOKIE)
36 .map(|c| c.as_bytes())
37 .and_then(|c| c.strip_prefix(COOKIE_NAME))
38 .and_then(|c| c.strip_prefix(b"="))
39 .ok_or_else(|| cgi::text_response(400, "Invalid cookie"))?;
40 if cookie.len() != COOKIE_LENGTH || cookie.contains(&b' ') || cookie.contains(&b';') {
41 Err(cgi::text_response(400, "Invalid cookie"))
42 } else {
43 Ok(cookie)
44 }
45}
46
47fn make_random_id() -> [u8; COOKIE_LENGTH] {
48 std::iter::from_fn(random)
49 .filter(|c| {
50 (b'A'..=b'Z').contains(c) || (b'a'..=b'z').contains(c) || (b'0'..=b'9').contains(c)
51 })
52 .take(COOKIE_LENGTH)
53 .collect::<Vec<_>>()
54 .try_into()
55 .unwrap()
56}
57
58fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> {
59 response.headers_mut().append(
60 cgi::http::header::SET_COOKIE,
61 cgi::http::header::HeaderValue::from_bytes(
62 &[
63 COOKIE_NAME,
64 b"=",
65 &make_random_id(),
66 b"; Secure HttpOnly SameSite=Strict Max-Age=30000000 Path=",
67 path.as_bytes(),
68 ]
69 .concat(),
70 )
71 .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
72 );
73 Ok(response)
74}
75
76fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
77 let voter = get_voter(&request);
78 let mut response = cgi::html_response(200, "<html><body>You should vote</body></html>");
79 if voter.is_err() {
80 response = set_cookie(response, request.uri().path())?
81 }
82 Ok(response)
83}
84
85fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
86 let datum = [voter, b" ", vote, b"\n"].concat();
87 let vpath = dir.join("votes");
88 let vfile = std::fs::File::options()
89 .append(true)
90 .create(true)
91 .open(vpath)?;
92 let mut vlock = fd_lock::RwLock::new(vfile);
93 vlock.write()?.write(&datum)?;
94 Ok(())
95}
96
97fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
98 let body = request.body();
99 // Valid votes look like "0 foo" or "1 bar"
100 if body.len() < 3
101 || (body[0] != b'0' && body[0] != b'1')
102 || body[1] != b' '
103 || body.contains(&b'\n')
104 {
105 return Err(cgi::text_response(415, "Invalid vote"));
106 }
107 write_vote(dir, &get_voter(&request)?, body)
108 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
109 Ok(cgi::text_response(200, "Vote recorded"))
110}
111
112fn strip_body(mut response: cgi::Response) -> cgi::Response {
113 response.body_mut().clear();
114 response
115}
116
117fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
118 let dir = validate_path(request.uri().path())?;
119 match request.method() {
120 &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body),
121 &cgi::http::Method::GET => prompt_for_vote(dir, request),
122 &cgi::http::Method::PUT => record_vote(dir, request),
123 _ => Err(cgi::text_response(405, "Huh?")),
124 }
125}
126
127fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
128 match respond(request) {
129 Ok(result) => result,
130 Err(error) => error,
131 }
132}
133
134cgi::cgi_main! { respond_or_report_error }