-
Notifications
You must be signed in to change notification settings - Fork 1
refactor: break up the three large modules in src/ #137
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2563fc1
refactor(services): split the domain services by domain
InstaZDLL 74a6451
refactor(subsonic): split the facade by method family
InstaZDLL f12e803
refactor(api): split the native surface and name it for what it serves
InstaZDLL 8cea5bb
docs(claude): record where the three surfaces now live
InstaZDLL 52fd5ef
fix(api): file the moved tests under the modules they cover
InstaZDLL a7facc1
docs(api): declare the responses and parameters that already exist
InstaZDLL e74b494
fix: seven defects the review found in the moved code
InstaZDLL 9c8873b
test(api): make the lagged-cursor test able to fail
InstaZDLL 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
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,143 @@ | ||
| //! Who is calling, and what their token is allowed to do. | ||
| //! | ||
| //! Split out of `http.rs`; `mod.rs` re-exports it, so `crate::api::*` paths are unchanged. | ||
|
|
||
| use super::*; | ||
|
|
||
| /// What a route needs of the credential it was called with. | ||
| /// | ||
| /// Chosen at every call of [`authenticated`], which is the only way into a | ||
| /// route, so a new route cannot be written without deciding: the compiler asks | ||
| /// the question. That is the whole reason this is a parameter rather than a | ||
| /// second helper a handler may forget to call — which is exactly what happened | ||
| /// to the scope list, stored since the foundations and read by nothing. | ||
| #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| pub(crate) enum Access { | ||
| /// Reads the caller's own catalogue and user data. | ||
| Read, | ||
| /// Writes on the caller's behalf: playlists, favorites, ratings, the | ||
| /// queue, bookmarks, shares, scrobbles and scans. | ||
| Write, | ||
| /// Acts on the instance: accounts, libraries, memberships, credentials. | ||
| Admin, | ||
| } | ||
|
|
||
| /// The scope that admits the administrative routes. | ||
| pub(super) const ADMIN_SCOPE: &str = "admin"; | ||
|
|
||
| /// The scope that admits any mutation. | ||
| pub(super) const WRITE_SCOPE: &str = "write"; | ||
|
|
||
| impl Access { | ||
| /// Whether a credential carrying `scopes` may do this. | ||
| /// | ||
| /// An empty list is unrestricted: a session, an OAuth grant and a token | ||
| /// issued without scopes all carry the account's full authority, so nothing | ||
| /// that works today stops working. | ||
| /// | ||
| /// A non-empty list grants only what it names, and a name this server does | ||
| /// not know grants nothing — so `catalog:read` reads and does no more, | ||
| /// without needing a vocabulary of every possible scope. `admin` implies | ||
| /// `write`: a credential trusted to create accounts is not usefully barred | ||
| /// from creating a playlist, and the surprise would be the other way round. | ||
| fn granted_by(self, scopes: &[String]) -> bool { | ||
| if scopes.is_empty() { | ||
| return true; | ||
| } | ||
| let holds = |wanted: &str| scopes.iter().any(|scope| scope == wanted); | ||
| match self { | ||
| Self::Read => true, | ||
| Self::Write => holds(WRITE_SCOPE) || holds(ADMIN_SCOPE), | ||
| Self::Admin => holds(ADMIN_SCOPE), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Resolves the caller and checks, in one place, that the credential may do | ||
| /// what the route is about to do. | ||
| /// | ||
| /// Both halves of administrative authority live here: an active administrator, | ||
| /// on a credential that has not been narrowed away from it. A token cannot | ||
| /// promote an ordinary account, and an administrator's token is not widened by | ||
| /// whose account it belongs to. | ||
| /// | ||
| /// It could widen itself, once: minting a session through the authorization | ||
| /// code flow returned one carrying the account's whole authority, whatever the | ||
| /// credential that asked. That is closed where it belongs now — the grant | ||
| /// records the caller's scopes and the session inherits them — rather than by | ||
| /// a rule this function has to know about. | ||
| pub(crate) async fn authenticated( | ||
| state: &AppState, | ||
| headers: &HeaderMap, | ||
| access: Access, | ||
| ) -> Result<crate::authentication::AuthUser, ApiError> { | ||
| let token = bearer_token(headers).ok_or(ApiError::Unauthorized)?; | ||
| let user = state | ||
| .auth | ||
| .authenticate(token) | ||
| .await | ||
| .map_err(ApiError::from)?; | ||
| let role_ok = access != Access::Admin || user.role == crate::database::AccountRole::Admin; | ||
| if role_ok && access.granted_by(&user.scopes) { | ||
| Ok(user) | ||
| } else { | ||
| Err(ApiError::Forbidden) | ||
| } | ||
| } | ||
|
|
||
| /// The bearer token, whatever case the client spelled the scheme in. | ||
| /// | ||
| /// RFC 7235 §2.1 makes the scheme name case-insensitive, so `bearer` is as | ||
| /// valid as `Bearer`. Matching the spelling exactly turned a conforming client | ||
| /// away as unauthenticated. | ||
| pub(super) fn bearer_token(headers: &HeaderMap) -> Option<&str> { | ||
| let (scheme, token) = headers | ||
| .get(header::AUTHORIZATION)? | ||
| .to_str() | ||
| .ok()? | ||
| .split_once(' ')?; | ||
| scheme | ||
| .eq_ignore_ascii_case("Bearer") | ||
| .then_some(token) | ||
| .filter(|token| !token.is_empty()) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| pub(super) async fn mutation_context( | ||
| state: &AppState, | ||
| headers: &HeaderMap, | ||
| user_id: Uuid, | ||
| ) -> Result<crate::sync::MutationContext, ApiError> { | ||
| let operation_id = | ||
| optional_uuid_header(headers, OPERATION_ID_HEADER)?.unwrap_or_else(Uuid::new_v4); | ||
| let origin_device_id = optional_uuid_header(headers, DEVICE_ID_HEADER)?; | ||
| if let Some(device_id) = origin_device_id { | ||
| let owned = state | ||
| .sync | ||
| .device_belongs_to_user(user_id, device_id) | ||
| .await | ||
| .map_err(db_error)?; | ||
| if !owned { | ||
| return Err(ApiError::Validation); | ||
| } | ||
| } | ||
| Ok(crate::sync::MutationContext { | ||
| operation_id, | ||
| origin_device_id, | ||
| }) | ||
| } | ||
|
|
||
| pub(super) fn optional_uuid_header( | ||
| headers: &HeaderMap, | ||
| name: &'static str, | ||
| ) -> Result<Option<Uuid>, ApiError> { | ||
| headers | ||
| .get(name) | ||
| .map(|value| { | ||
| value | ||
| .to_str() | ||
| .ok() | ||
| .and_then(|value| Uuid::parse_str(value).ok()) | ||
| .ok_or(ApiError::Validation) | ||
| }) | ||
| .transpose() | ||
| } | ||
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,178 @@ | ||
| //! Login, refresh and logout, for native clients and for the browser. | ||
| //! | ||
| //! Split out of `http.rs`; `mod.rs` re-exports it, so `crate::api::*` paths are unchanged. | ||
|
|
||
| use super::*; | ||
|
|
||
| #[derive(Debug, Deserialize, ToSchema)] | ||
| pub struct LoginRequest { | ||
| pub username: String, | ||
| pub password: String, | ||
| pub device_name: String, | ||
| } | ||
|
|
||
| #[derive(Debug, Deserialize, ToSchema)] | ||
| pub struct RefreshRequest { | ||
| pub refresh_token: String, | ||
| } | ||
|
|
||
| #[utoipa::path( | ||
| post, | ||
| path = "/api/v2/auth/login", | ||
| tag = "authentication", | ||
| request_body = LoginRequest, | ||
| responses( | ||
| (status = 200, body = crate::authentication::AuthTokens), | ||
| (status = 401, body = ErrorResponse), | ||
| (status = 422, body = ErrorResponse), | ||
| (status = 503, body = ErrorResponse) | ||
| ) | ||
| )] | ||
| pub async fn login( | ||
| State(state): State<AppState>, | ||
| Json(request): Json<LoginRequest>, | ||
| ) -> Result<Json<crate::authentication::AuthTokens>, ApiError> { | ||
| state | ||
| .auth | ||
| .login(&request.username, &request.password, &request.device_name) | ||
| .await | ||
| .map(Json) | ||
| .map_err(ApiError::from) | ||
| } | ||
|
|
||
| #[utoipa::path( | ||
| post, | ||
| path = "/api/v2/auth/refresh", | ||
| tag = "authentication", | ||
| request_body = RefreshRequest, | ||
| responses( | ||
| (status = 200, body = crate::authentication::AuthTokens), | ||
| (status = 401, body = ErrorResponse), | ||
| (status = 503, body = ErrorResponse) | ||
| ) | ||
| )] | ||
| pub async fn refresh( | ||
| State(state): State<AppState>, | ||
| Json(request): Json<RefreshRequest>, | ||
| ) -> Result<Json<crate::authentication::AuthTokens>, ApiError> { | ||
| state | ||
| .auth | ||
| .refresh(&request.refresh_token) | ||
| .await | ||
| .map(Json) | ||
| .map_err(ApiError::from) | ||
| } | ||
|
|
||
| #[utoipa::path( | ||
| post, | ||
| path = "/api/v2/auth/logout", | ||
| tag = "authentication", | ||
| responses( | ||
| (status = 204), | ||
| (status = 401, body = ErrorResponse), | ||
| (status = 503, body = ErrorResponse) | ||
| ) | ||
| )] | ||
| pub async fn logout( | ||
| State(state): State<AppState>, | ||
| headers: HeaderMap, | ||
| ) -> Result<StatusCode, ApiError> { | ||
| let access_token = bearer_token(&headers).ok_or(ApiError::Unauthorized)?; | ||
| state | ||
| .auth | ||
| .logout(access_token) | ||
| .await | ||
| .map_err(ApiError::from)?; | ||
| Ok(StatusCode::NO_CONTENT) | ||
| } | ||
|
|
||
| /// Browser sessions keep only the short-lived access token in JavaScript. The | ||
| /// rotating refresh token is an HttpOnly, same-site cookie and is therefore | ||
| /// never exposed to the embedded SPA. | ||
| #[utoipa::path( | ||
| post, | ||
| path = "/api/v2/web/auth/login", | ||
| tag = "authentication", | ||
| request_body = LoginRequest, | ||
| responses( | ||
| (status = 200, body = WebAuthResponse), | ||
| (status = 401, body = ErrorResponse), | ||
| (status = 403, body = ErrorResponse), | ||
| (status = 422, body = ErrorResponse), | ||
| (status = 503, body = ErrorResponse) | ||
| ) | ||
| )] | ||
|
InstaZDLL marked this conversation as resolved.
|
||
| pub async fn web_login( | ||
| State(state): State<AppState>, | ||
| headers: HeaderMap, | ||
| Json(request): Json<LoginRequest>, | ||
| ) -> Result<Response, ApiError> { | ||
| validate_web_origin(&state, &headers)?; | ||
| let tokens = state | ||
| .auth | ||
| .login(&request.username, &request.password, &request.device_name) | ||
| .await | ||
| .map_err(ApiError::from)?; | ||
| web_auth_response(&state, &headers, tokens) | ||
| } | ||
|
|
||
| #[utoipa::path( | ||
| post, | ||
| path = "/api/v2/web/auth/refresh", | ||
| tag = "authentication", | ||
| responses( | ||
| (status = 200, body = WebAuthResponse), | ||
| (status = 401, body = ErrorResponse), | ||
| (status = 403, body = ErrorResponse), | ||
| (status = 503, body = ErrorResponse) | ||
| ) | ||
| )] | ||
| pub async fn web_refresh( | ||
| State(state): State<AppState>, | ||
| headers: HeaderMap, | ||
| ) -> Result<Response, ApiError> { | ||
| validate_web_request(&state, &headers)?; | ||
| let refresh_token = cookie_value(&headers, WEB_REFRESH_COOKIE).ok_or(ApiError::Unauthorized)?; | ||
| let tokens = state | ||
| .auth | ||
| .refresh(refresh_token) | ||
| .await | ||
| .map_err(ApiError::from)?; | ||
| web_auth_response(&state, &headers, tokens) | ||
| } | ||
|
|
||
| #[utoipa::path( | ||
| post, | ||
| path = "/api/v2/web/auth/logout", | ||
| tag = "authentication", | ||
| responses( | ||
| (status = 204), | ||
| (status = 401, body = ErrorResponse), | ||
| (status = 403, body = ErrorResponse), | ||
| (status = 503, body = ErrorResponse) | ||
| ) | ||
| )] | ||
| pub async fn web_logout( | ||
| State(state): State<AppState>, | ||
| headers: HeaderMap, | ||
| ) -> Result<Response, ApiError> { | ||
| validate_web_request(&state, &headers)?; | ||
| let result = match cookie_value(&headers, WEB_REFRESH_COOKIE) { | ||
| Some(refresh_token) => state.auth.revoke_refresh(refresh_token).await, | ||
| None => Err(AuthError::InvalidRefreshToken), | ||
| }; | ||
| let mut response = match result { | ||
| Ok(()) => StatusCode::NO_CONTENT.into_response(), | ||
| Err(error) => ApiError::from(error).into_response(), | ||
| }; | ||
| let secure = secure_cookies(&state); | ||
| append_cookie( | ||
| &mut response, | ||
| expired_cookie(WEB_REFRESH_COOKIE, true, secure), | ||
| )?; | ||
| append_cookie( | ||
| &mut response, | ||
| expired_cookie(WEB_CSRF_COOKIE, false, secure), | ||
| )?; | ||
| Ok(response) | ||
| } | ||
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.