forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiB8298537Tahinli14 minutes ago332 commits

http.rs178 lines, 5.3 KiBHistoryRawDownload
1use std::time::Duration;
2
3use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE};
4
5use super::input_value;
6
7pub struct Resp {
8 pub status: u16,
9 pub headers: HeaderMap,
10 pub body: String,
11}
12
13impl Resp {
14 pub fn header(&self, name: HeaderName) -> Option<String> {
15 self.headers
16 .get(name)
17 .and_then(|v| v.to_str().ok())
18 .map(str::to_owned)
19 }
20
21 pub fn location(&self) -> Option<String> {
22 self.header(LOCATION)
23 }
24
25 pub fn set_cookies(&self) -> Vec<String> {
26 self.headers
27 .get_all(SET_COOKIE)
28 .iter()
29 .filter_map(|v| v.to_str().ok().map(str::to_owned))
30 .collect()
31 }
32}
33
34pub struct Http {
35 pub client: reqwest::Client,
36 pub base: String,
37}
38
39impl Http {
40 pub fn new(port: u16) -> Self {
41 Self::with_base(format!("http://127.0.0.1:{port}"))
42 }
43
44 pub fn with_base(base: String) -> Self {
45 let client = reqwest::Client::builder()
46 .redirect(reqwest::redirect::Policy::none())
47 .timeout(Duration::from_secs(60))
48 .build()
49 .expect("http client");
50 Self { client, base }
51 }
52
53 pub async fn get(&self, path: &str, cookie: Option<&str>) -> Resp {
54 self.get_language(path, cookie, None).await
55 }
56
57 pub async fn get_language(
58 &self,
59 path: &str,
60 cookie: Option<&str>,
61 language: Option<&str>,
62 ) -> Resp {
63 let mut req = self.client.get(format!("{}{path}", self.base));
64 if let Some(language) = language {
65 req = req.header(reqwest::header::ACCEPT_LANGUAGE, language);
66 }
67 self.send(req, cookie).await
68 }
69
70 pub async fn get_cookie(&self, path: &str, cookie: &str) -> Resp {
71 self.get(path, Some(cookie)).await
72 }
73
74 pub async fn get_bearer(&self, path: &str, token: &str) -> Resp {
75 let req = self
76 .client
77 .get(format!("{}{path}", self.base))
78 .bearer_auth(token);
79 self.send(req, None).await
80 }
81
82 pub async fn get_basic(&self, path: &str, user: &str, password: &str) -> Resp {
83 let req = self
84 .client
85 .get(format!("{}{path}", self.base))
86 .basic_auth(user, Some(password));
87 self.send(req, None).await
88 }
89
90 pub async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp {
91 self.send(
92 self.client.post(format!("{}{path}", self.base)).form(form),
93 cookie,
94 )
95 .await
96 }
97
98 pub async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response {
99 open_stream(&self.client, &format!("{}{path}", self.base), cookie).await
100 }
101
102 pub async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp {
103 let req = match cookie {
104 Some(cookie) => req.header(COOKIE, cookie),
105 None => req,
106 };
107 let res = req.send().await.expect("http request");
108 let status = res.status().as_u16();
109 let headers = res.headers().clone();
110 let body = res.text().await.expect("read body");
111 Resp {
112 status,
113 headers,
114 body,
115 }
116 }
117}
118
119pub fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {
120 resp.set_cookies().iter().find_map(|set| {
121 let pair = set.split(';').next()?;
122 let (name, value) = pair.split_once('=')?;
123 (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}"))
124 })
125}
126
127pub fn with_cookie(session: &str, res: &Resp, notice: &str) -> String {
128 let cookie = cookie_named(res, notice).expect("notice cookie");
129 format!("{session}; {cookie}")
130}
131
132pub async fn login(http: &Http, username: &str, password: &str) -> String {
133 let page = http.get("/login", None).await;
134 assert_eq!(page.status, 200, "GET /login");
135 let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie");
136 let precsrf = input_value(&page.body, "precsrf");
137 let res = http
138 .post_form(
139 "/login",
140 &[
141 ("username", username),
142 ("password", password),
143 ("next", "/"),
144 ("precsrf", &precsrf),
145 ],
146 Some(&precsrf_cookie),
147 )
148 .await;
149 assert_eq!(res.status, 303, "login as {username}: {}", res.body);
150 cookie_named(&res, "forge_session").expect("session cookie after login")
151}
152
153pub async fn csrf_for(http: &Http, path: &str, session: &str) -> String {
154 let page = http.get(path, Some(session)).await;
155 assert_eq!(page.status, 200, "GET {path}");
156 input_value(&page.body, "csrf")
157}
158
159pub async fn open_stream(
160 client: &reqwest::Client,
161 url: &str,
162 cookie: Option<&str>,
163) -> reqwest::Response {
164 let mut req = client.get(url);
165 if let Some(cookie) = cookie {
166 req = req.header(COOKIE, cookie);
167 }
168 let mut res = req.send().await.expect("stream request");
169 if res.status().is_success() {
170 let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk())
171 .await
172 .expect("the retry field")
173 .expect("stream chunk")
174 .expect("stream still open");
175 assert!(String::from_utf8_lossy(&retry).contains("retry: 1000"));
176 }
177 res
178}