Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ takes it when asked for: `shopify_api = "=1.0.0-rc.1"`.

A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATION.md).

### Since 1.0.0-rc.3

- Added: an admin origin, for a local stand-in of Shopify (local-storefront's `http://localhost:9292`), a mock server or a proxy: `ShopifyBuilder::admin_origin` and `ShopifyApp::with_admin_origin` send the requests built from the shop's domain (GraphQL, the client credentials grant, refresh tokens, the code and token exchanges) and the install link of `authorization_url` to that origin instead of `https://{shop}`. Only the scheme, the host and the port change: the paths are Shopify's, and the shop stays the identity of the session tokens, the tokens and the errors. The requests sent there name the shop in `X-Forwarded-Host`, and the install link in a last `shop` parameter. `ShopifyApp::builder` and `ShopifyApp::client` pass the origin on to their clients; `Shopify::admin_origin` and `ShopifyApp::admin_origin` read it. `AdminOrigin` checks it: an absolute `https://` URL, or `http://` to `localhost`, `127.0.0.1` or `[::1]` only, with no path (a trailing `/` aside), query string, fragment or user; anything else is an `Error::Config` that does not show what was given. Without it, nothing changes.

### Since 1.0.0-rc.2

- Changed: `graphql!` downloads a schema file only with the new `schema-download` feature (in `full` too), off by default. Without it the macro has no HTTP client (28 crates in its build instead of 55) and a build never uses the network: a file of the version the crate asks for is read as it is, and a missing or outdated one is a compile error that names `shopify-api schema download`. With it, `CARGO_NET_OFFLINE=true` also keeps the build offline.
Expand Down
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,43 @@ assert_eq!(my_code_under_test(&shopify).await?, "Test shop");
assert_eq!(mock.graphql_requests()[0].operation_name.as_deref(), Some("Shop"));
```

## A local Shopify: `admin_origin`

`admin_origin` sends the requests built from the shop's domain to another
origin than `https://{shop}`: a local stand-in of Shopify such as
[local-storefront](https://github.com/0xtlt/local-storefront), a mock server,
or a proxy. Only the scheme, the host and the port change: the paths are
Shopify's, and the shop stays the shop (the session tokens verified, the
tokens obtained, the errors).

```rust,ignore
use shopify_api::Shopify;
use shopify_api::oauth::ShopifyApp;

// A client: its GraphQL requests, and those of its client credentials or refresh token.
let shopify = Shopify::builder("local-supply-co.myshopify.com")
.admin_origin("http://localhost:9292")
.access_token(token)
.build()?;

// An app (feature `oauth`): its code and token exchanges, its install links,
// and every client its `builder` and `client` make.
let mut app = ShopifyApp::new(client_id, client_secret);
if let Ok(origin) = std::env::var("LSF_URL") {
app = app.with_admin_origin(origin)?;
}
```

The origin is `https://host[:port]`, or `http://` to `localhost`, `127.0.0.1`
or `[::1]` only, so that an access token never leaves the machine in clear
text; it has no path (a trailing `/` aside), query string, fragment or user.
`build` and `with_admin_origin` refuse anything else with `Error::Config`,
which does not show what was given. The requests sent to the origin name the
shop in `X-Forwarded-Host`, and the install link in a last `shop` parameter,
so that one origin can serve several shops. The addresses an answer gives (a
bulk operation's results, a staged upload's target) are used as they come.
Without `admin_origin`, nothing changes.

## Features

| Feature | |
Expand Down
33 changes: 27 additions & 6 deletions crates/shopify_api/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::{Mutex, OwnedMutexGuard};

use crate::origin::admin_url;
use crate::transport::{BoxFuture, HttpRequest, Method, Transport};
use crate::{Error, OAuthErrorCode, Result, ShopDomain};
use crate::{AdminOrigin, Error, OAuthErrorCode, Result, ShopDomain};

/// How a [`Shopify`](crate::Shopify) client gets its access token.
///
Expand Down Expand Up @@ -317,8 +318,22 @@ impl TokenResponse {
}
}

fn token_url(shop: &ShopDomain) -> String {
format!("https://{shop}/admin/oauth/access_token")
/// The token endpoint of `shop`, at `origin` when there is one.
fn token_url(shop: &ShopDomain, origin: Option<&AdminOrigin>) -> String {
admin_url(shop, origin, "/admin/oauth/access_token")
}

/// `request`, saying which shop it is for when it goes to an admin origin
/// instead of the shop's own host: one origin may serve several shops.
pub(crate) fn for_shop(
request: HttpRequest,
shop: &ShopDomain,
origin: Option<&AdminOrigin>,
) -> HttpRequest {
match origin {
Some(_) => request.with_header("X-Forwarded-Host", shop.as_str()),
None => request,
}
}

/// How the fields of a token request travel.
Expand All @@ -330,20 +345,22 @@ pub(crate) enum Encoding {
Json,
}

/// Asks the token endpoint of `shop` for a token. A refusal says what
/// Shopify answered, never what was sent.
/// Asks the token endpoint of `shop` for a token, at `origin` when there is
/// one. A refusal says what Shopify answered, never what was sent.
pub(crate) async fn request_token(
transport: &dyn Transport,
shop: &ShopDomain,
origin: Option<&AdminOrigin>,
user_agent: &str,
encoding: Encoding,
fields: &[(&str, &str)],
) -> Result<TokenData> {
let url = token_url(shop);
let url = token_url(shop, origin);
let request = HttpRequest::new(Method::Post, &url)
.with_header("Accept", "application/json")
.with_header("User-Agent", user_agent)
.with_timeout(Duration::from_secs(30));
let request = for_shop(request, shop, origin);
let request = match encoding {
Encoding::Form => request.with_form(fields),
Encoding::Json => {
Expand Down Expand Up @@ -413,6 +430,8 @@ const FAILURE_HOLD: Duration = Duration::from_secs(5);
pub(crate) struct Endpoint {
pub transport: Arc<dyn Transport>,
pub shop: ShopDomain,
/// Where the requests built from `shop` go instead of `https://{shop}`.
pub admin_origin: Option<AdminOrigin>,
pub user_agent: String,
}

Expand Down Expand Up @@ -643,6 +662,7 @@ async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result<Token
request_token(
transport,
&endpoint.shop,
endpoint.admin_origin.as_ref(),
&endpoint.user_agent,
Encoding::Form,
&fields,
Expand Down Expand Up @@ -672,6 +692,7 @@ async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result<Token
let mut token = request_token(
transport,
&endpoint.shop,
endpoint.admin_origin.as_ref(),
&endpoint.user_agent,
Encoding::Json,
&fields,
Expand Down
125 changes: 120 additions & 5 deletions crates/shopify_api/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use std::sync::Arc;
use std::time::Duration;

use crate::auth::{Endpoint, Tokens};
use crate::origin::admin_url;
use crate::transport::{Transport, default_transport};
use crate::{ApiVersion, Auth, Error, Result, ShopDomain, TokenData, TokenStore};
use crate::{AdminOrigin, ApiVersion, Auth, Error, Result, ShopDomain, TokenData, TokenStore};

/// The `User-Agent` of every request, unless [`ShopifyBuilder::user_agent`] sets another.
pub const USER_AGENT: &str = concat!("shopify_api/", env!("CARGO_PKG_VERSION"), " (Rust)");
Expand Down Expand Up @@ -46,6 +47,7 @@ impl std::fmt::Debug for Shopify {
formatter
.debug_struct("Shopify")
.field("shop", &self.shared.endpoint.shop)
.field("admin_origin", &self.shared.endpoint.admin_origin)
.field("api_version", &self.pinned)
.field("retry", &self.retry)
.finish_non_exhaustive()
Expand All @@ -62,6 +64,7 @@ impl Shopify {
pub fn builder(shop: impl AsRef<str>) -> ShopifyBuilder {
ShopifyBuilder {
shop: shop.as_ref().to_string(),
admin_origin: None,
auth: None,
api_version: None,
transport: None,
Expand All @@ -76,6 +79,12 @@ impl Shopify {
&self.shared.endpoint.shop
}

/// The origin requests go to instead of `https://{shop}`, when
/// [`ShopifyBuilder::admin_origin`] set one.
pub fn admin_origin(&self) -> Option<&AdminOrigin> {
self.shared.endpoint.admin_origin.as_ref()
}

/// The version requests go to: the one pinned with
/// [`ShopifyBuilder::api_version`], else [`ApiVersion::DEFAULT`].
///
Expand Down Expand Up @@ -106,11 +115,14 @@ impl Shopify {
}
}

/// `https://{shop}/admin/api/{version}/graphql.json`.
/// `https://{shop}/admin/api/{version}/graphql.json`, or the same path at
/// the [admin origin](ShopifyBuilder::admin_origin) when there is one.
pub fn graphql_url(&self, version: ApiVersion) -> String {
format!(
"https://{}/admin/api/{version}/graphql.json",
self.shared.endpoint.shop
let endpoint = &self.shared.endpoint;
admin_url(
&endpoint.shop,
endpoint.admin_origin.as_ref(),
&format!("/admin/api/{version}/graphql.json"),
)
}

Expand Down Expand Up @@ -320,6 +332,9 @@ fn jitter_fraction() -> f64 {
#[must_use]
pub struct ShopifyBuilder {
shop: String,
/// Checked when it is given, refused by `build`. Set by
/// `ShopifyApp::builder` too, with the app's.
pub(crate) admin_origin: Option<Result<AdminOrigin>>,
auth: Option<Auth>,
api_version: Option<ApiVersion>,
/// Set by `ShopifyApp::builder` too, with the app's.
Expand All @@ -335,6 +350,7 @@ impl std::fmt::Debug for ShopifyBuilder {
formatter
.debug_struct("ShopifyBuilder")
.field("shop", &self.shop)
.field("admin_origin", &self.admin_origin)
.field("auth", &self.auth)
.field("api_version", &self.api_version)
.field("retry", &self.retry)
Expand Down Expand Up @@ -376,6 +392,51 @@ impl ShopifyBuilder {
self
}

/// Sends the requests built from the shop's domain to `origin` instead of
/// `https://{shop}`: the GraphQL requests, and the token requests of the
/// client credentials grant and of refresh tokens. Only the scheme, the
/// host and the port change; the shop stays the shop, and each request
/// names it in `X-Forwarded-Host`. For a local stand-in of Shopify, such
/// as [local-storefront](https://github.com/0xtlt/local-storefront), or a
/// proxy.
///
/// `origin` is an [`AdminOrigin`]: `https://host[:port]`, or `http://`
/// to `localhost`, `127.0.0.1` or `[::1]` only. [`build`](Self::build)
/// fails with [`Error::Config`] when it is not one. Without it, the
/// requests go to `https://{shop}`.
///
/// ```
/// # #[cfg(any(feature = "rustls", feature = "native-tls"))]
/// # {
/// use shopify_api::{ApiVersion, Shopify};
///
/// // The Admin API of local-storefront: the token picks the shop.
/// let shopify = Shopify::builder("local-supply-co.myshopify.com")
/// .admin_origin("http://localhost:9292")
/// .access_token("shpat_…")
/// .build()?;
/// assert_eq!(
/// shopify.graphql_url(ApiVersion::V2026_10),
/// "http://localhost:9292/admin/api/2026-10/graphql.json"
/// );
/// assert_eq!(shopify.shop().as_str(), "local-supply-co.myshopify.com");
///
/// // Not in clear text off this machine.
/// assert!(
/// Shopify::builder("my-shop")
/// .admin_origin("http://lsf.example.com")
/// .access_token("shpat_…")
/// .build()
/// .is_err()
/// );
/// # }
/// # Ok::<(), shopify_api::Error>(())
/// ```
pub fn admin_origin(mut self, origin: impl AsRef<str>) -> Self {
self.admin_origin = Some(AdminOrigin::new(origin.as_ref()));
self
}

pub fn retry(mut self, retry: RetryPolicy) -> Self {
self.retry = retry;
self
Expand All @@ -401,6 +462,7 @@ impl ShopifyBuilder {

pub fn build(self) -> Result<Shopify> {
let shop = ShopDomain::new(&self.shop)?;
let admin_origin = self.admin_origin.transpose()?;
let auth = self.auth.ok_or_else(|| {
Error::auth("no credentials: call `access_token`, `client_credentials` or `auth`")
})?;
Expand All @@ -413,6 +475,7 @@ impl ShopifyBuilder {
endpoint: Arc::new(Endpoint {
transport,
shop,
admin_origin,
user_agent: self.user_agent,
}),
tokens: Tokens::new(auth, self.token_store, self.refresh_leeway),
Expand Down Expand Up @@ -512,6 +575,58 @@ mod tests {
);
}

#[cfg(feature = "testing")]
#[test]
fn an_admin_origin_moves_the_graphql_url_only() {
let shopify = Shopify::builder("my-shop")
.admin_origin("http://localhost:9292/")
.access_token("t")
.transport(crate::testing::MockTransport::new())
.build()
.unwrap();
assert_eq!(
shopify.graphql_url(ApiVersion::V2026_10),
"http://localhost:9292/admin/api/2026-10/graphql.json"
);
assert_eq!(shopify.shop().as_str(), "my-shop.myshopify.com");
assert_eq!(
shopify.admin_origin().map(AdminOrigin::as_str),
Some("http://localhost:9292")
);
assert!(format!("{shopify:?}").contains("http://localhost:9292"));

let without = Shopify::builder("my-shop")
.access_token("t")
.transport(crate::testing::MockTransport::new())
.build()
.unwrap();
assert_eq!(without.admin_origin(), None);
assert_eq!(
without.graphql_url(ApiVersion::V2026_10),
"https://my-shop.myshopify.com/admin/api/2026-10/graphql.json"
);
}

#[cfg(feature = "testing")]
#[test]
fn building_refuses_an_invalid_admin_origin() {
for origin in [
"http://lsf.example.com",
"http://localhost:9292/admin",
"localhost:9292",
"http://user:shpat_secret@localhost:9292",
] {
let builder = Shopify::builder("my-shop")
.admin_origin(origin)
.access_token("t")
.transport(crate::testing::MockTransport::new());
assert!(!format!("{builder:?}").contains("shpat_secret"));
let error = builder.build().unwrap_err();
assert!(matches!(error, Error::Config(_)), "{origin}: {error:?}");
assert!(!error.to_string().contains("shpat_secret"));
}
}

#[test]
fn building_needs_a_shop_and_credentials() {
assert!(matches!(
Expand Down
19 changes: 17 additions & 2 deletions crates/shopify_api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -951,8 +951,14 @@ mod tests {
fn token_endpoint(status: u16, body: String) -> Error {
let shop = crate::ShopDomain::new("a-shop").unwrap();
let transport = Answer(status, body);
let future =
crate::auth::request_token(&transport, &shop, "test", crate::auth::Encoding::Form, &[]);
let future = crate::auth::request_token(
&transport,
&shop,
None,
"test",
crate::auth::Encoding::Form,
&[],
);
tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
Expand Down Expand Up @@ -1172,6 +1178,15 @@ mod tests {
"Config",
Error::Config("the HTTP client does not start".to_string()),
));
for origin in [
format!("http://me:{TOKEN}@localhost:9292"),
format!("http://localhost:9292/?token={TOKEN}"),
format!("http://{TOKEN}.example.com"),
TOKEN.to_string(),
SIGNED_URL.to_string(),
] {
errors.push(("Config", crate::AdminOrigin::new(&origin).unwrap_err()));
}
#[cfg(feature = "webhooks")]
{
use base64::Engine;
Expand Down
2 changes: 2 additions & 0 deletions crates/shopify_api/src/graphql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ impl Shopify {
.with_header("User-Agent", &self.shared.endpoint.user_agent)
.with_header("X-Shopify-Access-Token", &token)
.with_body(body.clone());
let request =
crate::auth::for_shop(request, &endpoint.shop, endpoint.admin_origin.as_ref());
let may_retry = retries < self.retry.max_retries();
let response = match self.shared.endpoint.transport.send(request).await {
Ok(response) => response,
Expand Down
Loading
Loading