-
Notifications
You must be signed in to change notification settings - Fork 2
Add admin log download endpoint #68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
findolor
wants to merge
5
commits into
main
Choose a base branch
from
download-todays-logs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
829e58d
Split admin routes and add log downloads
findolor 1e899af
Introduce typed path config for logs
findolor b32f969
Update Cargo.lock
findolor 227f208
Refine admin log handling
findolor 2f39983
Log rejected admin log dates
findolor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| use chrono::NaiveDate; | ||
| use std::path::{Path, PathBuf}; | ||
|
|
||
| pub const LOG_FILE_BASENAME: &str = "st0x-rest-api.log"; | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub struct LogFiles { | ||
| root: PathBuf, | ||
| } | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub struct LogFile { | ||
| path: PathBuf, | ||
| download_filename: String, | ||
| } | ||
|
|
||
| impl LogFiles { | ||
| pub fn new(root: impl Into<PathBuf>) -> Self { | ||
| Self { root: root.into() } | ||
| } | ||
|
|
||
| pub fn file_for_date(&self, date: NaiveDate) -> LogFile { | ||
| let formatted_date = date.format("%Y-%m-%d"); | ||
| LogFile { | ||
| path: self | ||
| .root | ||
| .join(format!("{LOG_FILE_BASENAME}.{formatted_date}")), | ||
| download_filename: format!("st0x-rest-api-{formatted_date}.log"), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl LogFile { | ||
| pub fn path(&self) -> &Path { | ||
| &self.path | ||
| } | ||
|
|
||
| pub fn download_filename(&self) -> &str { | ||
| &self.download_filename | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn builds_expected_daily_log_path_and_filename() { | ||
| let logs = LogFiles::new("/tmp/st0x-logs"); | ||
| let date = NaiveDate::from_ymd_opt(2026, 3, 13).expect("valid test date"); | ||
|
|
||
| let file = logs.file_for_date(date); | ||
|
|
||
| assert_eq!( | ||
| file.path(), | ||
| Path::new("/tmp/st0x-logs/st0x-rest-api.log.2026-03-13") | ||
| ); | ||
| assert_eq!(file.download_filename(), "st0x-rest-api-2026-03-13.log"); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,229 @@ | ||
| use crate::auth::AdminKey; | ||
| use crate::error::ApiError; | ||
| use crate::fairings::{GlobalRateLimit, TracingSpan}; | ||
| use crate::log_files::LogFiles; | ||
| use chrono::NaiveDate; | ||
| use rocket::form::FromForm; | ||
| use rocket::fs::NamedFile; | ||
| use rocket::http::{ContentType, Header}; | ||
| use rocket::request::Request; | ||
| use rocket::response::Responder; | ||
| use rocket::{Route, State}; | ||
| use tracing::Instrument; | ||
|
|
||
| #[derive(Debug, Clone, FromForm)] | ||
| pub struct AdminLogDownloadParams { | ||
| pub date: Option<String>, | ||
| } | ||
|
|
||
| pub struct AdminLogDownload { | ||
| file: NamedFile, | ||
| filename: String, | ||
| } | ||
|
|
||
| impl<'r> Responder<'r, 'static> for AdminLogDownload { | ||
| fn respond_to(self, req: &'r Request<'_>) -> rocket::response::Result<'static> { | ||
| let mut response = self.file.respond_to(req)?; | ||
| response.set_header(ContentType::Binary); | ||
| response.set_header(Header::new( | ||
| "Content-Disposition", | ||
| format!("attachment; filename=\"{}\"", self.filename), | ||
| )); | ||
| Ok(response) | ||
| } | ||
| } | ||
|
|
||
| fn parse_log_date(params: &AdminLogDownloadParams) -> Result<NaiveDate, ApiError> { | ||
| let Some(date) = params.date.as_deref() else { | ||
| tracing::warn!("missing required date query parameter"); | ||
| return Err(ApiError::BadRequest( | ||
| "date query parameter is required".into(), | ||
| )); | ||
| }; | ||
|
|
||
| NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| { | ||
| tracing::warn!(date = %date, "rejected invalid log download date"); | ||
| ApiError::BadRequest("date must use YYYY-MM-DD format".into()) | ||
| }) | ||
| } | ||
|
|
||
| #[get("/logs?<params..>")] | ||
| pub async fn get_logs( | ||
| _global: GlobalRateLimit, | ||
| _admin: AdminKey, | ||
| log_files: &State<LogFiles>, | ||
| span: TracingSpan, | ||
| params: AdminLogDownloadParams, | ||
| ) -> Result<AdminLogDownload, ApiError> { | ||
| async move { | ||
| tracing::info!(date = ?params.date, "request received"); | ||
|
|
||
| let date = parse_log_date(¶ms)?; | ||
| let log_file = log_files.file_for_date(date); | ||
| let log_path = log_file.path().to_path_buf(); | ||
|
|
||
| tracing::info!(path = %log_path.display(), "resolved log file path"); | ||
|
|
||
| let file = NamedFile::open(&log_path).await.map_err(|e| { | ||
| if e.kind() == std::io::ErrorKind::NotFound { | ||
| tracing::warn!(path = %log_path.display(), "requested log file not found"); | ||
| ApiError::NotFound("log file not found".into()) | ||
| } else { | ||
| tracing::error!(path = %log_path.display(), error = %e, "failed to open log file"); | ||
| ApiError::Internal("failed to open log file".into()) | ||
| } | ||
| })?; | ||
|
|
||
| tracing::info!( | ||
| path = %log_path.display(), | ||
| filename = %log_file.download_filename(), | ||
| "serving log file" | ||
| ); | ||
|
|
||
| Ok(AdminLogDownload { | ||
| file, | ||
| filename: log_file.download_filename().to_string(), | ||
| }) | ||
| } | ||
| .instrument(span.0) | ||
| .await | ||
| } | ||
|
|
||
| pub fn routes() -> Vec<Route> { | ||
| rocket::routes![get_logs] | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use crate::test_helpers::{basic_auth_header, seed_admin_key, seed_api_key, TestClientBuilder}; | ||
| use rocket::http::{ContentType, Header, Status}; | ||
| use tempfile::TempDir; | ||
|
|
||
| fn write_log_file(temp_dir: &TempDir, date: &str, contents: &str) { | ||
| let path = temp_dir | ||
| .path() | ||
| .join(format!("{}.{date}", crate::log_files::LOG_FILE_BASENAME)); | ||
| std::fs::write(path, contents).expect("write log file"); | ||
| } | ||
|
|
||
| #[rocket::async_test] | ||
| async fn test_get_logs_with_admin_key() { | ||
| let temp_dir = TempDir::new().expect("temp dir"); | ||
| write_log_file(&temp_dir, "2026-03-13", "line one\nline two\n"); | ||
|
|
||
| let client = TestClientBuilder::new() | ||
| .log_dir(temp_dir.path()) | ||
| .build() | ||
| .await; | ||
| let (key_id, secret) = seed_admin_key(&client).await; | ||
| let header = basic_auth_header(&key_id, &secret); | ||
|
|
||
| let response = client | ||
| .get("/admin/logs?date=2026-03-13") | ||
| .header(Header::new("Authorization", header)) | ||
| .dispatch() | ||
| .await; | ||
|
|
||
| assert_eq!(response.status(), Status::Ok); | ||
| assert_eq!(response.content_type(), Some(ContentType::Binary)); | ||
| assert_eq!( | ||
| response.headers().get_one("Content-Disposition"), | ||
| Some("attachment; filename=\"st0x-rest-api-2026-03-13.log\"") | ||
| ); | ||
| assert_eq!( | ||
| response.into_string().await.unwrap(), | ||
| "line one\nline two\n".to_string() | ||
| ); | ||
| } | ||
|
|
||
| #[rocket::async_test] | ||
| async fn test_get_logs_with_non_admin_key_returns_403() { | ||
| let temp_dir = TempDir::new().expect("temp dir"); | ||
| write_log_file(&temp_dir, "2026-03-13", "line one\n"); | ||
|
|
||
| let client = TestClientBuilder::new() | ||
| .log_dir(temp_dir.path()) | ||
| .build() | ||
| .await; | ||
| let (key_id, secret) = seed_api_key(&client).await; | ||
| let header = basic_auth_header(&key_id, &secret); | ||
|
|
||
| let response = client | ||
| .get("/admin/logs?date=2026-03-13") | ||
| .header(Header::new("Authorization", header)) | ||
| .dispatch() | ||
| .await; | ||
|
|
||
| assert_eq!(response.status(), Status::Forbidden); | ||
| } | ||
|
|
||
| #[rocket::async_test] | ||
| async fn test_get_logs_without_auth_returns_401() { | ||
| let client = TestClientBuilder::new().build().await; | ||
|
|
||
| let response = client.get("/admin/logs?date=2026-03-13").dispatch().await; | ||
|
|
||
| assert_eq!(response.status(), Status::Unauthorized); | ||
| } | ||
|
|
||
| #[rocket::async_test] | ||
| async fn test_get_logs_with_invalid_date_returns_400() { | ||
| let client = TestClientBuilder::new().build().await; | ||
| let (key_id, secret) = seed_admin_key(&client).await; | ||
| let header = basic_auth_header(&key_id, &secret); | ||
|
|
||
| let response = client | ||
| .get("/admin/logs?date=2026-13-40") | ||
| .header(Header::new("Authorization", header)) | ||
| .dispatch() | ||
| .await; | ||
|
|
||
| assert_eq!(response.status(), Status::BadRequest); | ||
| let body: serde_json::Value = | ||
| serde_json::from_str(&response.into_string().await.unwrap()).unwrap(); | ||
| assert_eq!(body["error"]["code"], "BAD_REQUEST"); | ||
| assert_eq!(body["error"]["message"], "date must use YYYY-MM-DD format"); | ||
| } | ||
|
|
||
| #[rocket::async_test] | ||
| async fn test_get_logs_without_date_returns_400() { | ||
| let client = TestClientBuilder::new().build().await; | ||
| let (key_id, secret) = seed_admin_key(&client).await; | ||
| let header = basic_auth_header(&key_id, &secret); | ||
|
|
||
| let response = client | ||
| .get("/admin/logs") | ||
| .header(Header::new("Authorization", header)) | ||
| .dispatch() | ||
| .await; | ||
|
|
||
| assert_eq!(response.status(), Status::BadRequest); | ||
| let body: serde_json::Value = | ||
| serde_json::from_str(&response.into_string().await.unwrap()).unwrap(); | ||
| assert_eq!(body["error"]["code"], "BAD_REQUEST"); | ||
| assert_eq!(body["error"]["message"], "date query parameter is required"); | ||
| } | ||
|
|
||
| #[rocket::async_test] | ||
| async fn test_get_logs_when_file_is_missing_returns_404() { | ||
| let temp_dir = TempDir::new().expect("temp dir"); | ||
| let client = TestClientBuilder::new() | ||
| .log_dir(temp_dir.path()) | ||
| .build() | ||
| .await; | ||
| let (key_id, secret) = seed_admin_key(&client).await; | ||
| let header = basic_auth_header(&key_id, &secret); | ||
|
|
||
| let response = client | ||
| .get("/admin/logs?date=2026-03-13") | ||
| .header(Header::new("Authorization", header)) | ||
| .dispatch() | ||
| .await; | ||
|
|
||
| assert_eq!(response.status(), Status::NotFound); | ||
| let body: serde_json::Value = | ||
| serde_json::from_str(&response.into_string().await.unwrap()).unwrap(); | ||
| assert_eq!(body["error"]["code"], "NOT_FOUND"); | ||
| assert_eq!(body["error"]["message"], "log file not found"); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| mod logs; | ||
| mod registry; | ||
|
|
||
| use rocket::Route; | ||
|
|
||
| pub fn routes() -> Vec<Route> { | ||
| let mut routes = Vec::new(); | ||
| routes.extend(registry::routes()); | ||
| routes.extend(logs::routes()); | ||
| routes | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.