#[path = "../common/mod.rs"]
mod common;
use common::run_lua;
use serde_json::json;
use wiremock::matchers::{body_string_contains, header, headers, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
const WS: &str = "wks_xa1";
fn client(product: &str, uri: &str) -> String {
format!(
"local f = require(\"assay.forge\")\n\
local c = f.{product}({{ api_key = \"k\", workspace_id = \"{WS}\", base_url = \"{uri}\" }})\n"
)
}
fn reply(payload: serde_json::Value) -> ResponseTemplate {
ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": { "content": [{ "type": "text", "text": payload.to_string() }] },
}))
}
async fn mount_tool(server: &MockServer, key_header: &str, tool: &str, payload: serde_json::Value) {
Mock::given(method("POST"))
.and(path("/"))
.and(header(key_header, "k"))
.and(headers(
"accept",
vec!["application/json", "text/event-stream"],
))
.and(header("content-type", "application/json"))
.and(body_string_contains(tool))
.respond_with(reply(payload))
.mount(server)
.await;
}
fn warmforge_row() -> serde_json::Value {
json!({
"id": "mbx_xa1", "address": "ada@example.test", "status": "active",
"provider": "smtp", "warm": false, "warmupEnabled": true,
"warmupDaysCompleted": 9, "warmupDaysLeft": 5,
"healthReport": {
"address": "ada@example.test", "domain": "example.test", "id": "mbx_xa1",
"heatScore": 82, "warmupDays": 9, "lastCheckedAt": "2026-09-04T01:08:08Z",
"spf": { "status": "valid", "value": "v=spf1 include:_spf.example.test ~all" },
"dkim": { "status": "valid", "selector": "google" },
"mx": { "status": "invalid", "value": "" },
"blacklists": {
"detectedCount": 1,
"checks": [
{ "id": "clean.example.test", "name": "Clean", "detected": false },
{ "id": "listed.example.test", "name": "Listed", "detected": true },
],
},
},
})
}
#[tokio::test]
async fn test_a_primeforge_domain_name_is_sld_and_tld_joined() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Primeforge-Key",
"primeforge_list_domains",
json!({
"pagination": { "limit": 10, "offset": 0 },
"results": [
{ "id": "dom_xa1", "sld": "Example", "tld": "TEST", "status": "active" },
{ "id": "dom_xa2", "status": "active" },
],
}),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local rows = c:domains()
assert.eq(#rows, 1)
assert.eq(rows[1].domain, "example.test")
assert.eq(rows[1].provider, "primeforge")
assert.eq(rows[1].provider_ref, "dom_xa1")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_primeforge_filters_mailboxes_by_domain_without_sending_a_filter() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Primeforge-Key",
"primeforge_list_mailboxes",
json!({ "results": [
{ "id": "mbx_xa1", "address": "Ada@Example.TEST", "status": "ACTIVE",
"domainId": "dom_xa1", "password": "hunter2", "appPassword": "abcd efgh" },
{ "id": "mbx_xa2", "address": "bo@other.test", "status": "active",
"domainId": "dom_xa2" },
] }),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
assert.eq(#c:mailboxes(), 2)
local rows, meta = c:mailboxes("dom_xa1")
assert.eq(#rows, 1)
assert.eq(rows[1].address, "ada@example.test")
assert.eq(rows[1].domain, "example.test")
assert.eq(rows[1].raw.password, "[redacted]")
assert.eq(rows[1].raw.appPassword, "[redacted]")
-- Two rows is under the cap, so this window really is everything.
assert.eq(meta.truncated, false)
assert.eq(meta.cap, 10)
assert.eq(meta.seen, 2)
"#
))
.await
.unwrap();
let sent = &server.received_requests().await.unwrap()[0];
let body = String::from_utf8(sent.body.clone()).unwrap();
assert!(body.contains(WS), "workspace not sent: {body}");
assert!(
!body.contains("limit"),
"sent a paging argument the tool ignores: {body}"
);
assert!(
!body.contains("domainId"),
"sent a filter the tool does not accept: {body}"
);
}
#[tokio::test]
async fn test_each_product_sends_its_own_key_header() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Warmforge-Key",
"warmforge_list_mailboxes",
json!({ "mailboxes": [warmforge_row()], "page": 1, "pageSize": 50, "totalPages": 1 }),
)
.await;
run_lua(&format!(
"{}{}",
client("warmforge", &server.uri()),
r#"
local rows = c:mailboxes()
assert.eq(#rows, 1)
assert.eq(rows[1].address, "ada@example.test")
assert.eq(rows[1].provider, "warmforge")
assert.eq(rows[1].provider_ref, "mbx_xa1")
"#
))
.await
.unwrap();
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local rows, err = c:mailboxes()
assert.eq(rows, nil)
assert.eq(err.code, "http")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_the_health_report_is_tri_state_and_an_omitted_check_is_unknown() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Warmforge-Key",
"warmforge_list_mailboxes",
json!({ "mailboxes": [warmforge_row()], "totalPages": 1 }),
)
.await;
run_lua(&format!(
"{}{}",
client("warmforge", &server.uri()),
r#"
local h = c:health("ADA@example.test")
assert.eq(h.spf, "valid")
assert.eq(h.dkim, "valid")
assert.eq(h.mx, "invalid")
-- The row carries no dmarc at all. It is not a failing DMARC.
assert.eq(h.dmarc, "unknown")
assert.eq(h.heat, 82)
assert.eq(h.blacklists.detected, 1)
assert.eq(h.blacklists.lists[1], "listed.example.test")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_warmup_day_and_total_come_off_the_two_halves_of_the_curve() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Warmforge-Key",
"warmforge_list_mailboxes",
json!({ "mailboxes": [warmforge_row()], "totalPages": 1 }),
)
.await;
run_lua(&format!(
"{}{}",
client("warmforge", &server.uri()),
r#"
local w = c:warmup("ada@example.test")
assert.eq(w.day, 9)
assert.eq(w.total_days, 14)
assert.eq(w.heat, 82)
assert.eq(w.enabled, true)
local missing, err = c:warmup("nobody@example.test")
assert.eq(missing, nil)
assert.eq(err.code, "not_found")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_a_heat_score_outside_the_scale_is_not_a_reading() {
run_lua(
r#"
local f = require("assay.forge")
assert.eq(f.heat(82), 82)
assert.eq(f.heat(140), nil)
assert.eq(f.heat(-1), nil)
assert.eq(f.heat("hot"), nil)
"#,
)
.await
.unwrap();
}
#[tokio::test]
async fn test_a_placement_row_with_no_counts_is_no_test_not_a_zero() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Warmforge-Key",
"warmforge_list_mailboxes",
json!({ "mailboxes": [warmforge_row()], "totalPages": 1 }),
)
.await;
mount_tool(
&server,
"X-Warmforge-Key",
"warmforge_get_latest_mailbox_placement_results",
json!({ "results": [
{ "address": "ada@example.test", "mailboxId": "mbx_xa1", "provider": "smtp" },
] }),
)
.await;
run_lua(&format!(
"{}{}",
client("warmforge", &server.uri()),
r#"
local p, err = c:placement("ada@example.test")
assert.eq(p, nil)
assert.eq(err, nil)
local f = require("assay.forge")
assert.eq(f.placement(80, 15, 5).inbox, 0.8)
assert.eq(f.placement(0.8, 0.15, 0.05).spam, 0.15)
assert.eq(f.placement(0, 0, 0), nil)
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_warmforge_pages_to_total_pages() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(body_string_contains("\"page\":1"))
.respond_with(reply(json!({
"mailboxes": [{ "id": "mbx_xp1", "address": "one@example.test" }],
"page": 1, "pageSize": 50, "totalPages": 2,
})))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(body_string_contains("\"page\":2"))
.respond_with(reply(json!({
"mailboxes": [{ "id": "mbx_xp2", "address": "two@example.test" }],
"page": 2, "pageSize": 50, "totalPages": 2,
})))
.mount(&server)
.await;
run_lua(&format!(
"{}{}",
client("warmforge", &server.uri()),
r#"
local rows = c:mailboxes()
assert.eq(#rows, 2)
assert.eq(rows[2].address, "two@example.test")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_the_reply_frame_is_chosen_by_its_json_rpc_id() {
let server = MockServer::start().await;
let answer = json!({ "results": [{ "id": "dom_xa1", "sld": "example", "tld": "test" }] });
let stream = format!(
"event: message\ndata: {}\n\nevent: message\ndata: {}\n\n",
json!({ "jsonrpc": "2.0", "id": 1,
"result": { "content": [{ "text": answer.to_string() }] } }),
json!({ "jsonrpc": "2.0", "method": "notifications/progress", "params": {} }),
);
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200).set_body_raw(stream, "text/event-stream"))
.mount(&server)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local rows = c:domains()
assert.eq(#rows, 1)
assert.eq(rows[1].domain, "example.test")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_auth_and_rate_limits_read_as_themselves_not_as_absence() {
for (status, code) in [
(401u16, "auth"),
(403, "auth"),
(429, "rate_limit"),
(502, "server"),
] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(status))
.mount(&server)
.await;
let check = format!(
r#"
local rows, err = c:domains()
assert.eq(rows, nil)
assert.eq(err.code, "{code}")
assert.eq(err.status, {status})
assert.contains(tostring(err), "forge: ")
"#
);
run_lua(&format!("{}{check}", client("primeforge", &server.uri())))
.await
.unwrap();
}
}
#[tokio::test]
async fn test_a_tool_error_reads_as_a_tool_error() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0", "id": 1,
"error": { "code": -32602, "message": "unknown workspace" },
})))
.mount(&server)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local rows, err = c:domains()
assert.eq(rows, nil)
assert.eq(err.code, "tool")
assert.contains(err.message, "unknown workspace")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_a_client_refuses_to_build_without_a_key_or_a_workspace() {
for args in [r#"{ workspace_id = "wks_xa1" }"#, r#"{ api_key = "k" }"#] {
let err = run_lua(&format!(
"local f = require(\"assay.forge\")\nf.primeforge({args})"
))
.await
.unwrap_err()
.to_string();
assert!(err.contains("required"), "gave {err}");
}
run_lua(
r#"
local f = require("assay.forge")
local payload, err = f.mcp("nopeforge", "k", "any_tool")
assert.eq(payload, nil)
assert.eq(err.code, "product")
"#,
)
.await
.unwrap();
}
#[tokio::test]
async fn test_a_full_primeforge_window_reports_itself_as_truncated() {
let server = MockServer::start().await;
let ten: Vec<serde_json::Value> = (0..10)
.map(|n| {
json!({ "id": format!("mbx_x{n}"), "address": format!("p{n}@example.test"),
"domainId": "dom_xa1", "status": "active" })
})
.collect();
mount_tool(
&server,
"X-Primeforge-Key",
"primeforge_list_mailboxes",
json!({ "results": ten, "pagination": { "limit": 10, "offset": 0 } }),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local rows, meta = c:mailboxes()
assert.eq(#rows, 10)
assert.eq(meta.truncated, true)
assert.eq(meta.cap, 10)
assert.eq(meta.seen, 10)
-- The silent case the signal exists for: a domain with no rows in this
-- window looks identical to a domain with no mailboxes at all.
local none, none_meta = c:mailboxes("dom_elsewhere")
assert.eq(#none, 0)
assert.eq(none_meta.truncated, true)
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_a_short_primeforge_domain_list_is_not_truncated() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Primeforge-Key",
"primeforge_list_domains",
json!({ "results": [{ "id": "dom_xa1", "sld": "example", "tld": "test" }] }),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local rows, meta = c:domains()
assert.eq(#rows, 1)
assert.eq(meta.truncated, false)
assert.eq(meta.seen, 1)
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_a_miss_inside_a_truncated_window_says_so() {
let server = MockServer::start().await;
let full: Vec<serde_json::Value> = (0..50)
.map(|n| json!({ "id": format!("mbx_x{n}"), "address": format!("p{n}@example.test") }))
.collect();
Mock::given(method("POST"))
.respond_with(reply(json!({ "mailboxes": full })))
.mount(&server)
.await;
run_lua(&format!(
"{}{}",
client("warmforge", &server.uri()),
r#"
local rows, meta = c:mailboxes()
assert.eq(meta.truncated, true)
assert.eq(meta.cap, 2500)
local missing, err = c:warmup("nobody@example.test")
assert.eq(missing, nil)
assert.eq(err.code, "not_found")
assert.contains(err.message, "truncated")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_a_warmforge_walk_that_reaches_total_pages_is_not_truncated() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Warmforge-Key",
"warmforge_list_mailboxes",
json!({ "mailboxes": [warmforge_row()], "page": 1, "pageSize": 50, "totalPages": 1 }),
)
.await;
run_lua(&format!(
"{}{}",
client("warmforge", &server.uri()),
r#"
local rows, meta = c:mailboxes()
assert.eq(#rows, 1)
assert.eq(meta.truncated, false)
assert.eq(meta.seen, 1)
"#
))
.await
.unwrap();
}
fn quote_row(name: &str, price: serde_json::Value, available: bool) -> serde_json::Value {
json!({
"name": name, "price": price, "available": available, "is_premium": false,
"banned": false, "google_workspace_available": true, "ms365_workspace_available": false,
})
}
#[tokio::test]
async fn test_a_domain_quote_prices_a_year_in_whole_cents() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Primeforge-Key",
"primeforge_search_domains",
json!({ "domains": [
quote_row("example.test", json!(14), true),
quote_row("tryexample.test", json!(19.99), true),
] }),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local out = c:domain_price("Example.TEST")
assert.eq(#out.items, 2)
assert.eq(out.items[1].kind, "domain")
assert.eq(out.items[1].unit, "domain")
assert.eq(out.items[1].ref, "example.test")
assert.eq(out.items[1].quantity, 1)
assert.eq(out.items[1].unit_price_cents, 1400)
assert.eq(out.items[1].period, "year")
assert.eq(out.items[1].source, "vendor")
assert.eq(out.items[2].ref, "tryexample.test")
assert.eq(out.items[2].unit_price_cents, 1999)
-- The vendor states no currency beside the number.
assert.eq(out.items[1].currency, nil)
assert.eq(out.meta.currency_known, false)
assert.eq(out.meta.priced, true)
assert.eq(out.meta.seen, 2)
assert.eq(out.meta.unavailable, 0)
assert.eq(out.meta.unpriced, 0)
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_a_domain_nobody_can_buy_is_counted_rather_than_priced() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Primeforge-Key",
"primeforge_search_domains",
json!({ "domains": [
quote_row("taken.test", json!(14), false),
quote_row("free.test", json!(14), true),
] }),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local out = c:domain_price("taken.test")
assert.eq(#out.items, 1)
assert.eq(out.items[1].ref, "free.test")
assert.eq(out.meta.seen, 2)
assert.eq(out.meta.unavailable, 1)
assert.eq(out.meta.unpriced, 0)
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_an_available_domain_with_no_readable_price_is_unpriced_not_unavailable() {
let server = MockServer::start().await;
mount_tool(
&server,
"X-Primeforge-Key",
"primeforge_search_domains",
json!({ "domains": [
quote_row("free.test", serde_json::Value::Null, true),
quote_row("hex.test", json!("0x10"), true),
quote_row("taken.test", json!(14), false),
] }),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local out = c:domain_price("free.test")
assert.eq(#out.items, 0)
assert.eq(out.meta.seen, 3)
assert.eq(out.meta.unavailable, 1)
assert.eq(out.meta.unpriced, 2)
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_a_refused_quote_reads_as_an_error_not_as_a_free_domain() {
for (status, code) in [(401u16, "auth"), (429, "rate_limit"), (500, "server")] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/"))
.respond_with(ResponseTemplate::new(status))
.mount(&server)
.await;
let body = format!(
r#"
local out, err = c:domain_price("example.test")
assert.eq(out, nil)
assert.eq(err.code, "{code}")
assert.eq(err.status, {status})
"#
);
run_lua(&format!("{}{}", client("primeforge", &server.uri()), body))
.await
.unwrap();
}
}
#[tokio::test]
async fn test_a_quote_without_a_domain_is_refused_before_the_call() {
let server = MockServer::start().await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local out, err = c:domain_price("")
assert.eq(out, nil)
assert.eq(err.code, "config")
"#
))
.await
.unwrap();
assert!(
server.received_requests().await.unwrap().is_empty(),
"an empty domain reached the vendor"
);
}
#[tokio::test]
async fn test_a_full_address_as_a_username_is_refused_rather_than_stored_doubled() {
let server = MockServer::start().await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local _, err = c:create_mailboxes("dom_x1", {
{ username = "ada@brand.test", first_name = "Ada", last_name = "Lovelace" },
})
assert.eq(err.code, "config")
assert.contains(err.message, "local part")
"#
))
.await
.unwrap();
assert!(server.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn test_creating_mailboxes_sends_the_vendors_field_names_and_the_local_part() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/"))
.and(header("x-primeforge-key", "k"))
.and(body_string_contains("primeforge_create_mailboxes_for_domain"))
.and(body_string_contains("\"username\":\"ada\""))
.and(body_string_contains("\"firstName\":\"Ada\""))
.and(body_string_contains("\"signature\":\"Ada Lovelace\""))
.and(body_string_contains("\"domainId\":\"dom_x1\""))
.respond_with(reply(json!({ "created": 1 })))
.mount(&server)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local made = c:create_mailboxes("dom_x1", {
{ username = "Ada", first_name = "Ada", last_name = "Lovelace" },
})
assert.eq(made.created, 1)
local _, no_name = c:create_mailboxes("dom_x1", { { username = "ceo" } })
assert.eq(no_name.code, "config")
local _, none = c:create_mailboxes("dom_x1", {})
assert.eq(none.code, "config")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_buying_a_domain_refuses_an_incomplete_registrant_before_charging() {
let server = MockServer::start().await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local _, no_contact = c:buy_domain("brand.test")
assert.eq(no_contact.code, "config")
local _, partial = c:buy_domain("brand.test", { firstName = "Ada", lastName = "L" })
assert.eq(partial.code, "config")
assert.contains(partial.message, "email")
local _, no_domain = c:buy_domain("", { firstName = "Ada" })
assert.eq(no_domain.code, "config")
"#
))
.await
.unwrap();
assert!(server.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn test_buying_a_domain_sends_the_domain_and_the_whole_contact() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/"))
.and(body_string_contains("primeforge_buy_domains"))
.and(body_string_contains("\"brand.test\""))
.and(body_string_contains("\"country\":\"GB\""))
.respond_with(reply(json!({ "ok": true })))
.mount(&server)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local bought = c:buy_domain("Brand.TEST", {
firstName = "Ada", lastName = "Lovelace", email = "ada@brand.test",
phone = "+44.2000000000", address = "1 Road", city = "London",
state = "London", zip = "E1 1AA", country = "GB",
})
assert.eq(bought.domain, "brand.test")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_an_app_password_the_vendor_does_not_have_yet_is_not_an_empty_password() {
let server = MockServer::start().await;
mount_tool(
&server,
"x-primeforge-key",
"primeforge_get_mailbox",
json!({ "id": "mbx_x1", "status": "provisioning", "appPassword": "" }),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
local password, err = c:app_password("mbx_x1")
assert.eq(password, nil)
assert.eq(err.code, "not_ready")
"#
))
.await
.unwrap();
}
#[tokio::test]
async fn test_an_app_password_the_vendor_has_comes_back_on_its_own() {
let server = MockServer::start().await;
mount_tool(
&server,
"x-primeforge-key",
"primeforge_get_mailbox",
json!({ "id": "mbx_x1", "status": "active", "appPassword": "abcd efgh ijkl mnop" }),
)
.await;
run_lua(&format!(
"{}{}",
client("primeforge", &server.uri()),
r#"
assert.eq(c:app_password("mbx_x1"), "abcd efgh ijkl mnop")
local _, blank = c:app_password(" ")
assert.eq(blank.code, "config")
"#
))
.await
.unwrap();
}