forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

admin_client.rs258 lines, 9.6 KiBHistoryRawDownload
1//! The admin token file, and the CLI side of the admin routes on the internal socket.
2//!
3//! While the server runs it writes `data_dir/run/admin.token` (mode 0600, directory 0700) and
4//! serves `/internal/admin/*` on `data_dir/internal.sock`. The socket is 0600 and sits in the
5//! 0700 data dir, so only this user can reach it. Those routes also need the token. An `admin`
6//! command runs through the server when the socket answers, and runs against the database
7//! directly when it does not.
8
9use std::io::Write;
10use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
11use std::path::{Path, PathBuf};
12
13use forge_core::{Config, Error, Result};
14use serde::de::DeserializeOwned;
15use serde_json::Value;
16use tokio::io::{AsyncReadExt, AsyncWriteExt};
17use tokio::net::UnixStream;
18
19/// Header carrying the admin token on `/internal/admin/*`.
20pub const ADMIN_TOKEN_HEADER: &str = "x-forge-admin-token";
21const RUN_DIR: &str = "run";
22const TOKEN_FILE: &str = "admin.token";
23const SOCKET_FILE: &str = "internal.sock";
24
25/// Writes the per-boot admin token to `data_dir/run/admin.token`, replacing any earlier file.
26/// The file is created with mode 0600 and its directory is 0700.
27pub fn write_admin_token(data_dir: &Path, token: &str) -> Result<()> {
28 let run = data_dir.join(RUN_DIR);
29 std::fs::DirBuilder::new()
30 .recursive(true)
31 .mode(0o700)
32 .create(&run)?;
33 std::fs::set_permissions(&run, std::fs::Permissions::from_mode(0o700))?;
34 let path = run.join(TOKEN_FILE);
35 match std::fs::remove_file(&path) {
36 Ok(()) => {}
37 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
38 Err(e) => return Err(e.into()),
39 }
40 let mut file = std::fs::OpenOptions::new()
41 .write(true)
42 .create_new(true)
43 .mode(0o600)
44 .open(&path)?;
45 file.write_all(token.as_bytes())?;
46 file.sync_all()?;
47 Ok(())
48}
49
50/// Path of the admin token file for `data_dir`.
51pub fn admin_token_path(data_dir: &Path) -> PathBuf {
52 data_dir.join(RUN_DIR).join(TOKEN_FILE)
53}
54
55/// A server that answers on the internal socket.
56pub struct AdminClient {
57 socket: PathBuf,
58 token: String,
59}
60
61/// The running server, if one answers on its internal socket. `None` means nothing is listening
62/// (no socket, or a stale one), and the caller should work on the database directly. An error
63/// means a server is running but the CLI cannot talk to it.
64pub async fn running_server(config: &Config) -> Result<Option<AdminClient>> {
65 let socket = config.data_dir.join(SOCKET_FILE);
66 if !socket.exists() {
67 return Ok(None);
68 }
69 match UnixStream::connect(&socket).await {
70 Ok(stream) => drop(stream),
71 Err(e)
72 if matches!(
73 e.kind(),
74 std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound
75 ) =>
76 {
77 return Ok(None);
78 }
79 Err(e) => return Err(e.into()),
80 }
81 let path = admin_token_path(&config.data_dir);
82 let token = std::fs::read_to_string(&path).map_err(|e| {
83 Error::Config(format!(
84 "a server is running, but its admin token at {} cannot be read: {e}",
85 path.display()
86 ))
87 })?;
88 Ok(Some(AdminClient {
89 socket,
90 token: token.trim().to_owned(),
91 }))
92}
93
94/// How long a CLI write waits for the running server to answer a live notice.
95const NOTIFY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
96
97/// Tells the running server which open pages a CLI write changed (`/internal/admin/live`). Best
98/// effort: no server, a stale socket, a refusal or a timeout is logged at debug and ignored, so
99/// the command never fails because of it.
100pub async fn notify_live(config: &Config, body: Value) {
101 let server = match running_server(config).await {
102 Ok(Some(server)) => server,
103 Ok(None) => return,
104 Err(e) => {
105 tracing::debug!(error = %e, "live: no server to notify");
106 return;
107 }
108 };
109 match tokio::time::timeout(
110 NOTIFY_TIMEOUT,
111 server.post::<Value>("/internal/admin/live", &body),
112 )
113 .await
114 {
115 Ok(Ok(_)) => {}
116 Ok(Err(e)) => tracing::debug!(error = %e, "live: the server refused the notice"),
117 Err(_) => tracing::debug!("live: the server did not answer the notice in time"),
118 }
119}
120
121#[derive(serde::Deserialize)]
122struct ErrorBody {
123 error: String,
124}
125
126impl AdminClient {
127 /// Sends `body` as JSON to `path` and decodes the JSON answer. A refusal from the server
128 /// comes back as the matching error: 403 forbidden, 409 conflict, 400 invalid.
129 pub async fn post<T: DeserializeOwned>(&self, path: &str, body: &Value) -> Result<T> {
130 let payload = body.to_string();
131 let mut stream = UnixStream::connect(&self.socket).await?;
132 let head = format!(
133 "POST {path} HTTP/1.1\r\n\
134 Host: forge-internal\r\n\
135 Content-Type: application/json\r\n\
136 Content-Length: {}\r\n\
137 {ADMIN_TOKEN_HEADER}: {}\r\n\
138 Connection: close\r\n\r\n",
139 payload.len(),
140 self.token
141 );
142 stream.write_all(head.as_bytes()).await?;
143 stream.write_all(payload.as_bytes()).await?;
144 stream.flush().await?;
145 let mut raw = Vec::new();
146 stream.read_to_end(&mut raw).await?;
147 let (status, bytes) = crate::hook_cmd::parse_response(&raw)?;
148 if status == 200 {
149 return serde_json::from_slice(&bytes)
150 .map_err(|e| Error::Invalid(format!("unexpected answer from the server: {e}")));
151 }
152 let message = serde_json::from_slice::<ErrorBody>(&bytes)
153 .map(|b| b.error)
154 .unwrap_or_else(|_| String::from_utf8_lossy(&bytes).trim().to_owned());
155 Err(match status {
156 403 => Error::Forbidden(message),
157 409 => Error::Conflict(message),
158 400 => Error::Invalid(message),
159 _ => Error::Git(format!("server answered {status}: {message}")),
160 })
161 }
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167 use crate::backup::FsckSummary;
168 use crate::test_support::{ADMIN_TOKEN, test_config, test_state};
169 use topcoat::router::RouterService;
170
171 #[test]
172 fn token_file_is_private_and_replaced_on_each_boot() {
173 let dir = tempfile::tempdir().expect("tempdir");
174 write_admin_token(dir.path(), "first").expect("write");
175 let path = admin_token_path(dir.path());
176 assert_eq!(std::fs::read_to_string(&path).expect("read"), "first");
177 assert_eq!(
178 std::fs::metadata(&path).expect("meta").permissions().mode() & 0o777,
179 0o600
180 );
181 assert_eq!(
182 std::fs::metadata(path.parent().expect("run dir"))
183 .expect("meta")
184 .permissions()
185 .mode()
186 & 0o777,
187 0o700
188 );
189 write_admin_token(dir.path(), "second").expect("rewrite");
190 assert_eq!(std::fs::read_to_string(&path).expect("read"), "second");
191 }
192
193 #[tokio::test]
194 async fn no_socket_means_no_server() {
195 let dir = tempfile::tempdir().expect("tempdir");
196 let config = crate::test_support::test_config(dir.path());
197 assert!(running_server(&config).await.expect("probe").is_none());
198 }
199
200 #[tokio::test]
201 async fn stale_socket_means_no_server() {
202 let dir = tempfile::tempdir().expect("tempdir");
203 let config = crate::test_support::test_config(dir.path());
204 // A socket file with no listener behind it, left by a crashed server.
205 let listener =
206 std::os::unix::net::UnixListener::bind(dir.path().join(SOCKET_FILE)).expect("bind");
207 drop(listener);
208 assert!(running_server(&config).await.expect("probe").is_none());
209 }
210
211 /// Serves the internal router on a real unix socket, as boot does, and talks to it through
212 /// the client. Checks the answer, a refusal with the wrong token, and the no-server path.
213 #[tokio::test]
214 async fn client_talks_to_the_server_over_the_socket() {
215 let dir = tempfile::tempdir().expect("tempdir");
216 let data_dir = dir.path().join("data");
217 std::fs::create_dir_all(&data_dir).expect("data dir");
218 let state = test_state(&data_dir).await;
219 write_admin_token(&data_dir, ADMIN_TOKEN).expect("token");
220 let listener = tokio::net::UnixListener::bind(data_dir.join(SOCKET_FILE)).expect("bind");
221 let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
222 let server = tokio::spawn(topcoat::serve_until(
223 listener,
224 RouterService::new(crate::internal::router(state)),
225 async move {
226 let _ = stop_rx.await;
227 },
228 ));
229
230 let config = test_config(&data_dir);
231 let client = running_server(&config)
232 .await
233 .expect("probe")
234 .expect("the server is up");
235 let summary: FsckSummary = client
236 .post(
237 "/internal/admin/fsck",
238 &serde_json::json!({ "full": false }),
239 )
240 .await
241 .expect("fsck through the socket");
242 assert!(summary.is_ok());
243 assert_eq!(summary.repos, 0);
244
245 // The same route with a token that is not the admin token is refused.
246 let wrong = AdminClient {
247 socket: data_dir.join(SOCKET_FILE),
248 token: "not-the-token".into(),
249 };
250 let refused: Result<FsckSummary> = wrong
251 .post("/internal/admin/fsck", &serde_json::json!({}))
252 .await;
253 assert!(matches!(refused, Err(Error::Forbidden(_))), "{refused:?}");
254
255 let _ = stop_tx.send(());
256 let _ = server.await;
257 }
258}