Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(local): isolate named-instance scenario seeding (#5071)

gbirman9914de220ba4
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 4492294b28..d5e97264a0 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -2480,8 +2480,6 @@
],
"fusionauth": [
"crates/fusionauth",
- "crates/macro_env",
- "crates/macro_env_var",
"crates/workspace-hack"
],
"github": [
diff --git a/Cargo.lock b/Cargo.lock
index f8cc42a589..fecd791f47 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5576,7 +5576,6 @@ version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
- "macro_env",
"reqwest 0.13.4",
"serde",
"serde_json",
diff --git a/crates/fusionauth/Cargo.toml b/crates/fusionauth/Cargo.toml
index a1f16fa4d6..89a09a5a7f 100644
--- a/crates/fusionauth/Cargo.toml
+++ b/crates/fusionauth/Cargo.toml
@@ -7,7 +7,6 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
base64 = { workspace = true }
-macro_env = { path = "../macro_env" }
reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/crates/fusionauth/src/lib.rs b/crates/fusionauth/src/lib.rs
index 5d48fc303d..a847952bc3 100644
--- a/crates/fusionauth/src/lib.rs
+++ b/crates/fusionauth/src/lib.rs
@@ -41,22 +41,11 @@ const FUSIONAUTH_TENANT_ID_HEADER: &str = "X-FusionAuth-TenantId";
impl AuthedClient {
/// Creates a new authenticated client with the given API key and tenant ID.
pub fn new(url: &str, api_key: String, tenant_id: String) -> Self {
- // Create authenticated client with default Authorization header
- let mut auth_headers = reqwest::header::HeaderMap::new();
- auth_headers.insert(reqwest::header::AUTHORIZATION, api_key.parse().unwrap());
-
- // NOTE: we only want to insert this header automatically if we are
- // using a local fusionauth instance
- // This is due to the local fusionauth instance containing 2 tenants
- if is_local_fusionauth(url) {
- // We need to insert the
- tracing::trace!(
- "inserting {} header into fusionauth authed client",
- FUSIONAUTH_TENANT_ID_HEADER
- );
- auth_headers.insert(FUSIONAUTH_TENANT_ID_HEADER, tenant_id.parse().unwrap());
- }
+ Self::with_tenant_header(api_key, tenant_id, should_infer_local_tenant_header(url))
+ }
+ fn with_tenant_header(api_key: String, tenant_id: String, include_tenant: bool) -> Self {
+ let auth_headers = auth_headers(api_key, tenant_id, include_tenant);
let client = reqwest::Client::builder()
.default_headers(auth_headers)
.build()
@@ -71,6 +60,25 @@ impl AuthedClient {
}
}
+fn auth_headers(
+ api_key: String,
+ tenant_id: String,
+ include_tenant: bool,
+) -> reqwest::header::HeaderMap {
+ let mut headers = reqwest::header::HeaderMap::new();
+ headers.insert(reqwest::header::AUTHORIZATION, api_key.parse().unwrap());
+
+ if include_tenant {
+ tracing::trace!(
+ "inserting {} header into fusionauth authed client",
+ FUSIONAUTH_TENANT_ID_HEADER
+ );
+ headers.insert(FUSIONAUTH_TENANT_ID_HEADER, tenant_id.parse().unwrap());
+ }
+
+ headers
+}
+
/// An HTTP client without authentication headers.
#[derive(Clone, Debug, Default)]
pub struct UnauthedClient {
@@ -98,6 +106,8 @@ pub struct FusionAuthClient {
client_secret: String,
/// The base url for the fusion auth api
fusion_auth_base_url: String,
+ /// The browser-reachable base URL used for OAuth authorization redirects.
+ fusion_auth_public_url: String,
/// The oauth redirect uri
oauth_redirect_uri: String,
/// The authenticated client with default Authorization header
@@ -123,13 +133,78 @@ impl FusionAuthClient {
google_client_id: String,
google_client_secret: String,
) -> Self {
- let auth_client = AuthedClient::new(&fusion_auth_base_url, api_key, tenant_id);
+ Self::new_inner(
+ tenant_id,
+ api_key,
+ client_id,
+ client_secret,
+ fusion_auth_base_url,
+ oauth_redirect_uri,
+ google_client_id,
+ google_client_secret,
+ false,
+ )
+ }
+
+ /// Creates a client for a local FusionAuth instance.
+ ///
+ /// Local FusionAuth contains multiple tenants, so this always sends the
+ /// tenant header instead of inferring locality from the host port.
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "matches the existing constructor"
+ )]
+ pub fn new_for_local_instance(
+ tenant_id: String,
+ api_key: String,
+ client_id: String,
+ client_secret: String,
+ fusion_auth_base_url: String,
+ oauth_redirect_uri: String,
+ google_client_id: String,
+ google_client_secret: String,
+ ) -> Self {
+ Self::new_inner(
+ tenant_id,
+ api_key,
+ client_id,
+ client_secret,
+ fusion_auth_base_url,
+ oauth_redirect_uri,
+ google_client_id,
+ google_client_secret,
+ true,
+ )
+ }
+
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "shared constructor implementation"
+ )]
+ fn new_inner(
+ tenant_id: String,
+ api_key: String,
+ client_id: String,
+ client_secret: String,
+ fusion_auth_base_url: String,
+ oauth_redirect_uri: String,
+ google_client_id: String,
+ google_client_secret: String,
+ force_tenant_header: bool,
+ ) -> Self {
+ let auth_client = if force_tenant_header {
+ AuthedClient::with_tenant_header(api_key, tenant_id, true)
+ } else {
+ AuthedClient::new(&fusion_auth_base_url, api_key, tenant_id)
+ };
let unauth_client = UnauthedClient::new();
+ let fusion_auth_public_url = fusion_auth_base_url.clone();
Self {
client_id,
client_secret,
fusion_auth_base_url,
+ fusion_auth_public_url,
oauth_redirect_uri,
auth_client,
unauth_client,
@@ -138,6 +213,13 @@ impl FusionAuthClient {
}
}
+ /// Sets the browser-reachable FusionAuth base URL used to construct OAuth
+ /// authorization redirects. API calls continue using the internal base URL.
+ pub fn with_public_url(mut self, fusion_auth_public_url: String) -> Self {
+ self.fusion_auth_public_url = fusion_auth_public_url;
+ self
+ }
+
/// Returns the Google OAuth client ID.
pub fn google_client_id(&self) -> &str {
&self.google_client_id
@@ -156,11 +238,8 @@ impl FusionAuthClient {
where
T: serde::Serialize + std::fmt::Debug + 'static,
{
- let mut url = Url::parse(&format!(
- "{}/oauth2/authorize",
- transform_fusionauth_url(&self.fusion_auth_base_url)
- ))
- .expect("Invalid base URL");
+ let mut url = Url::parse(&format!("{}/oauth2/authorize", self.fusion_auth_public_url))
+ .expect("Invalid base URL");
url.query_pairs_mut()
.append_pair("client_id", &self.client_id)
@@ -185,32 +264,13 @@ impl FusionAuthClient {
}
}
-/// Determines if fusionauth is local based on the url
+/// Preserves automatic tenant-header behavior for the default local endpoints.
+/// Named-instance clients opt into local tenant behavior explicitly instead of
+/// inferring service identity from a host port.
#[tracing::instrument(level = tracing::Level::TRACE)]
-fn is_local_fusionauth(url: &str) -> bool {
+fn should_infer_local_tenant_header(url: &str) -> bool {
url.starts_with("http://fusionauth:9011") || url.starts_with("http://localhost:9011")
}
-/// Transforms the url replacing the domain with localhost
-#[tracing::instrument(level = tracing::Level::TRACE)]
-fn transform_local_fusionauth_url(url: &str) -> String {
- if is_local_fusionauth(url) {
- url.replace("fusionauth", "localhost")
- } else {
- url.to_string()
- }
-}
-
-/// Transforms the fusionauth url from the docker-network version into the
-/// local version that will work in the browser.
-#[tracing::instrument(level = tracing::Level::TRACE)]
-fn transform_fusionauth_url(url: &str) -> String {
- // TODO: may want to make this something we initialize once
- match macro_env::Environment::new_or_prod() {
- macro_env::Environment::Local => transform_local_fusionauth_url(url),
- _ => url.to_string(),
- }
-}
-
#[cfg(test)]
mod test;
diff --git a/crates/fusionauth/src/test.rs b/crates/fusionauth/src/test.rs
index 0f19778be0..9104602aec 100644
--- a/crates/fusionauth/src/test.rs
+++ b/crates/fusionauth/src/test.rs
@@ -1,19 +1,44 @@
use super::*;
#[test]
-fn test_transform_local_fusionauth_url() {
- let urls = vec![
- (
- "http://fusionauth:9011/a/b/c/d",
- "http://localhost:9011/a/b/c/d",
- ),
- (
- "https://fusionauth-dev.macro.com",
- "https://fusionauth-dev.macro.com",
- ),
- ];
+fn oauth_authorize_url_uses_public_url() {
+ let client = FusionAuthClient::new(
+ "tenant-id".into(),
+ "api-key".into(),
+ "client-id".into(),
+ "client-secret".into(),
+ "http://fusionauth:9011".into(),
+ "http://localhost:28011/oauth/redirect".into(),
+ "google-client-id".into(),
+ "google-client-secret".into(),
+ )
+ .with_public_url("http://localhost:28005".into());
- for (value, expected) in urls.iter() {
- assert_eq!(&transform_local_fusionauth_url(value), expected);
- }
+ let url = client
+ .construct_oauth2_authorize_url::<()>("idp-id", None, None)
+ .unwrap();
+
+ assert!(url.starts_with("http://localhost:28005/oauth2/authorize?"));
+ assert!(!url.contains("fusionauth:9011"));
+}
+
+#[test]
+fn named_instance_ports_do_not_infer_the_tenant_header() {
+ assert!(should_infer_local_tenant_header("http://fusionauth:9011"));
+ assert!(should_infer_local_tenant_header("http://localhost:9011"));
+
+ assert!(!should_infer_local_tenant_header("http://localhost:28005"));
+ assert!(!should_infer_local_tenant_header("http://localhost:28006"));
+ assert!(!should_infer_local_tenant_header("http://localhost:28008"));
+ assert!(!should_infer_local_tenant_header("http://localhost:28009"));
+ assert!(!should_infer_local_tenant_header("http://localhost:28010"));
+}
+
+#[test]
+fn tenant_header_is_explicitly_configurable() {
+ let without_tenant = auth_headers("api-key".into(), "tenant-id".into(), false);
+ assert!(!without_tenant.contains_key(FUSIONAUTH_TENANT_ID_HEADER));
+
+ let with_tenant = auth_headers("api-key".into(), "tenant-id".into(), true);
+ assert_eq!(with_tenant[FUSIONAUTH_TENANT_ID_HEADER], "tenant-id");
}
diff --git a/justfile b/justfile
index 3e59bccd0f..b6c0be8333 100644
--- a/justfile
+++ b/justfile
@@ -55,12 +55,11 @@ local-e2e-seed:
# `just seed-scenario apply --file seed/scenarios/team-perms.json`.
# Add --force to drop and re-migrate the local database first (pristine world).
# `just seed-scenario status` reports what's applied and re-prints login links.
-# Set INSTANCE=<name> to target a `run_local --instance <name>` stack; it
-# resolves that instance's host ports for Postgres/FusionAuth/LocalStack/frontend.
-# Defaults to the `macro` instance (unchanged from the fixed local ports).
+# Pass `--instance <name>` before the scenario subcommand to target a named
+# `run_local` stack. Omitting it targets the default `macro` instance.
[positional-arguments]
seed-scenario *ARGS:
- @eval "$({{ xtask }} seed-env --instance "${INSTANCE:-macro}")" && just tooling/seed_cli/scenario "$@"
+ @{{ xtask }} seed-scenario "$@"
# Start only the services needed by the local E2E suites. Avoid unrelated
# local services with extra env/dependency requirements blocking E2E.
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index 3eb8cbccab..f24c837f12 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -35,6 +35,8 @@ env_vars! {
}
maybe_env_vars! {
+ /// Browser-reachable FusionAuth origin used for OAuth authorization redirects.
+ pub struct FusionAuthPublicUrl;
pub struct GaMeasurementId;
pub struct GaApiSecret;
pub struct MetaPixelId;
@@ -72,6 +74,8 @@ pub struct Config {
pub fusionauth_client_secret_key: FusionAuthClientSecretKey,
/// FusionAuth base url
pub fusionauth_base_url: FusionAuthBaseUrl,
+ /// Browser-reachable FusionAuth URL. Falls back to the API base URL when unset.
+ pub fusionauth_public_url: FusionAuthPublicUrl,
/// FusionAuth oauth redirect uri
pub fusionauth_oauth_redirect_uri: FusionAuthOauthRedirectUri,
/// Google client id
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index b7c3aab060..6ac384e6f4 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -147,6 +147,11 @@ async fn main() -> anyhow::Result<()> {
.to_string(),
};
+ let fusionauth_public_url = config
+ .fusionauth_public_url
+ .value()
+ .unwrap_or(config.fusionauth_base_url.as_ref())
+ .to_owned();
let auth_client = fusionauth::FusionAuthClient::new(
config.fusionauth_tenant_id.to_string(),
fusionauth_api_key,
@@ -156,7 +161,8 @@ async fn main() -> anyhow::Result<()> {
config.fusionauth_oauth_redirect_uri.to_string().clone(),
config.google_client_id.to_string().clone(),
google_client_secret,
- );
+ )
+ .with_public_url(fusionauth_public_url);
tracing::trace!("initialized auth client");
let document_storage_service_client = DocumentStorageServiceClient::new(
diff --git a/services/mcp_service/src/config.rs b/services/mcp_service/src/config.rs
index 68edc1875c..c5c6f99506 100644
--- a/services/mcp_service/src/config.rs
+++ b/services/mcp_service/src/config.rs
@@ -9,7 +9,12 @@ use anyhow::Context;
use database_env_vars::DatabaseUrl;
pub use macro_auth::InternalApiKey;
pub use macro_env::Environment;
-use macro_env_var::env_vars;
+use macro_env_var::{env_vars, maybe_env_vars};
+
+maybe_env_vars! {
+ /// Browser-reachable FusionAuth origin used for OAuth authorization redirects.
+ pub struct FusionauthPublicUrl;
+}
env_vars! {
/// Auth key used by the document storage / search / lexical clients.
@@ -78,6 +83,8 @@ pub struct Config {
DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
pub mcp_public_url: McpPublicUrl,
pub fusionauth_base_url: FusionauthBaseUrl,
+ /// Browser-reachable FusionAuth URL. Falls back to the API base URL when unset.
+ pub fusionauth_public_url: FusionauthPublicUrl,
pub fusionauth_client_id: FusionauthClientId,
pub fusionauth_tenant_id: FusionauthTenantId,
pub fusionauth_api_key_secret_key: FusionauthApiKeySecretKey,
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 1202b00ba3..199a76ad3b 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -373,6 +373,11 @@ async fn build_auth_proxy(
.await
.context("failed to load Google client secret")?;
+ let fusionauth_public_url = config
+ .fusionauth_public_url
+ .value()
+ .unwrap_or(config.fusionauth_base_url.as_ref())
+ .to_owned();
let fusionauth_client = fusionauth::FusionAuthClient::new(
config.fusionauth_tenant_id.as_ref().to_owned(),
fusionauth_api_key.as_ref().to_owned(),
@@ -382,7 +387,8 @@ async fn build_auth_proxy(
mcp_oauth_redirect_uri,
config.google_client_id.as_ref().to_owned(),
google_client_secret.as_ref().to_owned(),
- );
+ )
+ .with_public_url(fusionauth_public_url);
let auth_provider = FusionAuthOAuthProvider::new(fusionauth_client)
.await
diff --git a/tooling/seed_cli/README.md b/tooling/seed_cli/README.md
index 2e71d9a59f..8cd65b61f7 100644
--- a/tooling/seed_cli/README.md
+++ b/tooling/seed_cli/README.md
@@ -24,6 +24,9 @@ just seed-scenario apply --file seed/scenarios/team-perms.json
just seed-scenario matrix --file seed/scenarios/team-perms.json
just seed-scenario status --file seed/scenarios/team-perms.json # or no --file
just seed-scenario reset --file seed/scenarios/team-perms.json # or --all
+
+# Target a named `run_local --instance 2508` stack.
+just seed-scenario --instance 2508 apply --file seed/scenarios/team-perms.json
```
- `apply` deletes the scenario's own rows first and re-seeds, so it always
diff --git a/tooling/seed_cli/src/main.rs b/tooling/seed_cli/src/main.rs
index 3d68b8adc4..8ba06f6318 100644
--- a/tooling/seed_cli/src/main.rs
+++ b/tooling/seed_cli/src/main.rs
@@ -51,7 +51,7 @@ pub async fn main() -> anyhow::Result<()> {
.context("could not connect to db")?;
tracing::trace!("initialized db");
- let fusionauth_client = FusionAuthClient::new(
+ let fusionauth_client = FusionAuthClient::new_for_local_instance(
env_vars.fusionauth_tenant_id.to_string(),
env_vars.fusionauth_api_key_secret_key.to_string(),
env_vars.fusionauth_client_id.to_string(),
diff --git a/tooling/xtask/crates/xtask_local/src/local/cli.rs b/tooling/xtask/crates/xtask_local/src/local/cli.rs
index eeec6d6a8f..55d14e8c9d 100644
--- a/tooling/xtask/crates/xtask_local/src/local/cli.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/cli.rs
@@ -2,6 +2,7 @@
//! xtask verbs (deps/workflows/...) keep their slice-pattern match in main.rs;
//! everything else routes here.
+use std::ffi::OsString;
use std::path::PathBuf;
use anyhow::Result;
@@ -40,6 +41,8 @@ enum Cmd {
StatusLocal(InstanceArgs),
/// Emit host-facing connection env for seeding an instance (eval in a shell).
SeedEnv(InstanceArgs),
+ /// Run a seed scenario against an instance's host-facing endpoints.
+ SeedScenario(SeedScenarioArgs),
/// Stop an instance's containers (keep volumes).
StopLocal(InstanceArgs),
/// Drop, recreate, and migrate the instance database.
@@ -135,6 +138,16 @@ pub struct ForceArg {
pub force: bool,
}
+#[derive(Args, Clone)]
+#[command(trailing_var_arg = true)]
+pub struct SeedScenarioArgs {
+ #[command(flatten)]
+ pub instance: InstanceArgs,
+ /// Arguments forwarded to `seed_cli scenario`.
+ #[arg(required = true, allow_hyphen_values = true)]
+ pub scenario_args: Vec<OsString>,
+}
+
/// Parse and run a local-orchestration command, or fall back to the legacy
/// usage message on unknown input.
pub fn dispatch(raw: &[String], legacy_usage: &str) -> Result<()> {
@@ -188,6 +201,13 @@ fn run(cli: Cli) -> Result<()> {
let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;
super::seed_env::emit(&instance)
}
+ Cmd::SeedScenario(a) => {
+ let instance = super::instance::Instance::derive(
+ a.instance.instance.as_deref(),
+ a.instance.port_base,
+ )?;
+ super::seed_env::run_scenario(&instance, &a.scenario_args)
+ }
Cmd::StopLocal(a) => super::stop(&a),
Cmd::ResetLocal(a) => super::reset(&a),
Cmd::DestroyLocal(a) => super::destroy(&a),
diff --git a/tooling/xtask/crates/xtask_local/src/local/cli/test.rs b/tooling/xtask/crates/xtask_local/src/local/cli/test.rs
index a0049258d4..225380b960 100644
--- a/tooling/xtask/crates/xtask_local/src/local/cli/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/cli/test.rs
@@ -24,3 +24,26 @@ fn local_e2e_accepts_suite_and_trailing_test_arguments() {
["tests/e2e/local-smoke.spec.ts", "--grep", "channels"]
);
}
+
+#[test]
+fn seed_scenario_accepts_instance_and_trailing_scenario_arguments() {
+ let cli = Cli::try_parse_from([
+ "cargo-x",
+ "seed-scenario",
+ "--instance",
+ "2508",
+ "apply",
+ "--file",
+ "seed/scenarios/team-perms.json",
+ ])
+ .unwrap();
+
+ let Cmd::SeedScenario(args) = cli.command else {
+ panic!("expected seed-scenario command");
+ };
+ assert_eq!(args.instance.instance.as_deref(), Some("2508"));
+ assert_eq!(
+ args.scenario_args,
+ ["apply", "--file", "seed/scenarios/team-perms.json"]
+ );
+}
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
index f50fa0be1d..acb5dc1837 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
@@ -240,9 +240,10 @@ impl ServiceAuthEnv {
}
/// FusionAuth identity — all fixed UUIDs/secrets shared with the deterministic
-/// kickstart (see [`identity`]). The OAuth redirect is the only per-instance bit.
+/// kickstart (see [`identity`]). Browser-facing URLs are instance-specific.
struct FusionAuthEnv {
oauth_redirect_uri: String,
+ public_url: String,
/// The auth service's own public origin (`BASE_URL`): OAuth callbacks and
/// email verification links are built on it. Same host-port convention as
/// [`identity::oauth_redirect_uri`]. Doppler supplies it for dev; the
@@ -255,6 +256,7 @@ impl FusionAuthEnv {
fn for_instance(instance: &Instance) -> Self {
FusionAuthEnv {
oauth_redirect_uri: identity::oauth_redirect_uri(instance.port(Port::Auth)),
+ public_url: format!("http://localhost:{}", instance.port(Port::FusionAuth)),
base_url: format!("http://localhost:{}", instance.port(Port::Auth)),
}
}
@@ -265,6 +267,7 @@ impl FusionAuthEnv {
"FUSIONAUTH_BASE_URL".into(),
"http://fusionauth:9011".into(),
);
+ env.insert("FUSIONAUTH_PUBLIC_URL".into(), self.public_url.clone());
env.insert(
"FUSIONAUTH_API_KEY".into(),
identity::FUSIONAUTH_API_KEY.into(),
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
index d3aaa895e8..174b1d6caa 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
@@ -1,6 +1,6 @@
use super::*;
use crate::local::Mode;
-use crate::local::instance::Instance;
+use crate::local::instance::{Instance, Port};
fn local_env() -> BTreeMap<String, String> {
let instance = Instance::derive(None, None).expect("default instance derives");
@@ -28,6 +28,7 @@ fn emits_required_keys() {
"SMTP_HOST",
"INTERNAL_API_SECRET_KEY",
"FUSIONAUTH_API_KEY_SECRET_KEY",
+ "FUSIONAUTH_PUBLIC_URL",
"FUSIONAUTH_OAUTH_REDIRECT_URI",
"JWT_SECRET_KEY",
] {
@@ -97,3 +98,21 @@ fn instance_secrets_are_scoped_but_identity_is_fixed() {
"the fixed FusionAuth identity should be constant across instances"
);
}
+
+#[test]
+fn fusionauth_public_url_uses_the_instance_host_port() {
+ let default = Instance::derive(None, None).unwrap();
+ let named = Instance::derive(Some("2508"), None).unwrap();
+ let default_env = LocalEnv::for_instance(Mode::Local, &default).to_env();
+ let named_env = LocalEnv::for_instance(Mode::Local, &named).to_env();
+ let named_public_url = format!("http://localhost:{}", named.port(Port::FusionAuth));
+
+ assert_eq!(
+ default_env.get("FUSIONAUTH_PUBLIC_URL").map(String::as_str),
+ Some("http://localhost:9011")
+ );
+ assert_eq!(
+ named_env.get("FUSIONAUTH_PUBLIC_URL").map(String::as_str),
+ Some(named_public_url.as_str())
+ );
+}
diff --git a/tooling/xtask/crates/xtask_local/src/local/proxy.rs b/tooling/xtask/crates/xtask_local/src/local/proxy.rs
index 913acd0174..b809517aa6 100644
--- a/tooling/xtask/crates/xtask_local/src/local/proxy.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/proxy.rs
@@ -121,6 +121,9 @@ const SPECIAL_ROUTES: &str = r#" @websocket path /websocket /websocket/*
uri strip_prefix /sync
reverse_proxy sync-service:8787
}
+ handle_path /lexical/* {
+ reverse_proxy lexical-service:8096
+ }
"#;
const MAILPIT_ROUTE: &str = r#" # Mailpit serves itself under /mailpit (MP_WEBROOT), so no prefix strip —
diff --git a/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs b/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs
index ac4a2e9e55..d7917ca37d 100644
--- a/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs
@@ -35,6 +35,16 @@ fn websocket_services_use_a_matcher() {
assert!(caddy.contains("handle_path /auth/* {"));
}
+#[test]
+fn document_content_services_are_available_through_the_proxy() {
+ let caddy = caddyfile(Mode::Local, false);
+
+ assert!(caddy.contains("uri strip_prefix /sync"));
+ assert!(caddy.contains("reverse_proxy sync-service:8787"));
+ assert!(caddy.contains("handle_path /lexical/*"));
+ assert!(caddy.contains("reverse_proxy lexical-service:8096"));
+}
+
/// The static-file block is the one route that differs by mode: LocalStack S3
/// fan-out locally, the dev-pointed service in dev.
#[test]
diff --git a/tooling/xtask/crates/xtask_local/src/local/seed_env.rs b/tooling/xtask/crates/xtask_local/src/local/seed_env.rs
index 1491caba38..61b7fbd980 100644
--- a/tooling/xtask/crates/xtask_local/src/local/seed_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/seed_env.rs
@@ -2,20 +2,22 @@
//!
//! Dockerized services reach each other over the compose network
//! (`postgres:5432`, `fusionauth:9011`, ...), but the seed CLI runs on the host
-//! and needs `localhost:<host-port>`. This prints `eval`-able shell exports so
-//! `just seed-scenario` can target a `run_local --instance <name>` stack. Each
-//! export preserves a value already in the environment (`${VAR:-...}`), so
-//! explicit overrides still win and the default instance reproduces the
+//! and needs `localhost:<host-port>`. This owns the environment used by both
+//! `seed-env` and `seed-scenario`, so instance endpoint resolution cannot drift.
+//! Each export preserves a value already in the environment (`${VAR:-...}`),
+//! so explicit overrides still win and the default instance reproduces the
//! recipe's historical fixed-port defaults exactly.
//!
-//! Sync-service and lexical-service are not instance-isolated (their compose
-//! ports are hardcoded to 8787/8096), so document content is left to the seed
-//! recipe's shared defaults rather than emitted here.
+//! Sync-service and lexical-service do not publish host ports for named
+//! instances, so their host-facing URLs go through the instance proxy.
#[cfg(test)]
mod test;
-use anyhow::Result;
+use std::ffi::OsString;
+use std::process::Command;
+
+use anyhow::{Context, Result, ensure};
use super::instance::{Instance, Port};
@@ -26,25 +28,62 @@ pub fn emit(instance: &Instance) -> Result<()> {
Ok(())
}
+/// Run `seed_cli scenario` with host-facing defaults for `instance`.
+pub fn run_scenario(instance: &Instance, scenario_args: &[OsString]) -> Result<()> {
+ let mut cmd = Command::new("just");
+ cmd.current_dir(super::repo_root())
+ .arg("tooling/seed_cli/scenario")
+ .args(scenario_args);
+ for (key, value) in values(instance) {
+ cmd.env(key, value);
+ }
+ let status = cmd.status().context("running seed_cli scenario")?;
+ ensure!(status.success(), "seed_cli scenario exited with {status}");
+ Ok(())
+}
+
/// The `eval`-able export block for the instance's host-facing endpoints. Each
/// line preserves any value already in the environment so explicit overrides
/// win and the default instance reproduces the recipe's fixed-port defaults.
fn render(instance: &Instance) -> String {
+ values(instance)
+ .into_iter()
+ .map(|(key, value)| format!(r#"export {key}="${{{key}:-{value}}}""#))
+ .collect::<Vec<_>>()
+ .join("\n")
+ + "\n"
+}
+
+fn values(instance: &Instance) -> Vec<(&'static str, String)> {
let postgres = instance.port(Port::Postgres);
let localstack = instance.port(Port::LocalStack);
let fusionauth = instance.port(Port::FusionAuth);
let frontend = instance.port(Port::Frontend);
+ let (sync_service_url, lexical_service_url) = if instance.is_default() {
+ (
+ "http://localhost:8787".to_string(),
+ "http://localhost:8096".to_string(),
+ )
+ } else {
+ let proxy = instance.port(Port::Proxy);
+ (
+ format!("http://localhost:{proxy}/sync"),
+ format!("http://localhost:{proxy}/lexical"),
+ )
+ };
- [
- format!(
- r#"export DATABASE_URL="${{DATABASE_URL:-postgres://user:password@localhost:{postgres}/macrodb}}""#
+ vec![
+ (
+ "DATABASE_URL",
+ format!("postgres://user:password@localhost:{postgres}/macrodb"),
),
- format!(r#"export LOCAL_AWS_URL="${{LOCAL_AWS_URL:-http://localhost:{localstack}}}""#),
- format!(
- r#"export FUSIONAUTH_BASE_URL="${{FUSIONAUTH_BASE_URL:-http://localhost:{fusionauth}}}""#
+ ("LOCAL_AWS_URL", format!("http://localhost:{localstack}")),
+ (
+ "FUSIONAUTH_BASE_URL",
+ format!("http://localhost:{fusionauth}"),
),
- format!(r#"export FRONTEND_PORT="${{FRONTEND_PORT:-{frontend}}}""#),
+ ("FRONTEND_PORT", frontend.to_string()),
+ ("SYNC_SERVICE_URL", sync_service_url),
+ ("LEXICAL_SERVICE_URL", lexical_service_url),
]
- .join("\n")
- + "\n"
}
diff --git a/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs
index 7e443bed9d..1ea76002ca 100644
--- a/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs
@@ -24,6 +24,17 @@ fn default_instance_reproduces_the_fixed_ports() {
rendered.contains(r#"export FRONTEND_PORT="${FRONTEND_PORT:-3000}""#),
"{rendered}"
);
+ assert!(
+ rendered
+ .contains(r#"export SYNC_SERVICE_URL="${SYNC_SERVICE_URL:-http://localhost:8787}""#),
+ "{rendered}"
+ );
+ assert!(
+ rendered.contains(
+ r#"export LEXICAL_SERVICE_URL="${LEXICAL_SERVICE_URL:-http://localhost:8096}""#
+ ),
+ "{rendered}"
+ );
}
#[test]
@@ -40,6 +51,15 @@ fn named_instance_shifts_into_its_port_window() {
assert_eq!(instance.port(Port::Postgres), base);
assert!(instance.port(Port::FusionAuth) > base);
assert_ne!(instance.port(Port::FusionAuth), 9011);
+ let proxy = instance.port(Port::Proxy);
+ assert!(
+ render(&instance).contains(&format!("http://localhost:{proxy}/sync")),
+ "sync-service should use the named instance proxy"
+ );
+ assert!(
+ render(&instance).contains(&format!("http://localhost:{proxy}/lexical")),
+ "lexical-service should use the named instance proxy"
+ );
}
#[test]
diff --git a/tooling/xtask/crates/xtask_local/src/local/validate.rs b/tooling/xtask/crates/xtask_local/src/local/validate.rs
index eb38524562..fba7aad92a 100644
--- a/tooling/xtask/crates/xtask_local/src/local/validate.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/validate.rs
@@ -134,6 +134,7 @@ pub fn local_env(
"REDIS_URI",
"LOCAL_AWS_URL",
"FUSIONAUTH_BASE_URL",
+ "FUSIONAUTH_PUBLIC_URL",
"FUSIONAUTH_CLIENT_ID",
"JWT_SECRET_KEY",
"DOCUMENT_STORAGE_BUCKET",