diff --git a/.github/workflows/live-esi.yml b/.github/workflows/live-esi.yml new file mode 100644 index 0000000..56e53f6 --- /dev/null +++ b/.github/workflows/live-esi.yml @@ -0,0 +1,47 @@ +name: Live ESI + +# Runs the smoke test against the live ESI API (`tests/live.rs`, ignored in +# the normal test run): one public endpoint of every group, read into the +# type the crate returns. It finds a change in what ESI sends that the OpenAPI +# spec does not show (`spec-diff.yml` covers the spec itself). It runs weekly +# and can be run by hand. +# +# ESI is a public service: if it is down or throttling, the run fails for +# that reason. The test is tried twice before the job gives up. +on: + schedule: + - cron: "47 6 * * 3" + workflow_dispatch: + +permissions: + contents: read + +env: + CARGO_INCREMENTAL: 0 + CARGO_NET_RETRY: 10 + CARGO_TERM_COLOR: always + CARGO_HTTP_MULTIPLEXING: false + CARGO_PROFILE_DEV_DEBUG: line-tables-only + +jobs: + live: + name: live + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + with: + shared-key: live-esi + cache-on-failure: true + - name: Smoke test the public endpoints + run: | + for attempt in 1 2; do + if cargo test --test live -- --ignored --nocapture; then + exit 0 + fi + echo "::warning::attempt $attempt failed" + sleep 60 + done + exit 1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cd5cd3..6915f8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,24 @@ All notable changes to this project are documented here. This project is a fork of [rfesi](https://github.com/Celeo/rfesi) 0.50.2; versioning restarts at 0.1.0. -## [Unreleased] +## [0.3.0] - 2026-11-04 + +### Fixed + +- `UniverseGroup::get_bloodlines` no longer fails as a whole: ESI sends `null` as the `ship_type_id` of six bloodlines although the spec requires it, so `Bloodline::ship_type_id` is now `Option` (**breaking** for code that reads it). +- Validating the SSO token now requires the `aud` claim to contain the client ID. Before, a token issued for another application was accepted, because every token lists `EVE Online` as an audience. +- Requests with a body (`POST`, `PUT`) now send `Content-Type: application/json`; before, no content type was sent. +- A client with an access token but no expiration no longer panics on an authenticated request: the token is sent and ESI decides whether it is still valid. +- Validating the SSO token no longer panics on a malformed key set or on a token without an `iss` claim; both return `EsiError::InvalidJWT`. A failing status when fetching the keys is now reported as `EsiError::InvalidStatusCode`. +- `FittingsGroup::create_character_fitting` reads the answer as the object ESI sends (`{"fitting_id": n}`); it was read as a bare number and failed on a real answer. The return type is still the `i64` ID. + +### Added + +- `EsiBuilder::metadata_url`: the address of the SSO metadata document that points to the token validation keys (default: the EVE SSO one), so the validated `authenticate` flow can run against a local server. + +### Changed + +- **Breaking:** fields that the spec does not mark as required are now `Option`: `ContainerLogEntry::password_type`, and `amount` plus `character_id` / `corporation_id` of the faction warfare leaderboard items (`CharacterLeaderboardItem`, `CorporationLeaderboardItem`). A real answer that omitted them failed to parse as a whole. ## [0.2.2] - 2026-11-01 diff --git a/Cargo.toml b/Cargo.toml index 5bfe789..f878407 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esi-openapi" -version = "0.2.2" +version = "0.3.0" authors = ["Rafael ", "Celeo "] edition = "2021" description = "Rust API for EVE Online's ESI, based on the OpenAPI specification (fork of rfesi)" @@ -19,7 +19,7 @@ jsonwebtoken = { version = "11.1", optional = true, features = ["rust_crypto"] } futures-util = { version = "0.3", default-features = false, features = ["alloc"] } log = "0.4" rand = "0.10" -reqwest = { version = "0.13", default-features = false, features = ["json", "charset", "http2", "form", "query", "gzip", "brotli", "deflate"] } +reqwest = { version = "0.13", default-features = false, features = ["json", "charset", "http2", "form", "query", "gzip", "brotli", "deflate", "rustls"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha2 = "0.11" @@ -36,8 +36,6 @@ chrono = "0.4" uuid = { version = "1.29", features = ["v4", "fast-rng"] } [features] -default = ["random_state", "validate_jwt", "rustls-tls"] +default = ["random_state", "validate_jwt"] random_state = [] validate_jwt = ["dep:jsonwebtoken"] -# default-tls = ["reqwest/default-tls"] -rustls-tls = ["reqwest/rustls"] diff --git a/resources/test/keys/jwks.json b/resources/test/keys/jwks.json new file mode 100644 index 0000000..ccfb1e3 --- /dev/null +++ b/resources/test/keys/jwks.json @@ -0,0 +1,21 @@ +{ + "keys": [ + { + "kty": "EC", + "alg": "ES256", + "crv": "P-256", + "kid": "ignored", + "use": "sig", + "x": "AAAA", + "y": "AAAA" + }, + { + "kty": "RSA", + "alg": "RS256", + "kid": "JWT-Signature-Key", + "use": "sig", + "n": "1WRqVbsBuwvsoRnI3JClNtmoQq1woLXZY_AkFDD0BOQBggzFsxNXJdF-mAXAAKHFEDrwG6wgg6aPsIae3L-LUEEddv9hAlJAobnNrBITnb1DCN_eNKfE4cDin-Ad7-0O25HhWKBMs1cWZx4CL9t_oEGq9XtgxHk0JF0czBEIH9W5EVPjxPnyi8AoTNncYGWw9xJzhhjU3Qk0nx05UrCnpoNDqEmj5EDZlgDc3GWuhIr8Hzdw4tZKWXEsopVN8MDZS7TpqI0QXc28l5rfbm2C0LiGhEaBMmlWNTjQ88Rfxl9vvjMS9_lNlcIbZoQihT_QHdr2WhpoS0D7HcUBGJC2zqE56OQ3-eZ-pAEU_oHezawC3rZMX9vDbZSZYSgTxW_aNQwOchbcOaNPPbae9QOHPU-J6Uuz2ch9pkBPD-y5vhZ3-zV2w9z5Bfc4Q1sxxcNfYSjwq87TCBKIVoktXHW36caHGJd5M3KrwWhaJzx7RSlJVJdMREbF4QKsiGz3hSV7e-8AoDlXSWooivtHjZIfSh1xOyb_sHL0paesVd2eI72w4Khnq98BuQvv1hORdLipkk2VvAtyMmRYsDlXEZsq2IkXh_ucfWlq_7MjC25SCXymhY-1SNPOxMx_gvq3MkDz29BeaoyPNfwBEGtdRP5oI8iRwC1fj8FFeV4PuDjRKm0", + "e": "AQAB" + } + ] +} diff --git a/src/builders.rs b/src/builders.rs index 2559f11..c66343a 100644 --- a/src/builders.rs +++ b/src/builders.rs @@ -73,6 +73,7 @@ pub struct EsiBuilder { pub(crate) base_api_url: Option, pub(crate) authorize_url: Option, pub(crate) token_url: Option, + pub(crate) metadata_url: Option, pub(crate) spec_url: Option, pub(crate) scope: Option, pub(crate) access_token: Option, @@ -192,6 +193,13 @@ impl EsiBuilder { self } + /// Set the URL of the SSO metadata document, which points to the keys that + /// validate the access token (only used with the "validate_jwt" feature). + pub fn metadata_url(mut self, val: &str) -> Self { + self.metadata_url = Some(val.to_owned()); + self + } + /// Set the spec_url. pub fn spec_url(mut self, val: &str) -> Self { self.spec_url = Some(val.to_owned()); @@ -274,7 +282,6 @@ impl EsiBuilder { let builder = Client::builder() .timeout(http_timeout) .default_headers(headers); - #[cfg(feature = "rustls-tls")] let builder = builder.tls_backend_rustls(); Ok(builder.build()?) } @@ -405,6 +412,10 @@ mod tests { "https://login.eveonline.com/v2/oauth/authorize" ); assert_eq!(b.token_url, "https://login.eveonline.com/v2/oauth/token"); + assert_eq!( + b.metadata_url, + "https://login.eveonline.com/.well-known/oauth-authorization-server" + ); assert_eq!(b.spec_url, "https://esi.evetech.net/meta/openapi.json"); assert_eq!(b.compatibility_date, "2026-08-18"); assert_eq!(b.access_token, None); @@ -418,6 +429,7 @@ mod tests { .base_api_url("http://eve-api/") .authorize_url("http://authorize-url/") .token_url("http://token-url") + .metadata_url("http://metadata-url") .spec_url("http://spec-url/") .build() .unwrap(); @@ -425,6 +437,7 @@ mod tests { assert_eq!(b.base_api_url, "http://eve-api/"); assert_eq!(b.authorize_url, "http://authorize-url/"); assert_eq!(b.token_url, "http://token-url"); + assert_eq!(b.metadata_url, "http://metadata-url"); assert_eq!(b.spec_url, "http://spec-url/"); } @@ -450,7 +463,7 @@ mod tests { #[test] fn test_builder_to_json_empty() { - let json = r#"{"compatibility_date":null,"client_id":null,"client_secret":null,"application_auth":null,"callback_url":null,"base_api_url":null,"authorize_url":null,"token_url":null,"spec_url":null,"scope":null,"access_token":null,"access_expiration":null,"refresh_token":null,"user_agent":null,"http_timeout":null,"spec":null}"#; + let json = r#"{"compatibility_date":null,"client_id":null,"client_secret":null,"application_auth":null,"callback_url":null,"base_api_url":null,"authorize_url":null,"token_url":null,"metadata_url":null,"spec_url":null,"scope":null,"access_token":null,"access_expiration":null,"refresh_token":null,"user_agent":null,"http_timeout":null,"spec":null}"#; assert_eq!(json, serde_json::to_string(&EsiBuilder::new()).unwrap()); } diff --git a/src/client.rs b/src/client.rs index d7c2768..a96fae5 100644 --- a/src/client.rs +++ b/src/client.rs @@ -31,6 +31,7 @@ use tokio::sync::RwLock; const BASE_URL: &str = "https://esi.evetech.net/"; const AUTHORIZE_URL: &str = "https://login.eveonline.com/v2/oauth/authorize"; const TOKEN_URL: &str = "https://login.eveonline.com/v2/oauth/token"; +const METADATA_URL: &str = "https://login.eveonline.com/.well-known/oauth-authorization-server"; const SPEC_URL: &str = "https://esi.evetech.net/meta/openapi.json"; const ERROR_LIMIT_REMAIN_HEADER: &str = "x-esi-error-limit-remain"; const ERROR_LIMIT_RESET_HEADER: &str = "x-esi-error-limit-reset"; @@ -195,6 +196,7 @@ pub struct Esi { pub(crate) base_api_url: String, pub(crate) authorize_url: String, pub(crate) token_url: String, + pub(crate) metadata_url: String, pub(crate) spec_url: String, pub(crate) scope: String, pub(crate) application_auth: bool, @@ -247,6 +249,7 @@ impl Esi { base_api_url: builder.base_api_url.unwrap_or(BASE_URL.to_string()), authorize_url: builder.authorize_url.unwrap_or(AUTHORIZE_URL.to_string()), token_url: builder.token_url.unwrap_or(TOKEN_URL.to_string()), + metadata_url: builder.metadata_url.unwrap_or(METADATA_URL.to_string()), spec_url: builder.spec_url.unwrap_or(SPEC_URL.to_string()), scope: builder.scope.unwrap_or_else(|| "".to_owned()), application_auth: builder.application_auth.unwrap_or(false), @@ -560,6 +563,7 @@ impl Esi { let claim_data = Some( crate::jwt_util::validate_jwt( &self.client, + &self.metadata_url, &data.access_token, self.client_id.as_ref().unwrap(), ) @@ -984,7 +988,9 @@ impl Esi { .headers(headers) .query(query.unwrap_or(&[])); req_builder = match body { - Some(b) => req_builder.body(b.to_owned()), + Some(b) => req_builder + .header(header::CONTENT_TYPE, "application/json") + .body(b.to_owned()), None => req_builder, }; let req = req_builder.build()?; @@ -1125,8 +1131,12 @@ impl Esi { if self.access_token.is_none() { return Err(EsiError::MissingAuthentication); } - if self.access_expiration.unwrap() < current_time_millis()? { - return Err(EsiError::AccessTokenExpired); + // A token given without an expiration can't be judged here: send it and + // let ESI answer if it is no longer valid. + if let Some(expiration) = self.access_expiration { + if expiration < current_time_millis()? { + return Err(EsiError::AccessTokenExpired); + } } Ok(()) } @@ -1135,9 +1145,10 @@ impl Esi { /// and the compatibility date. fn request_headers(&self, request_type: &RequestType) -> EsiResult { let mut map = HeaderMap::new(); - // The 'user-agent' and 'content-type' headers are set in the default headers - // from the builder, so all that's required here is to set the authorization - // header, if present, and the compatibility date. + // The 'user-agent' and 'accept' headers are set in the default headers + // from the builder (and 'content-type', when there is a body, in + // `send_request`), so all that's required here is to set the + // authorization header, if present, and the compatibility date. if *request_type == RequestType::Authenticated { if let Some(at) = &self.access_token { map.insert( diff --git a/src/groups/corporation.rs b/src/groups/corporation.rs index b3c4ea2..664b97c 100644 --- a/src/groups/corporation.rs +++ b/src/groups/corporation.rs @@ -131,8 +131,8 @@ pub struct ContainerLogEntry { pub new_config_bitmask: Option, /// Configuration bitmask before the change. pub old_config_bitmask: Option, - /// Kind of password involved. - pub password_type: ContainerPasswordType, + /// Kind of password involved (only for the password actions). + pub password_type: Option, /// Quantity moved. pub quantity: Option, /// Type ID of the item moved. @@ -863,6 +863,7 @@ mod corporation_management_tests { ) .unwrap(); assert_eq!(l[0].action, ContainerAction::EnterPassword); + assert_eq!(l[0].password_type, Some(ContainerPasswordType::Config)); let t: Vec = serde_json::from_str(r#"[{"title_id": 1, "name": "CEO", "roles": ["Director"]}]"#) .unwrap(); diff --git a/src/groups/faction_warfare.rs b/src/groups/faction_warfare.rs index bafdd7b..250090e 100644 --- a/src/groups/faction_warfare.rs +++ b/src/groups/faction_warfare.rs @@ -30,8 +30,8 @@ pub struct FWLeaderboards { #[derive(Debug, Deserialize)] #[allow(missing_docs)] pub struct CharacterLeaderboardItem { - pub amount: i64, - pub character_id: i64, + pub amount: Option, + pub character_id: Option, } #[derive(Debug, Deserialize)] @@ -52,8 +52,8 @@ pub struct FWCharacterLeaderboards { #[derive(Debug, Deserialize)] #[allow(missing_docs)] pub struct CorporationLeaderboardItem { - pub amount: i64, - pub corporation_id: i64, + pub amount: Option, + pub corporation_id: Option, } #[derive(Debug, Deserialize)] diff --git a/src/groups/fittings.rs b/src/groups/fittings.rs index df0fa40..0971438 100644 --- a/src/groups/fittings.rs +++ b/src/groups/fittings.rs @@ -99,6 +99,12 @@ pub struct NewFitting { pub ship_type_id: i64, } +/// The answer to saving a fitting. +#[derive(Debug, Deserialize)] +struct CreatedFitting { + fitting_id: i64, +} + impl FittingsGroup<'_> { api_get!( /// Return the fittings saved by a character. @@ -109,15 +115,23 @@ impl FittingsGroup<'_> { (character_id: i64) => "{character_id}" ); - api_post!( - /// Save a new fitting. Returns the ID of the created fitting. - create_character_fitting, - "PostCharactersCharacterIdFittings", - RequestType::Authenticated, - i64, - (character_id: i64) => "{character_id}", + /// Save a new fitting. Returns the ID of the created fitting. + pub async fn create_character_fitting( + &self, + character_id: i64, fitting: &NewFitting, - ); + ) -> EsiResult { + let path = self + .esi + .get_endpoint_for_op_id("PostCharactersCharacterIdFittings")? + .replace("{character_id}", &character_id.to_string()); + let body = serde_json::to_string(fitting)?; + let created: CreatedFitting = self + .esi + .query("POST", RequestType::Authenticated, &path, None, Some(&body)) + .await?; + Ok(created.fitting_id) + } api_delete!( /// Delete a saved fitting. @@ -145,6 +159,13 @@ mod fittings_tests { assert_eq!(fits[0].items[1].flag, FittingFlag::Unrecognized); } + #[test] + fn test_parse_created_fitting() { + let created: CreatedFitting = + serde_json::from_str(r#"{"fitting_id": 3000000000}"#).unwrap(); + assert_eq!(created.fitting_id, 3_000_000_000); + } + #[test] fn test_serialize_new_fitting() { let f = NewFitting { diff --git a/src/groups/universe.rs b/src/groups/universe.rs index e04b4d5..261aac1 100644 --- a/src/groups/universe.rs +++ b/src/groups/universe.rs @@ -317,7 +317,8 @@ pub struct Bloodline { pub name: String, pub perception: i64, pub race_id: i64, - pub ship_type_id: i64, + // The spec requires it, but ESI sends `null` for some bloodlines. + pub ship_type_id: Option, pub willpower: i64, } @@ -690,7 +691,7 @@ impl UniverseGroup<'_> { #[cfg(test)] mod new_endpoint_tests { - use super::{NameCategory, ResolvedName, Star, StructureFilter}; + use super::{Bloodline, NameCategory, ResolvedName, Star, StructureFilter}; #[test] fn test_parse_star_with_large_values() { @@ -702,6 +703,22 @@ mod new_endpoint_tests { assert_eq!(star.spectral_class, "K2 V"); } + #[test] + fn test_parse_bloodlines_with_a_null_ship_type() { + // ESI sends `null` for the ship of some bloodlines, although the spec + // requires it. + let json = r#"[ + {"bloodline_id": 5, "charisma": 3, "corporation_id": 1000066, "description": "d", + "intelligence": 7, "memory": 5, "name": "Amarr", "perception": 6, "race_id": 4, + "ship_type_id": 596, "willpower": 10}, + {"bloodline_id": 9, "charisma": 3, "corporation_id": 1000066, "description": "d", + "intelligence": 7, "memory": 5, "name": "Other", "perception": 6, "race_id": 4, + "ship_type_id": null, "willpower": 10}]"#; + let bloodlines: Vec = serde_json::from_str(json).unwrap(); + assert_eq!(bloodlines[0].ship_type_id, Some(596)); + assert_eq!(bloodlines[1].ship_type_id, None); + } + #[test] fn test_parse_resolved_names() { let json = r#"[{"category": "inventory_type", "id": 34, "name": "Tritanium"}, diff --git a/src/jwt_util.rs b/src/jwt_util.rs index ec4c866..c2ae243 100644 --- a/src/jwt_util.rs +++ b/src/jwt_util.rs @@ -6,12 +6,9 @@ use serde_json::Value; use crate::prelude::*; -const TOKEN_AUTH_INFO_URL: &str = - "https://login.eveonline.com/.well-known/oauth-authorization-server"; - /// Get the URL that hosts the valid JWT signing keys. -async fn get_keys_url(client: &Client) -> EsiResult { - let resp = client.get(TOKEN_AUTH_INFO_URL).send().await?; +async fn get_keys_url(client: &Client, metadata_url: &str) -> EsiResult { + let resp = client.get(metadata_url).send().await?; if resp.status() != 200 { error!( "Got status {} when making call to get token info", @@ -26,20 +23,35 @@ async fn get_keys_url(client: &Client) -> EsiResult { Ok(url.to_owned()) } +/// The set of signing keys published by the SSO. +struct Jwks; + +impl Jwks { + /// The first RS256 key of a JWKS document, as a JSON string. + fn rs256_key(data: &Value) -> EsiResult { + let keys = data["keys"] + .as_array() + .ok_or_else(|| EsiError::InvalidJWT(String::from("The key set has no keys")))?; + keys.iter() + .find(|entry| entry["alg"].as_str() == Some("RS256")) + .map(|entry| entry.to_string()) + .ok_or_else(|| EsiError::InvalidJWT(String::from("Could not find an RS256 key"))) + } +} + /// Get the RS256 key to use. -async fn get_rs256_key(client: &Client) -> EsiResult { - let keys_url = get_keys_url(client).await?; +async fn get_rs256_key(client: &Client, metadata_url: &str) -> EsiResult { + let keys_url = get_keys_url(client, metadata_url).await?; let resp = client.get(&keys_url).send().await?; + if resp.status() != 200 { + error!( + "Got status {} when making call to get the token keys", + resp.status() + ); + return Err(EsiError::InvalidStatusCode(resp.status().as_u16())); + } let data: Value = resp.json().await?; - let key = data["keys"] - .as_array() - .unwrap() - .iter() - .filter(|entry| entry["alg"].as_str().unwrap() == "RS256") - .map(|entry| serde_json::to_string(entry).unwrap()) - .next() - .ok_or_else(|| EsiError::InvalidJWT(String::from("Could not find an RS256 key")))?; - Ok(key) + Jwks::rs256_key(&data) } /// Decode and validate the JWT token @@ -55,9 +67,20 @@ fn validate( let token: TokenData = decode(token, decoding_key, &validations)?; /* Additional verifications from https://docs.esi.evetech.net/docs/sso/validating_eve_jwt.html */ - if token.claims["iss"].as_str().unwrap() != "login.eveonline.com" - && token.claims["iss"].as_str().unwrap() != "https://login.eveonline.com" - { + // `set_audience` accepts a token that lists any of the audiences, and every + // token lists "EVE Online": the client ID itself has to be there too. + let for_this_client = match &token.claims["aud"] { + Value::Array(audiences) => audiences.iter().any(|aud| aud.as_str() == Some(client_id)), + Value::String(audience) => audience == client_id, + _ => false, + }; + if !for_this_client { + return Err(EsiError::InvalidJWT(String::from( + "JWT was not issued for this client", + ))); + } + let issuer = token.claims["iss"].as_str().unwrap_or_default(); + if issuer != "login.eveonline.com" && issuer != "https://login.eveonline.com" { return Err(EsiError::InvalidJWT(String::from( "JWT issuer is incorrect", ))); @@ -70,10 +93,11 @@ fn validate( /// Decode and validate the SSO JWT, returning the contents. pub(crate) async fn validate_jwt( client: &Client, + metadata_url: &str, token: &str, client_id: &str, ) -> EsiResult { - let validation_key_str = get_rs256_key(client).await?; + let validation_key_str = get_rs256_key(client, metadata_url).await?; let validation_key: Jwk = serde_json::from_str(&validation_key_str)?; let decoding_key = DecodingKey::from_jwk(&validation_key)?; @@ -88,8 +112,69 @@ mod tests { use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header}; use serde_json::Value; - use crate::jwt_util::validate; - use crate::prelude::TokenClaims; + use crate::jwt_util::{validate, Jwks}; + use crate::prelude::{EsiError, TokenClaims}; + + #[test] + fn the_key_set_yields_its_first_rs256_key() { + let data = serde_json::json!({"keys": [ + {"alg": "ES256", "kid": "ec"}, + {"alg": "RS256", "kid": "first"}, + {"alg": "RS256", "kid": "second"} + ]}); + + let key: Value = serde_json::from_str(&Jwks::rs256_key(&data).unwrap()).unwrap(); + assert_eq!(key["kid"], "first"); + } + + #[test] + fn a_malformed_key_set_is_an_error_not_a_panic() { + for data in [ + serde_json::json!({}), + serde_json::json!({"keys": "nope"}), + serde_json::json!({"keys": []}), + serde_json::json!({"keys": [{"kid": "no-alg"}]}), + serde_json::json!({"keys": [{"alg": "ES256"}]}), + ] { + assert!( + matches!(Jwks::rs256_key(&data), Err(EsiError::InvalidJWT(_))), + "{data}" + ); + } + } + + #[test] + fn a_token_without_an_issuer_is_rejected_not_a_panic() { + let header = Header::new(Algorithm::RS256); + let (private_key, public_key) = load_key(); + let (claim, client_id) = generate_valid_claims(); + let mut value = serde_json::to_value(&claim).unwrap(); + value.as_object_mut().unwrap().remove("iss"); + let encoding_key = EncodingKey::from_rsa_pem(private_key.as_bytes()).unwrap(); + let token = jsonwebtoken::encode(&header, &value, &encoding_key).unwrap(); + let decoding_key = DecodingKey::from_rsa_pem(public_key.as_bytes()).unwrap(); + + assert!(matches!( + validate(&token, &client_id, &decoding_key), + Err(EsiError::InvalidJWT(_)) + )); + } + + #[test] + fn a_token_issued_for_another_client_is_rejected() { + let header = Header::new(Algorithm::RS256); + let (mut claim, client_id) = generate_valid_claims(); + claim.aud = vec!["another_client".to_string(), "EVE Online".to_string()]; + let (private_key, public_key) = load_key(); + let encoding_key = EncodingKey::from_rsa_pem(private_key.as_bytes()).unwrap(); + let token = jsonwebtoken::encode(&header, &claim, &encoding_key).unwrap(); + let decoding_key = DecodingKey::from_rsa_pem(public_key.as_bytes()).unwrap(); + + assert!(matches!( + validate(&token, &client_id, &decoding_key), + Err(EsiError::InvalidJWT(_)) + )); + } #[test] fn test_jwt_validity() { diff --git a/src/pkce.rs b/src/pkce.rs index 70d6c2e..621fc3a 100644 --- a/src/pkce.rs +++ b/src/pkce.rs @@ -13,20 +13,22 @@ pub struct Pkce { pub verifier: PkceVerifier, } +impl Pkce { + /// The `S256` challenge of a verifier (RFC 7636, section 4.2): + /// `BASE64URL(SHA256(ASCII(verifier)))`. + fn challenge_of(verifier: &str) -> PkceChallenge { + let hash = Sha256::digest(verifier.as_bytes()); + base64url(&hash.to_vec()) + } +} + pub fn generate() -> EsiResult { let verifier: Vec = (0..32).map(|_| random()).collect(); let verifier_base64 = base64url(&verifier); - - // Create SHA256 hash of verifier - let mut hasher = Sha256::new(); - hasher.update(&verifier_base64); - let challenge = hasher.finalize(); - - // Encode challenge as base64 URL-safe string - let challenge_base64 = base64url(&challenge.to_vec()); + let challenge = Pkce::challenge_of(&verifier_base64); Ok(Pkce { - challenge: challenge_base64, + challenge, verifier: verifier_base64, }) } @@ -37,3 +39,72 @@ pub fn base64url(verifier: &Vec) -> String { verifier_out.truncate(written_size); String::from_utf8(verifier_out).unwrap() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_challenge_of_the_rfc_7636_example_verifier_matches_the_rfc() { + // RFC 7636, appendix B. + assert_eq!( + Pkce::challenge_of("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + } + + #[test] + fn a_generated_pair_is_a_verifier_and_its_challenge() { + let pkce = generate().unwrap(); + + assert_eq!(pkce.challenge, Pkce::challenge_of(&pkce.verifier)); + assert_ne!(pkce.challenge, pkce.verifier); + } + + #[test] + fn the_verifier_has_the_length_and_alphabet_of_rfc_7636() { + // 32 random bytes encode to 43 characters without padding; the RFC + // asks for 43 to 128 characters of [A-Za-z0-9-._~]. + for _ in 0..50 { + let pkce = generate().unwrap(); + assert_eq!(pkce.verifier.len(), 43); + assert_eq!(pkce.challenge.len(), 43); + for text in [&pkce.verifier, &pkce.challenge] { + assert!( + text.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'), + "{text}" + ); + } + } + } + + #[test] + fn every_pair_is_different() { + let first = generate().unwrap(); + let second = generate().unwrap(); + + assert_ne!(first.verifier, second.verifier); + assert_ne!(first.challenge, second.challenge); + } + + #[test] + fn base64url_uses_the_url_alphabet_without_padding() { + // 0xfb 0xff encodes to "+/8=" in the standard alphabet. + assert_eq!(base64url(&vec![0xfb, 0xff]), "-_8"); + assert_eq!(base64url(&Vec::new()), ""); + assert_eq!(base64url(&b"f".to_vec()), "Zg"); + assert_eq!(base64url(&b"fo".to_vec()), "Zm8"); + assert_eq!(base64url(&b"foo".to_vec()), "Zm9v"); + } + + #[test] + fn base64url_round_trips_every_length_up_to_100() { + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + for length in 0..=100u8 { + let bytes: Vec = (0..length).map(|i| i.wrapping_mul(37)).collect(); + let text = base64url(&bytes); + assert_eq!(URL_SAFE_NO_PAD.decode(&text).unwrap(), bytes, "{length}"); + } + } +} diff --git a/tests/errors.rs b/tests/errors.rs new file mode 100644 index 0000000..1ea0761 --- /dev/null +++ b/tests/errors.rs @@ -0,0 +1,319 @@ +//! What the client does when things go wrong: error statuses, the rate and +//! error limits that ESI announces in its headers, bodies that cannot be read, +//! and a server that is down or does not answer. +//! +//! Every test runs against a local server (`tests/support`), so it checks the +//! whole path from the HTTP answer to the `EsiError` the caller gets, and +//! whether a request reached the server at all. + +mod support; + +use esi_openapi::prelude::*; +use esi_openapi::spec::Spec; +use support::{Reply, Server}; + +struct Harness; + +impl Harness { + fn spec() -> Spec { + serde_json::from_str(include_str!("../resources/test/openapi.json")).unwrap() + } + + fn builder(server: &Server) -> EsiBuilder { + EsiBuilder::new() + .user_agent("error tests") + .base_api_url(&server.url) + .spec(Some(Self::spec())) + } + + fn public(server: &Server) -> Esi { + Self::builder(server).build().unwrap() + } + + /// A client that is signed in for another hour. + fn signed_in(server: &Server) -> Esi { + let expiration = chrono::Utc::now().timestamp_millis() + 3_600_000; + Self::builder(server) + .access_token(Some("the-token")) + .access_expiration(Some(expiration)) + .build() + .unwrap() + } + + /// Any public call; the answer is not what the tests look at. + async fn call(esi: &Esi) -> EsiResult> { + esi.group_market().get_region_history(10000002, 34).await + } + + /// An answer that carries the error limit headers. + fn with_error_limit(reply: Reply, remain: &str, reset: &str) -> Reply { + reply + .with_header("X-ESI-Error-Limit-Remain", remain) + .with_header("X-ESI-Error-Limit-Reset", reset) + } +} + +use esi_openapi::groups::HistoryItem; + +#[tokio::test] +async fn every_error_status_is_reported_with_its_code_and_not_retried() { + for status in [400, 401, 403, 404, 500, 502, 503, 504] { + let server = Server::start(Reply::status(status)).await; + let result = Harness::call(&Harness::public(&server)).await; + + assert!( + matches!(result, Err(EsiError::InvalidStatusCode(code)) if code == status), + "{status}: {result:?}" + ); + assert_eq!(server.requests().len(), 1, "{status} must not be retried"); + } +} + +#[tokio::test] +async fn a_rejected_token_is_reported_and_kept() { + let server = Server::start(Reply::status(401)).await; + let esi = Harness::signed_in(&server); + let result = esi + .group_contacts() + .get_character_contacts(90000001, None) + .await; + + assert!(matches!(result, Err(EsiError::InvalidStatusCode(401)))); + assert_eq!(esi.access_token.as_deref(), Some("the-token")); +} + +#[tokio::test] +async fn a_429_without_headers_has_no_group_and_no_retry_after() { + let server = Server::start(Reply::status(429)).await; + let result = Harness::call(&Harness::public(&server)).await; + + assert!(matches!( + result, + Err(EsiError::RateLimited { + group: None, + retry_after_secs: None + }) + )); +} + +#[tokio::test] +async fn a_429_carries_the_group_and_the_retry_after_of_its_headers() { + let reply = Reply::status(429) + .with_header("X-Ratelimit-Group", "market") + .with_header("Retry-After", "7"); + let server = Server::start(reply).await; + let result = Harness::call(&Harness::public(&server)).await; + + match result { + Err(EsiError::RateLimited { + group, + retry_after_secs, + }) => { + assert_eq!(group.as_deref(), Some("market")); + assert_eq!(retry_after_secs, Some(7)); + } + other => panic!("{other:?}"), + } +} + +#[tokio::test] +async fn an_exhausted_error_limit_refuses_the_next_request_without_sending_it() { + let reply = Harness::with_error_limit(Reply::status(500), "0", "60"); + let server = Server::start(reply).await; + let esi = Harness::public(&server); + + let first = Harness::call(&esi).await; + assert!(matches!(first, Err(EsiError::InvalidStatusCode(500)))); + match esi.is_error_limited().await.unwrap() { + ErrorLimitStatus::Limited { for_millis } => { + assert!((55_000..=60_000).contains(&for_millis), "{for_millis}") + } + ErrorLimitStatus::NotLimited => panic!("the limit is exhausted"), + } + let second = Harness::call(&esi).await; + assert!( + matches!(second, Err(EsiError::ErrorLimited(ms)) if (55_000..=60_000).contains(&ms)), + "{second:?}" + ); + assert_eq!( + server.requests().len(), + 1, + "the second call must not be sent" + ); +} + +#[tokio::test] +async fn an_error_limit_with_errors_left_does_not_block() { + let reply = Harness::with_error_limit(Reply::status(500), "99", "60"); + let server = Server::start(reply).await; + let esi = Harness::public(&server); + + let _ = Harness::call(&esi).await; + let second = Harness::call(&esi).await; + + assert!(matches!(second, Err(EsiError::InvalidStatusCode(500)))); + assert_eq!(server.requests().len(), 2); + assert!(matches!( + esi.is_error_limited().await.unwrap(), + ErrorLimitStatus::NotLimited + )); +} + +#[tokio::test] +async fn the_error_limit_headers_of_a_successful_answer_count_too() { + let reply = Harness::with_error_limit(Reply::json("[]"), "0", "60"); + let server = Server::start(reply).await; + let esi = Harness::public(&server); + + Harness::call(&esi).await.unwrap(); + let second = Harness::call(&esi).await; + + assert!(matches!(second, Err(EsiError::ErrorLimited(_)))); + assert_eq!(server.requests().len(), 1); +} + +#[tokio::test] +async fn an_error_limit_met_at_the_sso_also_blocks_the_api_calls() { + let sso = Server::start(Harness::with_error_limit(Reply::status(400), "0", "60")).await; + let api = Server::start(Reply::json("[]")).await; + let mut esi = Harness::builder(&api) + .client_id("the-client") + .client_secret("the-secret") + .callback_url("http://localhost/callback") + .token_url(&format!("{}v2/oauth/token", sso.url)) + .refresh_token(Some("old-refresh")) + .build() + .unwrap(); + + let refresh = esi.refresh_access_token(None).await; + assert!(matches!(refresh, Err(EsiError::InvalidStatusCode(400)))); + let call = Harness::call(&esi).await; + + assert!(matches!(call, Err(EsiError::ErrorLimited(_)))); + assert!(api.requests().is_empty(), "the API must not be called"); +} + +#[tokio::test] +async fn unreadable_error_limit_headers_are_an_error() { + let reply = Harness::with_error_limit(Reply::json("[]"), "many", "10"); + let server = Server::start(reply).await; + let result = Harness::call(&Harness::public(&server)).await; + + assert!( + matches!(result, Err(EsiError::HeaderParseError(_, _))), + "{result:?}" + ); +} + +#[tokio::test] +async fn a_body_that_is_not_json_is_a_parse_error() { + let server = Server::start(Reply::json("{not json")).await; + let result = Harness::call(&Harness::public(&server)).await; + + assert!( + matches!(result, Err(EsiError::FailedJsonParse(_))), + "{result:?}" + ); +} + +#[tokio::test] +async fn a_body_of_the_wrong_shape_is_a_parse_error() { + let server = Server::start(Reply::json(r#"{"unexpected": true}"#)).await; + let result = Harness::call(&Harness::public(&server)).await; + + assert!( + matches!(result, Err(EsiError::FailedJsonParse(_))), + "{result:?}" + ); +} + +#[tokio::test] +async fn a_server_that_is_down_is_a_connection_error() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::public(&server); + // Nothing listens on a port that was just released. + let free = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = free.local_addr().unwrap(); + drop(free); + let esi_down = Harness::builder(&server) + .base_api_url(&format!("http://{address}/")) + .build() + .unwrap(); + + assert!(matches!( + Harness::call(&esi_down).await, + Err(EsiError::ReqwestError(_)) + )); + Harness::call(&esi).await.unwrap(); +} + +#[tokio::test] +async fn a_server_that_does_not_answer_times_out() { + let server = Server::start(Reply::never()).await; + let esi = Harness::builder(&server) + .http_timeout(Some(300)) + .build() + .unwrap(); + let started = std::time::Instant::now(); + let result = Harness::call(&esi).await; + + match result { + Err(EsiError::ReqwestError(error)) => assert!(error.is_timeout(), "{error}"), + other => panic!("{other:?}"), + } + assert!(started.elapsed() < std::time::Duration::from_secs(5)); +} + +#[tokio::test] +async fn an_error_answer_is_not_cached() { + let server = Server::sequence(vec![ + Reply::status(500), + Reply::json(r#"[]"#).with_header("Cache-Control", "max-age=60"), + ]) + .await; + let esi = Harness::builder(&server) + .enable_cache(true) + .build() + .unwrap(); + + assert!(matches!( + Harness::call(&esi).await, + Err(EsiError::InvalidStatusCode(500)) + )); + Harness::call(&esi).await.unwrap(); + assert_eq!(server.requests().len(), 2); + assert_eq!(esi.cache_len().await, 1); +} + +#[tokio::test] +async fn an_operation_missing_from_the_spec_never_reaches_the_server() { + let server = Server::start(Reply::json("[]")).await; + let empty: Spec = serde_json::from_str(r#"{"paths": {}}"#).unwrap(); + let esi = Harness::builder(&server).spec(Some(empty)).build().unwrap(); + let result = Harness::call(&esi).await; + + assert!( + matches!(result, Err(EsiError::UnknownOperationID(ref id)) if id == "GetMarketsRegionIdHistory"), + "{result:?}" + ); + assert!(server.requests().is_empty()); +} + +#[tokio::test] +async fn a_failing_spec_download_is_an_error_and_the_client_still_has_no_spec() { + let server = Server::start(Reply::status(500)).await; + let mut esi = EsiBuilder::new() + .user_agent("error tests") + .base_api_url(&server.url) + .spec_url(&format!("{}meta/openapi.json", server.url)) + .build() + .unwrap(); + let result = esi.update_spec().await; + + assert!( + matches!(result, Err(EsiError::InvalidStatusCode(500))), + "{result:?}" + ); + let call = Harness::call(&esi).await; + assert!(matches!(call, Err(EsiError::EmptySpec)), "{call:?}"); +} diff --git a/tests/live.rs b/tests/live.rs new file mode 100644 index 0000000..b411a06 --- /dev/null +++ b/tests/live.rs @@ -0,0 +1,429 @@ +//! Smoke test against the live ESI API, for the public endpoints. +//! +//! It calls one endpoint of every public group with real data and reads the +//! answer into the type the crate returns, so a change in what ESI sends that +//! the OpenAPI spec does not show (a field that becomes `null`, a new type of +//! value) is found here. Ids are taken from earlier answers where they can be +//! (the first alliance, the CEO of a corporation, ...) and fixed only for the +//! stable ones (The Forge, Jita, Tritanium). +//! +//! It is ignored by default because it needs the network. To run it: +//! +//! ```sh +//! cargo test --test live -- --ignored --nocapture +//! ``` +//! +//! The weekly `live-esi` workflow runs it too. A step that fails does not stop +//! the others; the test reports every failure at the end. + +use esi_openapi::groups::RouteRequest; +use esi_openapi::prelude::*; +use std::fmt::Debug; + +/// What each step found. +#[derive(Default)] +struct Report { + rows: Vec<(String, Result)>, +} + +impl Report { + /// Records the outcome of a step and gives back its value. + fn note(&mut self, name: &str, result: EsiResult) -> Option { + match result { + Ok(value) => { + let text = format!("{value:?}"); + let short: String = text.chars().take(70).collect(); + self.rows.push((name.to_owned(), Ok(short))); + Some(value) + } + Err(error) => { + self.rows + .push((name.to_owned(), Err(format!("{error} ({error:?})")))); + None + } + } + } + + fn failures(&self) -> Vec { + self.rows + .iter() + .filter_map(|(name, result)| result.as_ref().err().map(|e| format!("{name}: {e}"))) + .collect() + } + + fn print(&self) { + for (name, result) in &self.rows { + match result { + Ok(short) => println!("ok {name}: {short}"), + Err(error) => println!("FAIL {name}: {error}"), + } + } + } +} + +struct Smoke { + esi: Esi, + report: Report, +} + +impl Smoke { + /// A client with the live OpenAPI spec downloaded. + async fn new() -> Self { + let mut esi = EsiBuilder::new() + .user_agent("esi-openapi live smoke test (https://github.com/rafaga/esi-openapi)") + .http_timeout(Some(30_000)) + .build() + .unwrap(); + let mut report = Report::default(); + let spec = report.note("spec download", esi.update_spec().await); + assert!(spec.is_some(), "{:?}", report.failures()); + Self { esi, report } + } + + async fn meta_and_status(&mut self) { + let r = &mut self.report; + r.note("status", self.esi.group_status().get_status().await); + r.note("meta status", self.esi.group_meta().get_status().await); + r.note("meta name", self.esi.group_meta().get_name().await); + r.note( + "meta compatibility dates", + self.esi.group_meta().get_compatibility_dates().await, + ); + r.note( + "meta changelog", + self.esi.group_meta().get_changelog().await, + ); + } + + /// Alliance, corporation and character, each found from the one before. + async fn people(&mut self) { + let r = &mut self.report; + let alliances = r.note("alliance ids", self.esi.group_alliance().list_ids().await); + let Some(alliance_id) = alliances.and_then(|ids| ids.first().copied()) else { + return; + }; + r.note( + "alliance info", + self.esi.group_alliance().get_info(alliance_id).await, + ); + r.note( + "alliance icons", + self.esi + .group_alliance() + .get_alliance_icons(alliance_id) + .await, + ); + let members = r.note( + "alliance corporations", + self.esi + .group_alliance() + .get_alliance_corporations(alliance_id) + .await, + ); + if let Some(corporation_id) = members.and_then(|ids| ids.first().copied()) { + let corporation = r.note( + "corporation info", + self.esi + .group_corporation() + .get_public_info(corporation_id) + .await, + ); + r.note( + "corporation history", + self.esi + .group_corporation() + .get_history(corporation_id) + .await, + ); + r.note( + "corporation icons", + self.esi.group_corporation().get_icons(corporation_id).await, + ); + r.note( + "loyalty store offers", + self.esi + .group_loyalty() + .get_store_offers(corporation_id) + .await, + ); + if let Some(ceo_id) = corporation.and_then(|c| c.ceo_id) { + r.note( + "character info", + self.esi.group_character().get_public_info(ceo_id).await, + ); + r.note( + "character history", + self.esi.group_character().get_history(ceo_id).await, + ); + r.note( + "character portrait", + self.esi.group_character().get_portrait(ceo_id).await, + ); + r.note( + "character affiliation", + self.esi.group_character().get_affiliation(&[ceo_id]).await, + ); + } + } + let npc = r.note( + "npc corporations", + self.esi.group_corporation().get_npc_corps().await, + ); + if let Some(id) = npc.and_then(|ids| ids.first().copied()) { + r.note( + "npc corporation info", + self.esi.group_corporation().get_public_info(id).await, + ); + } + } + + async fn market(&mut self) { + let r = &mut self.report; + let forge = 10000002; + let tritanium = 34; + r.note( + "market history", + self.esi + .group_market() + .get_region_history(forge, tritanium) + .await, + ); + r.note( + "market orders", + self.esi + .group_market() + .get_region_orders(forge, Some("all".to_owned()), None, Some(tritanium)) + .await, + ); + r.note( + "market prices", + self.esi.group_market().get_market_prices().await, + ); + r.note( + "market region types", + self.esi.group_market().get_region_types(forge, None).await, + ); + let groups = r.note("market groups", self.esi.group_market().get_groups().await); + if let Some(id) = groups.and_then(|ids| ids.first().copied()) { + r.note("market group", self.esi.group_market().get_group(id).await); + } + r.note( + "public contracts", + self.esi + .group_contracts() + .get_public_contracts(forge, None) + .await, + ); + r.note( + "insurance prices", + self.esi.group_insurance().get_prices().await, + ); + } + + async fn universe(&mut self) { + let r = &mut self.report; + let universe = self.esi.group_universe(); + let jita = r.note("jita system", universe.get_system(30000142).await); + if let Some(jita) = jita { + if let Some(star) = jita.star_id { + r.note("star", universe.get_star(star).await); + } + if let Some(gate) = jita.stargates.as_ref().and_then(|g| g.first()) { + r.note("stargate", universe.get_stargate(*gate).await); + } + } + r.note("station", universe.get_station(60003760).await); + r.note("region", universe.get_region(10000002).await); + r.note("constellation", universe.get_constellation(20000020).await); + r.note("type (Tritanium)", universe.get_type(34).await); + r.note( + "group (Mineral)", + universe.get_universe_groups_group(18).await, + ); + r.note( + "category (Material)", + universe.get_universe_categories_category(4).await, + ); + r.note("system ids", universe.get_system_ids().await); + r.note("region ids", universe.get_region_ids().await); + r.note("constellation ids", universe.get_constellation_ids().await); + r.note("category ids", universe.get_category_ids().await); + let graphics = r.note("graphic ids", universe.get_graphic_ids().await); + if let Some(id) = graphics.and_then(|ids| ids.first().copied()) { + r.note("graphic", universe.get_graphic(id).await); + } + r.note("system jumps", universe.get_system_jumps().await); + r.note("system kills", universe.get_system_kills().await); + r.note( + "system kills snapshot", + universe.get_system_kills_snapshot().await, + ); + r.note("ancestries", universe.get_ancestries().await); + r.note("bloodlines", universe.get_bloodlines().await); + r.note("races", universe.get_races().await); + r.note("factions", universe.get_factions().await); + r.note("names", universe.get_names(&[30000142, 10000002, 34]).await); + r.note("ids", universe.get_ids(&["Jita", "The Forge"]).await); + let route = RouteRequest::default(); + r.note( + "route", + self.esi + .group_routes() + .calculate_route(30000142, 30002187, &route) + .await, + ); + } + + async fn dogma(&mut self) { + let r = &mut self.report; + let attributes = r.note( + "dogma attributes", + self.esi.group_dogma().get_attributes().await, + ); + if let Some(id) = attributes.and_then(|ids| ids.first().copied()) { + r.note( + "dogma attribute", + self.esi.group_dogma().get_attribute(id).await, + ); + } + let effects = r.note("dogma effects", self.esi.group_dogma().get_effects().await); + if let Some(id) = effects.and_then(|ids| ids.first().copied()) { + r.note("dogma effect", self.esi.group_dogma().get_effect(id).await); + } + r.note( + "planetary schematic", + self.esi + .group_planetary_interaction() + .get_schematic(65) + .await, + ); + } + + async fn conflict(&mut self) { + let r = &mut self.report; + let fw = self.esi.group_faction_warfare(); + r.note("fw leaderboards", fw.leaderboards().await); + r.note( + "fw character leaderboards", + fw.leaderboard_characters().await, + ); + r.note( + "fw corporation leaderboards", + fw.leaderboard_corporations().await, + ); + r.note("fw stats", fw.stats().await); + r.note("fw systems", fw.systems().await); + r.note("fw wars", fw.wars().await); + r.note("incursions", self.esi.group_incursions().list().await); + r.note( + "sovereignty campaigns", + self.esi.group_sovereignty().get_campaigns().await, + ); + r.note( + "sovereignty systems", + self.esi.group_sovereignty().get_systems().await, + ); + r.note( + "industry systems", + self.esi.group_industry().get_industry_systems().await, + ); + r.note( + "industry facilities", + self.esi.group_industry().get_facilities().await, + ); + let wars = r.note("wars", self.esi.group_wars().list(None).await); + if let Some(id) = wars.and_then(|ids| ids.first().copied()) { + r.note("war", self.esi.group_wars().get_war(id).await); + let killmails = r.note( + "war killmails", + self.esi.group_wars().get_war_killmails(id, None).await, + ); + if let Some(killmail) = killmails.and_then(|k| k.into_iter().next()) { + r.note( + "killmail", + self.esi + .group_killmails() + .get_killmail(killmail.killmail_id, &killmail.killmail_hash) + .await, + ); + } + } + } + + /// The groups whose answers are pages with a cursor. + async fn paged(&mut self) { + let r = &mut self.report; + let campaigns = r.note( + "military campaigns", + self.esi.group_military_campaigns().list().await, + ); + if let Some(campaign) = campaigns.and_then(|c| c.into_iter().next()) { + r.note( + "military campaign", + self.esi + .group_military_campaigns() + .get_campaign(campaign.id) + .await, + ); + let objectives = r.note( + "campaign objectives", + self.esi + .group_military_campaigns() + .list_objectives(campaign.id, None, None, Some(10)) + .await, + ); + if let Some(objective) = objectives.and_then(|p| p.items.into_iter().next()) { + r.note( + "campaign objective", + self.esi + .group_military_campaigns() + .get_objective(campaign.id, objective.id) + .await, + ); + } + } + let jobs = r.note( + "freelance jobs", + self.esi + .group_freelance_jobs() + .list(None, None, Some(10), None) + .await, + ); + if let Some(job) = jobs.and_then(|p| p.items.into_iter().next()) { + r.note( + "freelance job", + self.esi.group_freelance_jobs().get_job(job.id).await, + ); + } + r.note( + "paragon hub listings", + self.esi + .group_paragon_hub() + .get_skinr_listings(None, None, Some(10)) + .await, + ); + } +} + +#[tokio::test] +#[ignore = "needs the live ESI; run it explicitly"] +async fn the_public_endpoints_read_what_esi_sends() { + let mut smoke = Smoke::new().await; + smoke.meta_and_status().await; + smoke.people().await; + smoke.market().await; + smoke.universe().await; + smoke.dogma().await; + smoke.conflict().await; + smoke.paged().await; + + smoke.report.print(); + let failures = smoke.report.failures(); + assert!( + failures.is_empty(), + "{} of {} steps failed:\n {}", + failures.len(), + smoke.report.rows.len(), + failures.join("\n ") + ); +} diff --git a/tests/oauth.rs b/tests/oauth.rs new file mode 100644 index 0000000..167a1cc --- /dev/null +++ b/tests/oauth.rs @@ -0,0 +1,597 @@ +//! The OAuth 2.0 side of the client: the authorize URL for both flows, the PKCE +//! challenge, and the token exchange against a local stand-in for the SSO. + +mod support; + +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::Engine; +use esi_openapi::prelude::*; +use sha2::{Digest, Sha256}; +use support::{Reply, Server}; + +struct Flow; + +impl Flow { + /// A client with a secret: the classic web-application flow. + fn with_secret() -> EsiBuilder { + EsiBuilder::new() + .user_agent("oauth tests") + .client_id("the-client") + .client_secret("the-secret") + .callback_url("http://localhost/callback") + .scope("esi-skills.read_skills.v1 esi-wallet.read_character_wallet.v1") + } + + /// A client without a secret: the PKCE flow. + fn with_pkce() -> EsiBuilder { + EsiBuilder::new() + .user_agent("oauth tests") + .client_id("the-client") + .callback_url("http://localhost/callback") + .enable_application_authentication(true) + } + + /// RFC 7636 section 4.2: `BASE64URL(SHA256(ASCII(verifier)))`. + fn challenge_of(verifier: &str) -> String { + URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) + } + + /// The value of a parameter in the query of a URL. + fn parameter(url: &str, name: &str) -> Option { + let query = url.split_once('?')?.1; + query + .split('&') + .find_map(|pair| pair.strip_prefix(&format!("{name}="))) + .map(str::to_owned) + } + + fn token_reply() -> Reply { + Reply::json( + r#"{"access_token":"new-access","expires_in":1199,"refresh_token":"new-refresh","token_type":"Bearer"}"#, + ) + } + + fn token_url(server: &Server) -> String { + format!("{}v2/oauth/token", server.url) + } +} + +#[test] +fn the_challenge_of_the_rfc_7636_example_verifier_matches_the_rfc() { + // Appendix B of RFC 7636. It anchors the helper the tests below rely on. + assert_eq!( + Flow::challenge_of("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); +} + +#[test] +fn the_secret_flow_url_has_the_standard_parameters_and_no_challenge() { + let esi = Flow::with_secret().build().unwrap(); + let info = esi.get_authorize_url().unwrap(); + let url = &info.authorization_url; + + assert_eq!( + Flow::parameter(url, "response_type").as_deref(), + Some("code") + ); + assert_eq!( + Flow::parameter(url, "client_id").as_deref(), + Some("the-client") + ); + assert_eq!( + Flow::parameter(url, "redirect_uri").as_deref(), + Some("http://localhost/callback") + ); + assert_eq!( + Flow::parameter(url, "scope").as_deref(), + Some("esi-skills.read_skills.v1%20esi-wallet.read_character_wallet.v1") + ); + assert_eq!( + Flow::parameter(url, "state").as_deref(), + Some(info.state.as_str()) + ); + assert!(!url.contains("code_challenge"), "{url}"); + assert_eq!(info.pkce_verifier, None); +} + +#[cfg(feature = "random_state")] +#[test] +fn the_state_is_random_and_alphanumeric() { + let esi = Flow::with_secret().build().unwrap(); + let first = esi.get_authorize_url().unwrap().state; + let second = esi.get_authorize_url().unwrap().state; + + assert_eq!(first.len(), 10); + assert!(first.chars().all(|c| c.is_ascii_alphanumeric()), "{first}"); + assert_ne!(first, second); +} + +#[test] +fn the_pkce_url_carries_the_challenge_of_the_returned_verifier() { + let esi = Flow::with_pkce().build().unwrap(); + let info = esi.get_authorize_url().unwrap(); + let verifier = info + .pkce_verifier + .expect("the PKCE flow returns a verifier"); + let url = &info.authorization_url; + + assert_eq!( + Flow::parameter(url, "code_challenge_method").as_deref(), + Some("S256") + ); + assert_eq!( + Flow::parameter(url, "code_challenge").as_deref(), + Some(Flow::challenge_of(&verifier).as_str()) + ); +} + +#[test] +fn the_pkce_verifier_follows_the_rfc_7636_alphabet_and_length() { + let esi = Flow::with_pkce().build().unwrap(); + let verifier = esi.get_authorize_url().unwrap().pkce_verifier.unwrap(); + + // The RFC asks for 43 to 128 characters of [A-Za-z0-9-._~]. + assert!((43..=128).contains(&verifier.len()), "{verifier}"); + assert!( + verifier + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-._~".contains(c)), + "{verifier}" + ); +} + +#[test] +fn every_authorization_gets_its_own_verifier() { + let esi = Flow::with_pkce().build().unwrap(); + let first = esi.get_authorize_url().unwrap().pkce_verifier.unwrap(); + let second = esi.get_authorize_url().unwrap().pkce_verifier.unwrap(); + + assert_ne!(first, second); +} + +#[test] +fn the_authorize_url_needs_the_client_id_and_the_callback() { + let no_id = EsiBuilder::new() + .user_agent("oauth tests") + .client_secret("the-secret") + .callback_url("http://localhost/callback") + .build() + .unwrap(); + assert!(matches!( + no_id.get_authorize_url(), + Err(EsiError::EmptyClientValue(name)) if name == "client_id" + )); + + let no_callback = EsiBuilder::new() + .user_agent("oauth tests") + .client_id("the-client") + .client_secret("the-secret") + .build() + .unwrap(); + assert!(matches!( + no_callback.get_authorize_url(), + Err(EsiError::EmptyClientValue(name)) if name == "callback_url" + )); +} + +#[test] +fn a_secret_and_the_pkce_flow_together_are_rejected() { + let esi = Flow::with_secret() + .enable_application_authentication(true) + .build() + .unwrap(); + + assert!(matches!( + esi.get_authorize_url(), + Err(EsiError::MissingAuthenticationFlowInformation) + )); +} + +#[test] +fn neither_a_secret_nor_the_pkce_flow_is_rejected() { + let esi = EsiBuilder::new() + .user_agent("oauth tests") + .client_id("the-client") + .callback_url("http://localhost/callback") + .build() + .unwrap(); + + assert!(matches!( + esi.get_authorize_url(), + Err(EsiError::MissingAuthenticationFlowInformation) + )); +} + +#[tokio::test] +async fn refreshing_posts_the_form_with_basic_credentials_and_stores_the_answer() { + let server = Server::start(Flow::token_reply()).await; + let mut esi = Flow::with_secret() + .token_url(&Flow::token_url(&server)) + .refresh_token(Some("old-refresh")) + .build() + .unwrap(); + let before = chrono::Utc::now().timestamp_millis(); + esi.refresh_access_token(None).await.unwrap(); + let after = chrono::Utc::now().timestamp_millis(); + + let request = server.only(); + assert_eq!(request.method, "POST"); + assert_eq!(request.path(), "/v2/oauth/token"); + assert_eq!( + request.form(), + ["grant_type=refresh_token", "refresh_token=old-refresh"] + ); + let expected = format!("Basic {}", STANDARD.encode("the-client:the-secret")); + assert_eq!(request.header("authorization"), Some(expected.as_str())); + + assert_eq!(esi.access_token.as_deref(), Some("new-access")); + assert_eq!(esi.refresh_token.as_deref(), Some("new-refresh")); + let expiration = esi.access_expiration.unwrap(); + assert!( + (before + 1_199_000..=after + 1_199_000).contains(&expiration), + "expires_in is seconds: {expiration}" + ); +} + +#[tokio::test] +async fn a_refresh_token_given_to_the_call_wins_over_the_stored_one() { + let server = Server::start(Flow::token_reply()).await; + let mut esi = Flow::with_secret() + .token_url(&Flow::token_url(&server)) + .refresh_token(Some("stored")) + .build() + .unwrap(); + esi.refresh_access_token(Some("given")).await.unwrap(); + + assert_eq!( + server.only().form(), + ["grant_type=refresh_token", "refresh_token=given"] + ); +} + +#[tokio::test] +async fn the_pkce_refresh_sends_the_client_id_and_no_credentials() { + let server = Server::start(Flow::token_reply()).await; + let mut esi = Flow::with_pkce() + .token_url(&Flow::token_url(&server)) + .refresh_token(Some("old-refresh")) + .build() + .unwrap(); + esi.refresh_access_token(None).await.unwrap(); + + let request = server.only(); + assert_eq!( + request.form(), + [ + "client_id=the-client", + "grant_type=refresh_token", + "refresh_token=old-refresh" + ] + ); + assert_eq!(request.header("authorization"), None); +} + +#[tokio::test] +async fn refreshing_without_any_refresh_token_does_not_call_the_sso() { + let server = Server::start(Flow::token_reply()).await; + let mut esi = Flow::with_secret() + .token_url(&Flow::token_url(&server)) + .build() + .unwrap(); + let result = esi.refresh_access_token(None).await; + + assert!(matches!(result, Err(EsiError::NoRefreshTokenAvailable))); + assert!(server.requests().is_empty()); +} + +#[tokio::test] +async fn a_rejected_refresh_reports_the_status_and_keeps_the_old_tokens() { + let server = Server::start(Reply::status(400)).await; + let mut esi = Flow::with_secret() + .token_url(&Flow::token_url(&server)) + .access_token(Some("still-here")) + .refresh_token(Some("old-refresh")) + .build() + .unwrap(); + let result = esi.refresh_access_token(None).await; + + assert!(matches!(result, Err(EsiError::InvalidStatusCode(400)))); + assert_eq!(esi.access_token.as_deref(), Some("still-here")); + assert_eq!(esi.refresh_token.as_deref(), Some("old-refresh")); +} + +/// Without `validate_jwt` the exchange is testable offline: with it the client +/// downloads the SSO keys from a fixed address. +#[cfg(not(feature = "validate_jwt"))] +#[tokio::test] +async fn the_code_exchange_posts_the_code_and_stores_the_tokens() { + let server = Server::start(Flow::token_reply()).await; + let mut esi = Flow::with_secret() + .token_url(&Flow::token_url(&server)) + .build() + .unwrap(); + esi.authenticate("the-code", None).await.unwrap(); + + let request = server.only(); + assert_eq!(request.method, "POST"); + assert_eq!( + request.form(), + ["code=the-code", "grant_type=authorization_code"] + ); + assert_eq!(esi.access_token.as_deref(), Some("new-access")); + assert_eq!(esi.refresh_token.as_deref(), Some("new-refresh")); +} + +#[cfg(not(feature = "validate_jwt"))] +#[tokio::test] +async fn the_pkce_code_exchange_sends_the_verifier() { + let server = Server::start(Flow::token_reply()).await; + let mut esi = Flow::with_pkce() + .token_url(&Flow::token_url(&server)) + .build() + .unwrap(); + esi.authenticate("the-code", Some("the-verifier".to_owned())) + .await + .unwrap(); + + let request = server.only(); + assert_eq!( + request.form(), + [ + "client_id=the-client", + "code=the-code", + "code_verifier=the-verifier", + "grant_type=authorization_code" + ] + ); + assert_eq!(request.header("authorization"), None); +} + +/// The default feature: the token the SSO returns is validated against the +/// keys the metadata document points to. +#[cfg(feature = "validate_jwt")] +mod validated { + use super::*; + use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; + + struct Sso; + + impl Sso { + /// The claims of an EVE SSO token; `expires_in` is seconds from now. + fn claims(audience: &str, issuer: &str, expires_in: i64) -> serde_json::Value { + let now = chrono::Utc::now().timestamp(); + serde_json::json!({ + "aud": [audience, "EVE Online"], + "azp": audience, + "exp": now + expires_in, + "iat": now, + "iss": issuer, + "jti": "00000000-0000-4000-8000-000000000000", + "kid": "JWT-Signature-Key", + "name": "Test Pilot", + "owner": "8PmzCeTKb4VFUDrHLc/AeZXDSWM=", + "region": "world", + "scp": ["esi-skills.read_skills.v1"], + "sub": "CHARACTER:EVE:123123", + "tenant": "tranquility", + "tier": "live" + }) + } + + fn sign(claims: &serde_json::Value) -> String { + let key = include_str!("../resources/test/keys/jwtRS256.key"); + let mut header = Header::new(Algorithm::RS256); + header.kid = Some("JWT-Signature-Key".to_owned()); + encode( + &header, + claims, + &EncodingKey::from_rsa_pem(key.as_bytes()).unwrap(), + ) + .unwrap() + } + + /// A token endpoint that answers with `access_token`. + fn token_reply(access_token: &str) -> Reply { + Reply::json(&format!( + r#"{{"access_token":"{access_token}","expires_in":1199,"refresh_token":"new-refresh","token_type":"Bearer"}}"# + )) + } + + /// A server that plays the SSO: token, metadata and keys. + async fn server(token: Reply) -> Server { + Server::routes(vec![ + ("/v2/oauth/token", token), + ( + "/.well-known", + Reply::json(r#"{"jwks_uri":"{base}oauth/jwks"}"#), + ), + ( + "/oauth/jwks", + Reply::json(include_str!("../resources/test/keys/jwks.json")), + ), + ]) + .await + } + + fn client(server: &Server) -> EsiBuilder { + Flow::with_secret() + .token_url(&Flow::token_url(server)) + .metadata_url(&format!( + "{}.well-known/oauth-authorization-server", + server.url + )) + } + } + + #[tokio::test] + async fn a_valid_token_is_stored_and_its_claims_returned() { + let token = Sso::sign(&Sso::claims( + "the-client", + "https://login.eveonline.com", + 1200, + )); + let server = Sso::server(Sso::token_reply(&token)).await; + let mut esi = Sso::client(&server).build().unwrap(); + let claims = esi.authenticate("the-code", None).await.unwrap().unwrap(); + + assert_eq!(claims.sub, "CHARACTER:EVE:123123"); + assert_eq!(claims.name, "Test Pilot"); + assert_eq!(esi.access_token.as_deref(), Some(token.as_str())); + assert_eq!(esi.refresh_token.as_deref(), Some("new-refresh")); + let paths: Vec<_> = server + .requests() + .iter() + .map(|r| r.path().to_owned()) + .collect(); + assert_eq!( + paths, + [ + "/v2/oauth/token", + "/.well-known/oauth-authorization-server", + "/oauth/jwks" + ] + ); + } + + #[tokio::test] + async fn the_legacy_issuer_without_the_scheme_is_accepted() { + let token = Sso::sign(&Sso::claims("the-client", "login.eveonline.com", 1200)); + let server = Sso::server(Sso::token_reply(&token)).await; + let mut esi = Sso::client(&server).build().unwrap(); + + assert!(esi.authenticate("the-code", None).await.unwrap().is_some()); + } + + #[tokio::test] + async fn a_token_for_another_client_is_rejected_and_not_stored() { + let token = Sso::sign(&Sso::claims( + "someone-else", + "https://login.eveonline.com", + 1200, + )); + let server = Sso::server(Sso::token_reply(&token)).await; + let mut esi = Sso::client(&server).build().unwrap(); + let result = esi.authenticate("the-code", None).await; + + assert!(matches!(result, Err(EsiError::InvalidJWT(_)))); + assert_eq!(esi.access_token, None); + assert_eq!(esi.refresh_token, None); + } + + #[tokio::test] + async fn an_expired_token_is_rejected() { + let token = Sso::sign(&Sso::claims( + "the-client", + "https://login.eveonline.com", + -3600, + )); + let server = Sso::server(Sso::token_reply(&token)).await; + let mut esi = Sso::client(&server).build().unwrap(); + let result = esi.authenticate("the-code", None).await; + + assert!(matches!(result, Err(EsiError::JwtValidationFailed(_)))); + assert_eq!(esi.access_token, None); + } + + #[tokio::test] + async fn a_token_from_another_issuer_is_rejected() { + let token = Sso::sign(&Sso::claims("the-client", "https://evil.example", 1200)); + let server = Sso::server(Sso::token_reply(&token)).await; + let mut esi = Sso::client(&server).build().unwrap(); + let result = esi.authenticate("the-code", None).await; + + assert!(matches!(result, Err(EsiError::InvalidJWT(_)))); + assert_eq!(esi.access_token, None); + } + + #[tokio::test] + async fn a_token_with_a_tampered_signature_is_rejected() { + let token = Sso::sign(&Sso::claims( + "the-client", + "https://login.eveonline.com", + 1200, + )); + let (body, signature) = token.rsplit_once('.').unwrap(); + let flipped = if signature.starts_with('A') { 'B' } else { 'A' }; + let tampered = format!("{body}.{flipped}{}", &signature[1..]); + let server = Sso::server(Sso::token_reply(&tampered)).await; + let mut esi = Sso::client(&server).build().unwrap(); + let result = esi.authenticate("the-code", None).await; + + assert!(matches!(result, Err(EsiError::JwtValidationFailed(_)))); + assert_eq!(esi.access_token, None); + } + + #[tokio::test] + async fn a_metadata_document_without_keys_url_is_an_error() { + let token = Sso::sign(&Sso::claims( + "the-client", + "https://login.eveonline.com", + 1200, + )); + let server = Server::routes(vec![ + ("/v2/oauth/token", Sso::token_reply(&token)), + ("/.well-known", Reply::json("{}")), + ]) + .await; + let mut esi = Sso::client(&server).build().unwrap(); + let result = esi.authenticate("the-code", None).await; + + assert!(matches!(result, Err(EsiError::InvalidJWT(_)))); + assert_eq!(esi.access_token, None); + } + + #[tokio::test] + async fn a_failing_keys_endpoint_is_reported_with_its_status() { + let token = Sso::sign(&Sso::claims( + "the-client", + "https://login.eveonline.com", + 1200, + )); + let server = Server::routes(vec![ + ("/v2/oauth/token", Sso::token_reply(&token)), + ( + "/.well-known", + Reply::json(r#"{"jwks_uri":"{base}oauth/jwks"}"#), + ), + ("/oauth/jwks", Reply::status(503)), + ]) + .await; + let mut esi = Sso::client(&server).build().unwrap(); + let result = esi.authenticate("the-code", None).await; + + assert!(matches!(result, Err(EsiError::InvalidStatusCode(503)))); + assert_eq!(esi.access_token, None); + } + + #[tokio::test] + async fn the_pkce_exchange_validates_the_token_too() { + let token = Sso::sign(&Sso::claims( + "the-client", + "https://login.eveonline.com", + 1200, + )); + let server = Sso::server(Sso::token_reply(&token)).await; + let mut esi = Flow::with_pkce() + .token_url(&Flow::token_url(&server)) + .metadata_url(&format!("{}.well-known/x", server.url)) + .build() + .unwrap(); + esi.authenticate("the-code", Some("the-verifier".to_owned())) + .await + .unwrap(); + + let token_request = &server.requests()[0]; + assert_eq!( + token_request.form(), + [ + "client_id=the-client", + "code=the-code", + "code_verifier=the-verifier", + "grant_type=authorization_code" + ] + ); + assert_eq!(esi.access_token.as_deref(), Some(token.as_str())); + } +} diff --git a/tests/requests.rs b/tests/requests.rs new file mode 100644 index 0000000..3c92955 --- /dev/null +++ b/tests/requests.rs @@ -0,0 +1,320 @@ +//! What the client puts on the wire for each kind of endpoint macro. +//! +//! Every test points the client at a recording local server and checks the +//! method, the path, the query string, the body and the headers of the one +//! request it receives. The real OpenAPI spec resolves the operation IDs, so +//! a path that drifts from the spec also shows up here. + +mod support; + +use esi_openapi::groups::{FittingFlag, FittingItem, NewFitting}; +use esi_openapi::prelude::*; +use esi_openapi::spec::Spec; +use support::{Reply, Server}; + +struct Harness; + +impl Harness { + fn spec() -> Spec { + serde_json::from_str(include_str!("../resources/test/openapi.json")).unwrap() + } + + fn builder(server: &Server) -> EsiBuilder { + EsiBuilder::new() + .user_agent("request tests") + .base_api_url(&server.url) + .spec(Some(Self::spec())) + } + + /// A client that is signed in for another hour. + fn signed_in(server: &Server) -> Esi { + let expiration = chrono::Utc::now().timestamp_millis() + 3_600_000; + Self::builder(server) + .access_token(Some("the-token")) + .access_expiration(Some(expiration)) + .build() + .unwrap() + } + + fn anonymous(server: &Server) -> Esi { + Self::builder(server).build().unwrap() + } +} + +#[tokio::test] +async fn a_public_get_sends_its_path_and_required_query() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::anonymous(&server); + esi.group_market() + .get_region_history(10000002, 34) + .await + .unwrap(); + + let request = server.only(); + assert_eq!(request.method, "GET"); + assert_eq!(request.path(), "/markets/10000002/history"); + assert_eq!(request.query(), ["type_id=34"]); + assert!(request.body.is_empty()); +} + +#[tokio::test] +async fn a_public_request_carries_no_authorization_even_with_a_token() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::signed_in(&server); + esi.group_market() + .get_region_history(10000002, 34) + .await + .unwrap(); + + assert_eq!(server.only().header("authorization"), None); +} + +#[tokio::test] +async fn every_request_carries_the_user_agent_and_the_compatibility_date() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::anonymous(&server); + esi.group_market() + .get_region_history(10000002, 34) + .await + .unwrap(); + + let request = server.only(); + assert_eq!(request.header("user-agent"), Some("request tests")); + let date = request + .header("x-compatibility-date") + .expect("the compatibility date is missing"); + assert_eq!(date.len(), "2026-08-18".len()); + assert!(date.chars().nth(4) == Some('-'), "not a date: {date}"); +} + +#[tokio::test] +async fn an_authenticated_get_sends_the_bearer_token_and_omits_absent_optionals() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::signed_in(&server); + esi.group_contacts() + .get_character_contacts(90000001, None) + .await + .unwrap(); + + let request = server.only(); + assert_eq!(request.method, "GET"); + assert_eq!(request.path(), "/characters/90000001/contacts"); + assert_eq!(request.header("authorization"), Some("Bearer the-token")); + assert!(request.query().is_empty(), "{:?}", request.query()); +} + +#[tokio::test] +async fn an_optional_query_parameter_is_sent_when_given() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::signed_in(&server); + esi.group_contacts() + .get_character_contacts(90000001, Some(3)) + .await + .unwrap(); + + assert_eq!(server.only().query(), ["page=3"]); +} + +#[tokio::test] +async fn an_authenticated_request_without_a_token_never_reaches_the_server() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::anonymous(&server); + let result = esi + .group_contacts() + .get_character_contacts(90000001, None) + .await; + + assert!(matches!(result, Err(EsiError::MissingAuthentication))); + assert!(server.requests().is_empty()); +} + +#[tokio::test] +async fn a_token_without_an_expiration_is_sent_and_does_not_panic() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::builder(&server) + .access_token(Some("no-expiration")) + .build() + .unwrap(); + esi.group_contacts() + .get_character_contacts(90000001, None) + .await + .unwrap(); + + assert_eq!( + server.only().header("authorization"), + Some("Bearer no-expiration") + ); +} + +#[tokio::test] +async fn an_expired_token_never_reaches_the_server() { + let server = Server::start(Reply::json("[]")).await; + let expired = chrono::Utc::now().timestamp_millis() - 1_000; + let esi = Harness::builder(&server) + .access_token(Some("old")) + .access_expiration(Some(expired)) + .build() + .unwrap(); + let result = esi + .group_contacts() + .get_character_contacts(90000001, None) + .await; + + assert!(matches!(result, Err(EsiError::AccessTokenExpired))); + assert!(server.requests().is_empty()); +} + +#[tokio::test] +async fn a_delete_repeats_the_key_for_each_value_of_a_many_parameter() { + let server = Server::start(Reply::status(204)).await; + let esi = Harness::signed_in(&server); + esi.group_contacts() + .delete_character_contacts(90000001, &[11, 22, 33]) + .await + .unwrap(); + + let request = server.only(); + assert_eq!(request.method, "DELETE"); + assert_eq!(request.path(), "/characters/90000001/contacts"); + assert_eq!( + request.query(), + ["contact_ids=11", "contact_ids=22", "contact_ids=33"] + ); + assert_eq!(request.header("authorization"), Some("Bearer the-token")); +} + +#[tokio::test] +async fn a_delete_with_two_path_parameters_fills_both() { + let server = Server::start(Reply::status(204)).await; + let esi = Harness::signed_in(&server); + esi.group_fittings() + .delete_character_fitting(90000001, 777) + .await + .unwrap(); + + let request = server.only(); + assert_eq!(request.method, "DELETE"); + assert_eq!(request.path(), "/characters/90000001/fittings/777"); +} + +#[tokio::test] +async fn a_post_sends_the_json_body_and_its_query_parameters() { + let server = Server::start(Reply::json("[5,6]")).await; + let esi = Harness::signed_in(&server); + let created = esi + .group_contacts() + .add_character_contacts(90000001, 5.5, Some(&[1, 2]), Some(true), &[100, 200]) + .await + .unwrap(); + + assert_eq!(created, [5, 6]); + let request = server.only(); + assert_eq!(request.method, "POST"); + assert_eq!(request.path(), "/characters/90000001/contacts"); + assert_eq!( + request.query(), + ["label_ids=1", "label_ids=2", "standing=5.5", "watched=true"] + ); + assert_eq!(request.json(), serde_json::json!([100, 200])); +} + +#[tokio::test] +async fn a_request_with_a_body_declares_it_as_json() { + let server = Server::start(Reply::json("[5]")).await; + let esi = Harness::signed_in(&server); + esi.group_contacts() + .add_character_contacts(90000001, 1.0, None, None, &[100]) + .await + .unwrap(); + + assert_eq!( + server.only().header("content-type"), + Some("application/json") + ); +} + +#[tokio::test] +async fn a_post_leaves_out_the_optional_parameters_that_are_none() { + let server = Server::start(Reply::json("[5]")).await; + let esi = Harness::signed_in(&server); + esi.group_contacts() + .add_character_contacts(90000001, -10.0, None, None, &[100]) + .await + .unwrap(); + + assert_eq!(server.only().query(), ["standing=-10"]); +} + +#[tokio::test] +async fn a_post_serializes_a_struct_body() { + let server = Server::start(Reply::json(r#"{"fitting_id": 4242}"#)).await; + let esi = Harness::signed_in(&server); + let fitting = NewFitting { + description: "A test fit".to_owned(), + items: vec![FittingItem { + flag: FittingFlag::HiSlot0, + quantity: 1, + type_id: 3001, + }], + name: "Test".to_owned(), + ship_type_id: 587, + }; + let id = esi + .group_fittings() + .create_character_fitting(90000001, &fitting) + .await + .unwrap(); + + assert_eq!(id, 4242); + let request = server.only(); + assert_eq!(request.method, "POST"); + assert_eq!(request.path(), "/characters/90000001/fittings"); + let body = request.json(); + assert_eq!(body["name"], "Test"); + assert_eq!(body["ship_type_id"], 587); + assert_eq!(body["items"][0]["flag"], "HiSlot0"); + assert_eq!(body["items"][0]["type_id"], 3001); +} + +#[tokio::test] +async fn a_put_sends_the_json_body_and_its_query_parameters() { + let server = Server::start(Reply::status(204)).await; + let esi = Harness::signed_in(&server); + esi.group_contacts() + .update_character_contacts(90000001, 2.0, None, Some(false), &[100, 200, 300]) + .await + .unwrap(); + + let request = server.only(); + assert_eq!(request.method, "PUT"); + assert_eq!(request.path(), "/characters/90000001/contacts"); + assert_eq!(request.query(), ["standing=2", "watched=false"]); + assert_eq!(request.json(), serde_json::json!([100, 200, 300])); +} + +#[tokio::test] +async fn the_language_and_tenant_settings_become_headers() { + let server = Server::start(Reply::json("[]")).await; + let esi = Harness::builder(&server) + .language(Language::De) + .tenant("serenity") + .build() + .unwrap(); + esi.group_market() + .get_region_history(10000002, 34) + .await + .unwrap(); + + let request = server.only(); + assert_eq!(request.header("accept-language"), Some("de")); + assert_eq!(request.header("x-tenant"), Some("serenity")); +} + +#[tokio::test] +async fn a_server_error_is_reported_with_its_status() { + let server = Server::start(Reply::status(404)).await; + let esi = Harness::anonymous(&server); + let result = esi.group_market().get_region_history(1, 34).await; + + assert!(result.is_err(), "a 404 must not parse as success"); +} diff --git a/tests/schema_values.rs b/tests/schema_values.rs new file mode 100644 index 0000000..bf1fd4e --- /dev/null +++ b/tests/schema_values.rs @@ -0,0 +1,686 @@ +//! Reads every response type of the crate from data generated out of the OpenAPI +//! fixture in `resources/test/openapi.json`. +//! +//! `conformance.rs` checks that the field *names* of a struct are in the +//! response schema of its operation. This test checks the *values*: for each +//! operation it builds JSON documents from the response schema and +//! deserializes them into the Rust type the crate returns. It catches a field +//! that is `i32` where the schema says `int64`, a field that is not an +//! `Option` where the schema does not require it or allows `null`, and an enum +//! that lacks a variant of the schema. +//! +//! Three kinds of document are built for each operation, once for every value +//! of the enums and `oneOf` choices it contains: +//! - `Full`: every property, with a value; +//! - `Required`: only the required properties; +//! - `Nulls`: every property, with `null` where the schema allows it. + +use esi_openapi::groups::*; +use serde::de::DeserializeOwned; +use serde_json::{json, Map, Value}; +use std::collections::BTreeSet; +use std::fmt::Debug; + +#[derive(Clone, Copy, Debug)] +enum Mode { + Full, + Required, + Nulls, +} + +struct Schemas { + spec: Value, +} + +impl Schemas { + fn load() -> Self { + let spec = serde_json::from_str(include_str!("../resources/test/openapi.json")).unwrap(); + Self { spec } + } + + fn resolve<'a>(&'a self, node: &'a Value) -> &'a Value { + match node.get("$ref").and_then(Value::as_str) { + Some(reference) => { + let mut current = &self.spec; + for key in reference.trim_start_matches("#/").split('/') { + current = ¤t[key]; + } + self.resolve(current) + } + None => node, + } + } + + /// The JSON schema of the successful response of an operation, if it has one. + fn response_schema(&self, op_id: &str) -> Option<&Value> { + for item in self.spec["paths"].as_object().unwrap().values() { + for operation in item.as_object().unwrap().values() { + if operation["operationId"] != op_id { + continue; + } + let (_, response) = operation["responses"] + .as_object()? + .iter() + .find(|(code, _)| code.starts_with('2'))?; + let response = self.resolve(response); + return response["content"]["application/json"].get("schema"); + } + } + panic!("{op_id} is not in the spec"); + } + + /// The type of a schema, ignoring `null`, and whether `null` is allowed. + fn kind<'a>(&self, schema: &'a Value) -> (Option<&'a str>, bool) { + match &schema["type"] { + Value::String(kind) => (Some(kind.as_str()), kind == "null"), + Value::Array(kinds) => { + let nullable = kinds.iter().any(|kind| kind == "null"); + let kind = kinds + .iter() + .filter_map(Value::as_str) + .find(|k| *k != "null"); + (kind, nullable) + } + _ => (None, false), + } + } + + /// How many values the biggest enum or `oneOf` under a schema has. + fn choices(&self, schema: &Value, stack: &mut Vec) -> usize { + let reference = schema.get("$ref").and_then(Value::as_str); + if let Some(reference) = reference { + if stack.iter().any(|seen| seen == reference) { + return 1; + } + stack.push(reference.to_owned()); + } + let node = self.resolve(schema); + let mut most = 1; + if let Some(values) = node["enum"].as_array() { + most = most.max(values.len()); + } + if let Some(variants) = node["oneOf"].as_array() { + most = most.max(variants.len()); + for variant in variants { + most = most.max(self.choices(variant, stack)); + } + } + if let Some(properties) = node["properties"].as_object() { + for property in properties.values() { + most = most.max(self.choices(property, stack)); + } + } + if let Some(items) = node.get("items") { + most = most.max(self.choices(items, stack)); + } + if let Some(extra) = node.get("additionalProperties") { + most = most.max(self.choices(extra, stack)); + } + if reference.is_some() { + stack.pop(); + } + most + } + + /// A document that satisfies the schema; `choice` picks among enum values + /// and `oneOf` variants. + fn sample(&self, schema: &Value, choice: usize, mode: Mode, stack: &mut Vec) -> Value { + let reference = schema.get("$ref").and_then(Value::as_str); + if let Some(reference) = reference { + if stack.iter().any(|seen| seen == reference) { + return Value::Null; + } + stack.push(reference.to_owned()); + } + let node = self.resolve(schema); + let value = self.sample_node(node, choice, mode, stack); + if reference.is_some() { + stack.pop(); + } + value + } + + fn sample_node( + &self, + node: &Value, + choice: usize, + mode: Mode, + stack: &mut Vec, + ) -> Value { + if let Some(values) = node["enum"].as_array() { + return values[choice % values.len()].clone(); + } + if let Some(variants) = node["oneOf"].as_array() { + // A variant is an object with its one property, which the schema does + // not list as required but the variant is meant to carry. + return self.sample( + &variants[choice % variants.len()], + choice, + Mode::Full, + stack, + ); + } + let (kind, _) = self.kind(node); + match kind { + Some("integer") => json!(5_000_000_000_i64), + Some("number") => json!(1.5), + Some("boolean") => json!(true), + Some("string") => match node["format"].as_str() { + Some("date-time") => json!("2026-01-01T00:00:00Z"), + Some("date") => json!("2026-01-01"), + Some("uuid") => json!("00000000-0000-4000-8000-000000000000"), + _ => json!("text"), + }, + Some("array") => { + let item = self.sample(&node["items"], choice, mode, stack); + json!([item]) + } + _ => self.sample_object(node, choice, mode, stack), + } + } + + fn sample_object( + &self, + node: &Value, + choice: usize, + mode: Mode, + stack: &mut Vec, + ) -> Value { + let required: BTreeSet<&str> = node["required"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + let mut object = Map::new(); + for (name, property) in node["properties"].as_object().into_iter().flatten() { + let resolved = self.resolve(property); + let (_, nullable) = self.kind(resolved); + let value = match mode { + Mode::Required if !required.contains(name.as_str()) => continue, + Mode::Nulls if nullable => Value::Null, + _ => self.sample(property, choice, mode, stack), + }; + object.insert(name.clone(), value); + } + if let Some(extra) = node.get("additionalProperties").filter(|v| v.is_object()) { + object.insert("key".to_owned(), self.sample(extra, choice, mode, stack)); + } + Value::Object(object) + } + + /// Deserializes the documents of one operation into `T`. Returns the + /// failure, if any: the first one found. + fn check(&self, op_id: &str) -> Option { + self.check_schema::(op_id, self.response_schema(op_id)?) + } + + fn check_schema( + &self, + op_id: &str, + schema: &Value, + ) -> Option { + let documents = self.choices(schema, &mut Vec::new()); + for choice in 0..documents { + for mode in [Mode::Full, Mode::Required, Mode::Nulls] { + let sample = self.sample(schema, choice, mode, &mut Vec::new()); + let text = sample.to_string(); + let shown: String = text.chars().take(160).collect(); + match serde_json::from_value::(sample) { + Err(error) => { + return Some(format!( + "{op_id} as {} [{mode:?}, choice {choice}]: {error}\n {shown}", + std::any::type_name::() + )); + } + // The enums fall back to `Unrecognized` for a value they do not + // list, which hides a value the schema has. + Ok(value) if format!("{value:?}").contains("Unrecognized") => { + return Some(format!( + "{op_id} as {} [{mode:?}, choice {choice}]: a value of the schema reads as Unrecognized\n {shown}", + std::any::type_name::() + )); + } + Ok(_) => {} + } + } + } + None + } + + /// Like `check`, for an operation whose response wraps the list the crate + /// returns in a private struct: the schema of `field` is read into `T`. + fn check_field(&self, op_id: &str, field: &str) -> Option { + let schema = &self.resolve(self.response_schema(op_id)?)["properties"][field]; + assert!(schema.is_object(), "{op_id} has no property {field}"); + self.check_schema::(op_id, schema) + } + + fn failures(&self) -> Vec { + let schemas = self; + let mut failures: Vec = Vec::new(); + failures.extend(schemas.check::>("GetAlliances")); + failures.extend(schemas.check::("GetAlliancesAllianceId")); + failures.extend(schemas.check::>("GetAlliancesAllianceIdContacts")); + failures.extend(schemas.check::>("GetAlliancesAllianceIdContactsLabels")); + failures.extend(schemas.check::>("GetAlliancesAllianceIdCorporations")); + failures.extend(schemas.check::("GetAlliancesAllianceIdIcons")); + failures.extend(schemas.check::("GetCharactersAccessListsDetail")); + failures.extend(schemas.check_field::>( + "GetCharactersAccessListsListing", + "access_lists", + )); + failures + .extend(schemas.check::>("GetCharactersCharacterIdAgentsResearch")); + failures.extend(schemas.check::>("GetCharactersCharacterIdAssets")); + failures.extend(schemas.check::("GetCharactersCharacterIdAttributes")); + failures.extend(schemas.check::>("GetCharactersCharacterIdBlueprints")); + failures + .extend(schemas.check::>("GetCharactersCharacterIdCalendar")); + failures.extend(schemas.check::("GetCharactersCharacterIdCalendarEventId")); + failures.extend( + schemas.check::>("GetCharactersCharacterIdCalendarEventIdAttendees"), + ); + failures.extend(schemas.check::("GetCharactersCharacterIdClones")); + failures.extend(schemas.check::>("GetCharactersCharacterIdContacts")); + failures + .extend(schemas.check::>("GetCharactersCharacterIdContactsLabels")); + failures.extend(schemas.check::>("GetCharactersCharacterIdContracts")); + failures.extend( + schemas.check::>("GetCharactersCharacterIdContractsContractIdBids"), + ); + failures.extend( + schemas.check::>("GetCharactersCharacterIdContractsContractIdItems"), + ); + failures.extend(schemas.check::>( + "GetCharactersCharacterIdCorporationhistory", + )); + failures.extend(schemas.check::("GetCharactersCharacterIdFatigue")); + failures.extend(schemas.check::>("GetCharactersCharacterIdFittings")); + failures.extend(schemas.check::("GetCharactersCharacterIdFleet")); + failures.extend(schemas.check::("GetCharactersCharacterIdFwStats")); + failures.extend(schemas.check::>("GetCharactersCharacterIdImplants")); + failures.extend(schemas.check::>("GetCharactersCharacterIdIndustryJobs")); + failures.extend( + schemas.check::>("GetCharactersCharacterIdKillmailsRecent"), + ); + failures.extend(schemas.check::("GetCharactersCharacterIdLocation")); + failures + .extend(schemas.check::>("GetCharactersCharacterIdLoyaltyPoints")); + failures.extend(schemas.check::>("GetCharactersCharacterIdMail")); + failures.extend(schemas.check::("GetCharactersCharacterIdMailLabels")); + failures.extend(schemas.check::>("GetCharactersCharacterIdMailLists")); + failures.extend(schemas.check::("GetCharactersCharacterIdMailMailId")); + failures.extend(schemas.check::>("GetCharactersCharacterIdMedals")); + failures.extend(schemas.check::>("GetCharactersCharacterIdMining")); + failures + .extend(schemas.check::>("GetCharactersCharacterIdNotifications")); + failures + .extend(schemas.check::>( + "GetCharactersCharacterIdNotificationsContacts", + )); + failures.extend(schemas.check::("GetCharactersCharacterIdOnline")); + failures.extend(schemas.check::>("GetCharactersCharacterIdOrders")); + failures.extend( + schemas.check::>("GetCharactersCharacterIdOrdersHistory"), + ); + failures.extend(schemas.check::>("GetCharactersCharacterIdPlanets")); + failures.extend(schemas.check::("GetCharactersCharacterIdPlanetsPlanetId")); + failures.extend(schemas.check::("GetCharactersCharacterIdPortrait")); + failures.extend(schemas.check::("GetCharactersCharacterIdRoles")); + failures.extend(schemas.check::("GetCharactersCharacterIdSearch")); + failures.extend(schemas.check::("GetCharactersCharacterIdShip")); + failures.extend(schemas.check::>("GetCharactersCharacterIdSkillqueue")); + failures.extend(schemas.check::("GetCharactersCharacterIdSkills")); + failures.extend(schemas.check::>("GetCharactersCharacterIdStandings")); + failures.extend(schemas.check::>("GetCharactersCharacterIdTitles")); + failures.extend(schemas.check::("GetCharactersCharacterIdWallet")); + failures + .extend(schemas.check::>("GetCharactersCharacterIdWalletJournal")); + failures.extend( + schemas.check::>("GetCharactersCharacterIdWalletTransactions"), + ); + failures.extend( + schemas.check_field::>( + "GetCharactersCosmeticsSkinr", + "licenses", + ), + ); + failures.extend(schemas.check_field::>( + "GetCharactersCosmeticsSkinrComponents", + "licenses", + )); + failures.extend(schemas.check::("GetCharactersDetail")); + failures.extend(schemas.check_field::>( + "GetCharactersFreelanceJobsListing", + "freelance_jobs", + )); + failures + .extend(schemas.check::("GetCharactersFreelanceJobsParticipation")); + failures.extend( + schemas.check::("GetCharactersMercenaryTacticalOperationsDetail"), + ); + failures.extend(schemas.check_field::>( + "GetCharactersMercenaryTacticalOperationsListing", + "operations", + )); + failures.extend( + schemas.check::>( + "GetCharactersMilitaryCampaignsObjectivesListing", + ), + ); + failures.extend( + schemas.check::( + "GetCharactersMilitaryCampaignsObjectivesParticipation", + ), + ); + failures + .extend(schemas.check::>("GetCharactersParagonHubSkinr")); + failures + .extend(schemas.check::("GetCharactersStructuresMercenaryDensDetail")); + failures.extend(schemas.check_field::>( + "GetCharactersStructuresMercenaryDensListing", + "mercenary_dens", + )); + failures + .extend(schemas.check::>("GetContractsPublicBidsContractId")); + failures + .extend(schemas.check::>("GetContractsPublicItemsContractId")); + failures.extend(schemas.check::>("GetContractsPublicRegionId")); + failures.extend( + schemas.check::>("GetCorporationCorporationIdMiningExtractions"), + ); + failures.extend( + schemas.check::>("GetCorporationCorporationIdMiningObservers"), + ); + failures.extend( + schemas.check::>( + "GetCorporationCorporationIdMiningObserversObserverId", + ), + ); + failures.extend(schemas.check::("GetCorporationsCorporationId")); + failures.extend( + schemas.check::>( + "GetCorporationsCorporationIdAlliancehistory", + ), + ); + failures.extend(schemas.check::>("GetCorporationsCorporationIdAssets")); + failures.extend(schemas.check::>("GetCorporationsCorporationIdBlueprints")); + failures.extend(schemas.check::>("GetCorporationsCorporationIdContacts")); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdContactsLabels"), + ); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdContainersLogs"), + ); + failures.extend(schemas.check::>("GetCorporationsCorporationIdContracts")); + failures.extend( + schemas + .check::>("GetCorporationsCorporationIdContractsContractIdBids"), + ); + failures + .extend(schemas.check::>( + "GetCorporationsCorporationIdContractsContractIdItems", + )); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdCustomsOffices"), + ); + failures + .extend(schemas.check::("GetCorporationsCorporationIdDivisions")); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdFacilities"), + ); + failures.extend(schemas.check::("GetCorporationsCorporationIdFwStats")); + failures.extend(schemas.check::("GetCorporationsCorporationIdIcons")); + failures.extend( + schemas + .check::>("GetCorporationsCorporationIdIndustryJobs"), + ); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdKillmailsRecent"), + ); + failures + .extend(schemas.check::>("GetCorporationsCorporationIdMedals")); + failures + .extend(schemas.check::>("GetCorporationsCorporationIdMedalsIssued")); + failures.extend(schemas.check::>("GetCorporationsCorporationIdMembers")); + failures.extend(schemas.check::("GetCorporationsCorporationIdMembersLimit")); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdMembersTitles"), + ); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdMembertracking"), + ); + failures + .extend(schemas.check::>("GetCorporationsCorporationIdOrders")); + failures + .extend(schemas.check::>( + "GetCorporationsCorporationIdOrdersHistory", + )); + failures.extend(schemas.check::>("GetCorporationsCorporationIdRoles")); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdRolesHistory"), + ); + failures + .extend(schemas.check::>("GetCorporationsCorporationIdShareholders")); + failures.extend(schemas.check::>("GetCorporationsCorporationIdStandings")); + failures.extend(schemas.check::>("GetCorporationsCorporationIdStarbases")); + failures.extend( + schemas.check::("GetCorporationsCorporationIdStarbasesStarbaseId"), + ); + failures.extend( + schemas.check::>("GetCorporationsCorporationIdStructures"), + ); + failures + .extend(schemas.check::>("GetCorporationsCorporationIdTitles")); + failures + .extend(schemas.check::>("GetCorporationsCorporationIdWallets")); + failures.extend( + schemas + .check::>("GetCorporationsCorporationIdWalletsDivisionJournal"), + ); + failures.extend(schemas.check::>( + "GetCorporationsCorporationIdWalletsDivisionTransactions", + )); + failures.extend( + schemas.check::>("GetCorporationsFreelanceJobsListing"), + ); + failures.extend( + schemas.check::>("GetCorporationsFreelanceJobsParticipants"), + ); + failures.extend(schemas.check::>("GetCorporationsNpccorps")); + failures + .extend(schemas.check::("GetCorporationsProjectsContribution")); + failures.extend( + schemas.check::>("GetCorporationsProjectsContributors"), + ); + failures.extend(schemas.check::("GetCorporationsProjectsDetail")); + failures.extend(schemas.check::>("GetCorporationsProjectsListing")); + failures.extend(schemas.check::("GetCorporationsStructuresSkyhooksDetail")); + failures.extend(schemas.check_field::>( + "GetCorporationsStructuresSkyhooksListing", + "skyhooks", + )); + failures.extend( + schemas.check::( + "GetCorporationsStructuresSovereigntyHubsDetail", + ), + ); + failures.extend(schemas.check_field::>( + "GetCorporationsStructuresSovereigntyHubsListing", + "sovereignty_hubs", + )); + failures.extend(schemas.check::("GetCosmeticsSkinr")); + failures.extend(schemas.check::>("GetDogmaAttributes")); + failures.extend(schemas.check::("GetDogmaAttributesAttributeId")); + failures.extend(schemas.check::("GetDogmaDynamicItemsTypeIdItemId")); + failures.extend(schemas.check::>("GetDogmaEffects")); + failures.extend(schemas.check::("GetDogmaEffectsEffectId")); + failures.extend(schemas.check::("GetFleetsFleetId")); + failures.extend(schemas.check::>("GetFleetsFleetIdMembers")); + failures.extend(schemas.check::>("GetFleetsFleetIdWings")); + failures.extend(schemas.check::("GetFreelanceJobsDetail")); + failures.extend(schemas.check::>("GetFreelanceJobsListing")); + failures.extend(schemas.check::("GetFwLeaderboards")); + failures.extend(schemas.check::("GetFwLeaderboardsCharacters")); + failures + .extend(schemas.check::("GetFwLeaderboardsCorporations")); + failures.extend(schemas.check::>("GetFwStats")); + failures.extend(schemas.check::>("GetFwSystems")); + failures.extend(schemas.check::>("GetFwWars")); + failures.extend(schemas.check::>("GetIncursions")); + failures.extend(schemas.check::>("GetIndustryFacilities")); + failures.extend(schemas.check::>("GetIndustrySystems")); + failures.extend(schemas.check::>("GetInsurancePrices")); + failures.extend(schemas.check::("GetKillmailsKillmailIdKillmailHash")); + failures.extend(schemas.check::>("GetLoyaltyStoresCorporationIdOffers")); + failures.extend(schemas.check::>("GetMarketsGroups")); + failures.extend(schemas.check::("GetMarketsGroupsMarketGroupId")); + failures.extend(schemas.check::>("GetMarketsPrices")); + failures.extend(schemas.check::>("GetMarketsRegionIdHistory")); + failures.extend(schemas.check::>("GetMarketsRegionIdOrders")); + failures.extend(schemas.check::>("GetMarketsRegionIdTypes")); + failures.extend(schemas.check::>("GetMarketsStructuresStructureId")); + failures.extend(schemas.check::("GetMetaChangelog")); + failures.extend(schemas.check::("GetMetaCompatibilityDates")); + failures.extend(schemas.check::("GetMetaName")); + failures.extend(schemas.check::("GetMetaStatus")); + failures.extend(schemas.check::("GetMilitaryCampaignsDetail")); + failures.extend( + schemas.check_field::>("GetMilitaryCampaignsListing", "campaigns"), + ); + failures.extend(schemas.check::("GetMilitaryCampaignsObjectivesDetail")); + failures.extend(schemas.check::>("GetMilitaryCampaignsObjectivesListing")); + failures.extend(schemas.check::>("GetParagonHubSkinr")); + failures.extend(schemas.check::>("GetParagonHubSkinrAlliances")); + failures.extend(schemas.check::>("GetParagonHubSkinrCharacters")); + failures.extend(schemas.check::>("GetParagonHubSkinrCorporations")); + failures + .extend(schemas.check_field::>("GetSkyhooksRaidable", "skyhooks")); + failures.extend(schemas.check::>("GetSovereigntyCampaigns")); + failures.extend( + schemas.check_field::>("GetSovereigntySystems", "solar_systems"), + ); + failures.extend(schemas.check::("GetStatus")); + failures.extend(schemas.check::>("GetUniverseAncestries")); + failures.extend(schemas.check::("GetUniverseAsteroidBeltsAsteroidBeltId")); + failures.extend(schemas.check::>("GetUniverseBloodlines")); + failures.extend(schemas.check::>("GetUniverseCategories")); + failures.extend(schemas.check::("GetUniverseCategoriesCategoryId")); + failures.extend(schemas.check::>("GetUniverseConstellations")); + failures.extend(schemas.check::("GetUniverseConstellationsConstellationId")); + failures.extend(schemas.check::>("GetUniverseFactions")); + failures.extend(schemas.check::>("GetUniverseGraphics")); + failures.extend(schemas.check::("GetUniverseGraphicsGraphicId")); + failures.extend(schemas.check::>("GetUniverseGroups")); + failures.extend(schemas.check::("GetUniverseGroupsGroupId")); + failures.extend(schemas.check::("GetUniverseMoonsMoonId")); + failures.extend(schemas.check::("GetUniversePlanetsPlanetId")); + failures.extend(schemas.check::>("GetUniverseRaces")); + failures.extend(schemas.check::>("GetUniverseRegions")); + failures.extend(schemas.check::("GetUniverseRegionsRegionId")); + failures.extend(schemas.check::("GetUniverseSchematicsSchematicId")); + failures.extend(schemas.check::("GetUniverseStargatesStargateId")); + failures.extend(schemas.check::("GetUniverseStarsStarId")); + failures.extend(schemas.check::("GetUniverseStationsStationId")); + failures.extend(schemas.check::>("GetUniverseStructures")); + failures.extend(schemas.check::("GetUniverseStructuresStructureId")); + failures.extend(schemas.check::>("GetUniverseSystemJumps")); + failures.extend(schemas.check::>("GetUniverseSystemKills")); + failures.extend(schemas.check::>("GetUniverseSystems")); + failures.extend(schemas.check::("GetUniverseSystemsSystemId")); + failures.extend(schemas.check::>("GetUniverseTypes")); + failures.extend(schemas.check::("GetUniverseTypesTypeId")); + failures.extend(schemas.check::>("GetWars")); + failures.extend(schemas.check::("GetWarsWarId")); + failures.extend(schemas.check::>("GetWarsWarIdKillmails")); + failures.extend(schemas.check::>("PostCharactersAffiliation")); + failures.extend( + schemas.check::>("PostCharactersCharacterIdAssetsLocations"), + ); + failures.extend(schemas.check::>("PostCharactersCharacterIdAssetsNames")); + failures.extend(schemas.check::>("PostCharactersCharacterIdContacts")); + failures.extend(schemas.check::("PostCharactersCharacterIdCspa")); + failures + .extend(schemas.check_field::("PostCharactersCharacterIdFittings", "fitting_id")); + failures.extend(schemas.check::("PostCharactersCharacterIdMail")); + failures.extend(schemas.check::("PostCharactersCharacterIdMailLabels")); + failures.extend( + schemas.check::>("PostCorporationsCorporationIdAssetsLocations"), + ); + failures + .extend(schemas.check::>("PostCorporationsCorporationIdAssetsNames")); + failures.extend(schemas.check::("PostFleetsFleetIdWings")); + failures.extend(schemas.check::("PostFleetsFleetIdWingsWingIdSquads")); + failures.extend(schemas.check::("PostRoute")); + failures.extend(schemas.check::("PostUniverseIds")); + failures.extend(schemas.check::>("PostUniverseNames")); + + failures + } +} + +#[test] +fn every_response_type_reads_the_documents_the_schema_describes() { + let failures = Schemas::load().failures(); + + assert!( + failures.is_empty(), + "{} operations do not read what their schema allows:\n {}", + failures.len(), + failures.join("\n ") + ); +} + +#[test] +fn every_operation_with_a_json_response_is_in_the_list() { + let schemas = Schemas::load(); + let listed = include_str!("schema_values.rs"); + let mut missing = Vec::new(); + for item in schemas.spec["paths"].as_object().unwrap().values() { + for operation in item.as_object().unwrap().values() { + let Some(op_id) = operation["operationId"].as_str() else { + continue; + }; + if schemas.response_schema(op_id).is_some() && !listed.contains(&format!("\"{op_id}\"")) + { + missing.push(op_id.to_owned()); + } + } + } + + assert!( + missing.is_empty(), + "add these operations to `failures`: {missing:?}" + ); +} + +#[test] +fn the_documents_built_from_a_schema_follow_it() { + let schemas = Schemas::load(); + let schema = json!({ + "type": "object", + "required": ["id"], + "properties": { + "id": {"type": "integer", "format": "int64"}, + "kind": {"type": "string", "enum": ["a", "b", "c"]}, + "note": {"type": ["string", "null"]}, + "price": {"oneOf": [ + {"type": "object", "properties": {"isk": {"type": "number"}}}, + {"type": "object", "properties": {"plex": {"type": "integer"}}} + ]} + } + }); + + assert_eq!(schemas.choices(&schema, &mut Vec::new()), 3); + let full = schemas.sample(&schema, 1, Mode::Full, &mut Vec::new()); + assert_eq!( + full, + json!({"id": 5_000_000_000_i64, "kind": "b", "note": "text", "price": {"plex": 5_000_000_000_i64}}) + ); + let required = schemas.sample(&schema, 0, Mode::Required, &mut Vec::new()); + assert_eq!(required, json!({"id": 5_000_000_000_i64})); + let nulls = schemas.sample(&schema, 0, Mode::Nulls, &mut Vec::new()); + assert_eq!(nulls["note"], Value::Null); + assert_eq!(nulls["kind"], "a"); +} diff --git a/tests/support/mod.rs b/tests/support/mod.rs new file mode 100644 index 0000000..9fc6f29 --- /dev/null +++ b/tests/support/mod.rs @@ -0,0 +1,253 @@ +//! A tiny local HTTP server that records the requests it receives and answers +//! each with the same reply. The integration tests that check what the client +//! sends use it instead of ESI. + +#![allow(dead_code)] + +use std::sync::{Arc, Mutex}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +/// One request as the server received it. +#[derive(Debug, Clone)] +pub struct Recorded { + pub method: String, + /// The path and the query string, as sent. + pub target: String, + headers: Vec<(String, String)>, + pub body: String, +} + +impl Recorded { + fn parse(raw: &str) -> Self { + let (head, body) = raw.split_once("\r\n\r\n").unwrap_or((raw, "")); + let mut lines = head.lines(); + let mut request_line = lines.next().unwrap_or_default().split_whitespace(); + let method = request_line.next().unwrap_or_default().to_owned(); + let target = request_line.next().unwrap_or_default().to_owned(); + let headers = lines + .filter_map(|line| line.split_once(':')) + .map(|(name, value)| (name.trim().to_lowercase(), value.trim().to_owned())) + .collect(); + Self { + method, + target, + headers, + body: body.to_owned(), + } + } + + /// The value of a header (the name in lowercase). + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value.as_str()) + } + + pub fn path(&self) -> &str { + self.target.split('?').next().unwrap_or_default() + } + + /// The `key=value` pairs of the query string, sorted, as sent. + pub fn query(&self) -> Vec { + Self::sorted_pairs(self.target.split_once('?').map_or("", |(_, query)| query)) + } + + /// The `key=value` pairs of a form body, sorted, as sent. + pub fn form(&self) -> Vec { + Self::sorted_pairs(&self.body) + } + + /// The body as JSON. + pub fn json(&self) -> serde_json::Value { + serde_json::from_str(&self.body).expect("the body is not JSON") + } + + fn sorted_pairs(text: &str) -> Vec { + let mut pairs: Vec = text + .split('&') + .filter(|pair| !pair.is_empty()) + .map(str::to_owned) + .collect(); + pairs.sort(); + pairs + } +} + +/// The answer the server gives to every request. +#[derive(Clone)] +pub struct Reply { + status: u16, + headers: Vec<(String, String)>, + body: String, +} + +impl Reply { + /// A `200` with a JSON body. + pub fn json(body: &str) -> Self { + Self { + status: 200, + headers: vec![("Content-Type".to_owned(), "application/json".to_owned())], + body: body.to_owned(), + } + } + + /// No answer at all: the server reads the request and keeps the connection + /// open without writing, to test timeouts. + pub fn never() -> Self { + Self { + status: 0, + headers: Vec::new(), + body: String::new(), + } + } + + /// An empty answer with the given status. + pub fn status(status: u16) -> Self { + Self { + status, + headers: Vec::new(), + body: String::new(), + } + } + + pub fn with_header(mut self, name: &str, value: &str) -> Self { + self.headers.push((name.to_owned(), value.to_owned())); + self + } + + /// The raw answer; `{base}` in the body stands for the address of the server. + fn render(&self, base: &str) -> String { + if self.status == 0 { + return String::new(); + } + let body = self.body.replace("{base}", base); + let mut text = format!("HTTP/1.1 {} Test\r\n", self.status); + for (name, value) in &self.headers { + text.push_str(&format!("{name}: {value}\r\n")); + } + text.push_str(&format!( + "Content-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + )); + text + } +} + +pub struct Server { + /// The address to give the client, ending in `/`. + pub url: String, + requests: Arc>>, +} + +impl Server { + /// A server that gives every request the same reply. + pub async fn start(reply: Reply) -> Self { + Self::routes(vec![("/", reply)]).await + } + + /// A server with a reply per path prefix; the first prefix that matches + /// wins and a path that matches none gets a `404`. + pub async fn routes(routes: Vec<(&str, Reply)>) -> Self { + Self::launch( + routes + .into_iter() + .map(|(prefix, reply)| (prefix, vec![reply])) + .collect(), + ) + .await + } + + /// A server that answers the first request with the first reply, the + /// second with the second, and so on; the last reply repeats. + pub async fn sequence(replies: Vec) -> Self { + Self::launch(vec![("/", replies)]).await + } + + async fn launch(routes: Vec<(&str, Vec)>) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/", listener.local_addr().unwrap()); + let requests: Arc>> = Arc::new(Mutex::new(Vec::new())); + let seen = Arc::clone(&requests); + let answers: Vec<(String, Vec)> = routes + .into_iter() + .map(|(prefix, replies)| { + let texts = replies.iter().map(|reply| reply.render(&url)).collect(); + (prefix.to_owned(), texts) + }) + .collect(); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let seen = Arc::clone(&seen); + let answers = answers.clone(); + tokio::spawn(async move { + let raw = Self::read_request(&mut socket).await; + let recorded = Recorded::parse(&raw); + let answer = { + let mut recorded_so_far = seen.lock().unwrap(); + let route = answers + .iter() + .find(|(prefix, _)| recorded.path().starts_with(prefix.as_str())); + let answer = route.map_or_else( + || Reply::status(404).render(""), + |(prefix, texts)| { + let before = recorded_so_far + .iter() + .filter(|request| request.path().starts_with(prefix.as_str())) + .count(); + texts[before.min(texts.len() - 1)].clone() + }, + ); + recorded_so_far.push(recorded); + answer + }; + if answer.is_empty() { + tokio::time::sleep(std::time::Duration::from_secs(60)).await; + } + let _ = socket.write_all(answer.as_bytes()).await; + }); + } + }); + Self { url, requests } + } + + /// Reads the head and as much body as `Content-Length` announces. + async fn read_request(socket: &mut tokio::net::TcpStream) -> String { + let mut data: Vec = Vec::new(); + let mut buffer = [0u8; 4096]; + loop { + let read = socket.read(&mut buffer).await.unwrap_or(0); + if read == 0 { + break; + } + data.extend_from_slice(&buffer[..read]); + let Some(head_end) = data.windows(4).position(|window| window == b"\r\n\r\n") else { + continue; + }; + let head = String::from_utf8_lossy(&data[..head_end]).to_lowercase(); + let length = head + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(0); + if data.len() >= head_end + 4 + length { + break; + } + } + String::from_utf8_lossy(&data).into_owned() + } + + pub fn requests(&self) -> Vec { + self.requests.lock().unwrap().clone() + } + + /// The only request received; fails if there were none or several. + pub fn only(&self) -> Recorded { + let requests = self.requests(); + assert_eq!(requests.len(), 1, "expected one request: {requests:#?}"); + requests[0].clone() + } +}