-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat(mobile): identify clients to Buzz servers #2596
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
Closed
Closed
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
454719f
feat(mobile): identify clients to Buzz servers
cb04e92
Merge origin/main into mobile-client-headers
442bffd
Merge origin/main into mobile-client-headers
b5d0670
fix(mobile): harden advisory client headers
94db169
fix(client-info): address review edge cases
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| //! Advisory parsing for the mobile `Buzz-Client` structured field. | ||
|
|
||
| use std::convert::Infallible; | ||
|
|
||
| use axum::{ | ||
| extract::OptionalFromRequestParts, | ||
| http::{request::Parts, HeaderMap}, | ||
| }; | ||
| use sfv::{BareItem, Dictionary, ListEntry, Parser}; | ||
|
|
||
| /// Parsed, untrusted metadata supplied by a Buzz client. | ||
| /// | ||
| /// This data is for observability only. It must never participate in | ||
| /// authentication, authorization, or tenant selection. | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| pub struct ClientInfo { | ||
| /// Structured header format version. | ||
| pub format_version: i64, | ||
| /// Logical application identifier. | ||
| pub app: String, | ||
| /// Client platform (`ios` or `android`). | ||
| pub platform: String, | ||
| /// User-visible application version. | ||
| pub app_version: String, | ||
| /// Platform build identifier, constrained to decimal digits. | ||
| pub app_build: String, | ||
| /// Coarse public operating-system version. | ||
| pub os_version: String, | ||
| /// Android API level, present only on Android. | ||
| pub os_api: Option<i64>, | ||
| } | ||
|
|
||
| impl ClientInfo { | ||
| /// Parse `Buzz-Client` from a request header map. | ||
| /// | ||
| /// A missing header is a supported state and returns `None` without a | ||
| /// metric. A present but invalid header increments the parse-failure | ||
| /// counter and also returns `None`, so it can never reject a request. | ||
| #[must_use] | ||
| pub fn from_headers(headers: &HeaderMap) -> Option<Self> { | ||
| let value = headers.get("buzz-client")?; | ||
| let parsed = value.to_str().ok().and_then(|raw| Self::parse(raw).ok()); | ||
| if parsed.is_none() { | ||
| metrics::counter!("buzz_client_header_parse_failures_total").increment(1); | ||
| } | ||
| parsed | ||
| } | ||
|
|
||
| fn parse(raw: &str) -> Result<Self, ()> { | ||
| let dictionary: Dictionary = Parser::new(raw).parse_dictionary().map_err(|_| ())?; | ||
|
|
||
| let format_version = integer(&dictionary, "v")?; | ||
| if format_version != 1 { | ||
| return Err(()); | ||
| } | ||
|
|
||
| let app = token(&dictionary, "app")?; | ||
| if app != "buzz-mobile" { | ||
| return Err(()); | ||
| } | ||
|
|
||
| let platform = token(&dictionary, "platform")?; | ||
| if platform != "ios" && platform != "android" { | ||
| return Err(()); | ||
| } | ||
|
|
||
| let app_version = string(&dictionary, "app-version")?; | ||
| let app_build = string(&dictionary, "app-build")?; | ||
| let os_version = string(&dictionary, "os-version")?; | ||
| if app_version.is_empty() | ||
| || app_build.is_empty() | ||
| || !app_build.bytes().all(|byte| byte.is_ascii_digit()) | ||
| || os_version.is_empty() | ||
| { | ||
| return Err(()); | ||
| } | ||
|
|
||
| let os_api = optional_integer(&dictionary, "os-api")?; | ||
| match platform.as_str() { | ||
| "android" if !matches!(os_api, Some(api) if api > 0) => return Err(()), | ||
| "ios" if os_api.is_some() => return Err(()), | ||
| _ => {} | ||
| } | ||
|
|
||
| Ok(Self { | ||
| format_version, | ||
| app, | ||
| platform, | ||
| app_version, | ||
| app_build, | ||
| os_version, | ||
| os_api, | ||
| }) | ||
| } | ||
|
|
||
| /// Record a low-cardinality observation for a parsed client. | ||
| pub fn record_observation(&self) { | ||
| metrics::counter!( | ||
| "buzz_client_requests_total", | ||
| "app" => self.app.clone(), | ||
| "platform" => self.platform.clone(), | ||
| "app_version" => self.app_version.clone(), | ||
| ) | ||
| .increment(1); | ||
| } | ||
|
brow marked this conversation as resolved.
|
||
| } | ||
|
|
||
| impl<S> OptionalFromRequestParts<S> for ClientInfo | ||
|
brow marked this conversation as resolved.
Outdated
|
||
| where | ||
| S: Send + Sync, | ||
| { | ||
| type Rejection = Infallible; | ||
|
|
||
| async fn from_request_parts( | ||
| parts: &mut Parts, | ||
| _state: &S, | ||
| ) -> Result<Option<Self>, Self::Rejection> { | ||
| Ok(Self::from_headers(&parts.headers)) | ||
| } | ||
| } | ||
|
|
||
| fn bare_item<'a>(dictionary: &'a Dictionary, key: &str) -> Result<&'a BareItem, ()> { | ||
| let Some(ListEntry::Item(item)) = dictionary.get(key) else { | ||
| return Err(()); | ||
| }; | ||
| if !item.params.is_empty() { | ||
| return Err(()); | ||
| } | ||
| Ok(&item.bare_item) | ||
| } | ||
|
|
||
| fn token(dictionary: &Dictionary, key: &str) -> Result<String, ()> { | ||
| bare_item(dictionary, key)? | ||
| .as_token() | ||
| .map(|value| value.as_str().to_owned()) | ||
| .ok_or(()) | ||
| } | ||
|
|
||
| fn string(dictionary: &Dictionary, key: &str) -> Result<String, ()> { | ||
| bare_item(dictionary, key)? | ||
| .as_string() | ||
| .map(|value| value.as_str().to_owned()) | ||
| .ok_or(()) | ||
| } | ||
|
|
||
| fn integer(dictionary: &Dictionary, key: &str) -> Result<i64, ()> { | ||
| bare_item(dictionary, key)? | ||
| .as_integer() | ||
| .map(Into::into) | ||
| .ok_or(()) | ||
| } | ||
|
|
||
| fn optional_integer(dictionary: &Dictionary, key: &str) -> Result<Option<i64>, ()> { | ||
| if !dictionary.contains_key(key) { | ||
| return Ok(None); | ||
| } | ||
| integer(dictionary, key).map(Some) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use axum::http::{HeaderMap, HeaderValue}; | ||
| use metrics_util::debugging::{DebugValue, DebuggingRecorder}; | ||
|
|
||
| use super::*; | ||
|
|
||
| fn parse_failures(recorder: &DebuggingRecorder) -> u64 { | ||
| recorder | ||
| .snapshotter() | ||
| .snapshot() | ||
| .into_vec() | ||
| .into_iter() | ||
| .find_map(|(key, _, _, value)| { | ||
| (key.key().name() == "buzz_client_header_parse_failures_total").then_some(value) | ||
| }) | ||
| .map(|value| match value { | ||
| DebugValue::Counter(value) => value, | ||
| _ => panic!("parse failures must be a counter"), | ||
| }) | ||
| .unwrap_or_default() | ||
| } | ||
|
|
||
| #[test] | ||
| fn parses_valid_ios_and_android_headers() { | ||
| let ios = ClientInfo::parse( | ||
| r#"v=1, app=buzz-mobile, platform=ios, app-version="0.4.5", app-build="6", os-version="18.5""#, | ||
| ) | ||
| .expect("valid iOS header"); | ||
| assert_eq!( | ||
| ios, | ||
| ClientInfo { | ||
| format_version: 1, | ||
| app: "buzz-mobile".to_owned(), | ||
| platform: "ios".to_owned(), | ||
| app_version: "0.4.5".to_owned(), | ||
| app_build: "6".to_owned(), | ||
| os_version: "18.5".to_owned(), | ||
| os_api: None, | ||
| } | ||
| ); | ||
|
|
||
| let android = ClientInfo::parse( | ||
| r#"v=1, app=buzz-mobile, platform=android, app-version="0.4.5", app-build="7", os-version="15", os-api=35, future-key=ignored"#, | ||
| ) | ||
| .expect("valid Android header"); | ||
| assert_eq!(android.os_api, Some(35)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn missing_header_is_absent_without_parse_failure() { | ||
| let recorder = DebuggingRecorder::new(); | ||
| metrics::with_local_recorder(&recorder, || { | ||
| assert_eq!(ClientInfo::from_headers(&HeaderMap::new()), None); | ||
| }); | ||
| assert_eq!(parse_failures(&recorder), 0); | ||
| } | ||
|
|
||
| #[test] | ||
| fn malformed_or_semantically_invalid_header_is_absent_and_counted() { | ||
| for raw in [ | ||
| "not a dictionary", | ||
| r#"v=2, app=buzz-mobile, platform=ios, app-version="1", app-build="1", os-version="18""#, | ||
| r#"v=1, app=buzz-mobile, platform=android, app-version="1", app-build="1", os-version="15""#, | ||
| r#"v=1, app=buzz-mobile, platform=ios, app-version="1", app-build="1.beta", os-version="18""#, | ||
| ] { | ||
| let recorder = DebuggingRecorder::new(); | ||
| let mut headers = HeaderMap::new(); | ||
| headers.insert( | ||
| "buzz-client", | ||
| HeaderValue::from_str(raw).expect("test header value"), | ||
| ); | ||
| metrics::with_local_recorder(&recorder, || { | ||
| assert_eq!(ClientInfo::from_headers(&headers), None, "{raw}"); | ||
| }); | ||
| assert_eq!(parse_failures(&recorder), 1, "{raw}"); | ||
| } | ||
| } | ||
| } | ||
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
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.