|
| 1 | +/// On most systems we do not concern ourselves with local security [1], however on Android |
| 2 | +/// apps have their storage isolated yet ActivityWatch happily exposes its API and database |
| 3 | +/// through the HTTP API when the server is running. This could be considered a severe |
| 4 | +/// security flaw, and fixing it would significantly improve security on Android (as mentioned in [2]). |
| 5 | +/// |
| 6 | +/// Requiring an API key can also be useful in other scenarios where an extra level of security is |
| 7 | +/// desired. |
| 8 | +/// |
| 9 | +/// Based on the ApiKey example at [3]. |
| 10 | +/// |
| 11 | +/// [1]: https://docs.activitywatch.net/en/latest/security.html#activitywatch-is-only-as-secure-as-your-system |
| 12 | +/// [2]: https://forum.activitywatch.net/t/rest-api-supported-with-android-version-of-activity-watch/854/6?u=erikbjare |
| 13 | +/// [3]: https://api.rocket.rs/v0.4/rocket/request/trait.FromRequest.html |
| 14 | +use rocket::http::Status; |
| 15 | +use rocket::request::{self, FromRequest, Request}; |
| 16 | +use rocket::{Outcome, State}; |
| 17 | + |
| 18 | +use crate::config::AWConfig; |
| 19 | + |
| 20 | +struct ApiKey(Option<String>); |
| 21 | + |
| 22 | +#[derive(Debug)] |
| 23 | +enum ApiKeyError { |
| 24 | + BadCount, |
| 25 | + Missing, |
| 26 | + Invalid, |
| 27 | +} |
| 28 | + |
| 29 | +// TODO: Use guard on endpoints |
| 30 | +// TODO: Add tests for protected endpoints (important to ensure security) |
| 31 | +impl<'a, 'r> FromRequest<'a, 'r> for ApiKey { |
| 32 | + type Error = ApiKeyError; |
| 33 | + |
| 34 | + fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> { |
| 35 | + // TODO: How will this key be configured by the user? |
| 36 | + let config = request.guard::<State<AWConfig>>().unwrap(); |
| 37 | + match &config.apikey { |
| 38 | + None => Outcome::Success(ApiKey(None)), |
| 39 | + Some(apikey) => { |
| 40 | + // TODO: How will this header be set in the browser? |
| 41 | + let keys: Vec<_> = request.headers().get("x-api-key").collect(); |
| 42 | + match keys.len() { |
| 43 | + 0 => Outcome::Failure((Status::BadRequest, ApiKeyError::Missing)), |
| 44 | + 1 if apikey == keys[0] => Outcome::Success(ApiKey(Some(keys[0].to_string()))), |
| 45 | + 1 => Outcome::Failure((Status::BadRequest, ApiKeyError::Invalid)), |
| 46 | + _ => Outcome::Failure((Status::BadRequest, ApiKeyError::BadCount)), |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments