434 lines
16 KiB
TypeScript
434 lines
16 KiB
TypeScript
/**
|
||
* ISO-01..08 — cross-cutting region/tenant isolation (catalogue §11.1).
|
||
*
|
||
* Region A is the seeded region 1 (staff `e2e_staff`). Region B is a brand-new
|
||
* region created with `superadmin.regions.create` plus its own staff, so it owns
|
||
* no pre-existing data and every foreign-id assertion is unambiguous.
|
||
*
|
||
* Global writes (global product/store create) are deliberately NOT performed:
|
||
* they OOM this seeded workerd (see cache-invariants). ISO-06 reads an existing
|
||
* seeded global product/store instead.
|
||
*
|
||
* Rows pinned `(current)`:
|
||
* - ISO-02: `user.product.getProductDetails` rejects a foreign-region SKU with a
|
||
* raw `Error('Product not found')` -> INTERNAL_SERVER_ERROR, not 404.
|
||
* - ISO-05: the notif-cred region is not exposed by any procedure; only the
|
||
* address-region association is observable.
|
||
*/
|
||
|
||
import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
|
||
import { staffClient, superadminClient } from '../helpers/sessions'
|
||
import {
|
||
PASSWORD,
|
||
createAddress,
|
||
createCoupon,
|
||
createFutureSlot,
|
||
createProduct,
|
||
createRegion,
|
||
createStore,
|
||
placeOrder,
|
||
registerThrowawayUser,
|
||
} from '../helpers/fixtures'
|
||
import {
|
||
getEssentialConsts,
|
||
scaffoldCache,
|
||
type EssentialConsts,
|
||
} from '../helpers/cache'
|
||
import { TEST_BOUND_ID, TEST_REGION_ID } from '../helpers/env'
|
||
|
||
jest.setTimeout(300_000)
|
||
|
||
const REGION_A = TEST_REGION_ID
|
||
const BOUND_A = TEST_BOUND_ID
|
||
|
||
interface RegionB {
|
||
regionId: number
|
||
boundId: number
|
||
client: ApiClient
|
||
storeId: number
|
||
productId: number
|
||
skuId: number
|
||
}
|
||
|
||
interface RegionAFixture {
|
||
admin: ApiClient
|
||
storeId: number
|
||
productId: number
|
||
skuId: number
|
||
slotId: number
|
||
tagId: number
|
||
bannerId: number
|
||
couponId: number
|
||
couponCode: string
|
||
snippetId: number
|
||
snippetCode: string
|
||
userToken: string
|
||
userMobile: string
|
||
userId: number
|
||
orderId: number
|
||
}
|
||
|
||
/** Create one product for an arbitrary region client. */
|
||
async function createProductVia(
|
||
client: ApiClient,
|
||
storeId: number,
|
||
name: string,
|
||
price: number
|
||
): Promise<{ productId: number; skuId: number }> {
|
||
const res: any = await client.admin.product.createProduct.mutate({
|
||
name,
|
||
shortDescription: 'iso fixture',
|
||
storeId,
|
||
productType: 'item',
|
||
skus: [
|
||
{
|
||
name: '1pc',
|
||
price,
|
||
marketPrice: price + 50,
|
||
images: [],
|
||
isFlashAvailable: false,
|
||
flashPrice: null,
|
||
isOutOfStock: false,
|
||
isOffer: false,
|
||
isComboOnly: false,
|
||
isSuspended: false,
|
||
features: [{ featureName: 'quantity', featureValue: '1pc' }],
|
||
},
|
||
],
|
||
})
|
||
return { productId: Number(res.product.id), skuId: Number(res.product.skus[0].id) }
|
||
}
|
||
|
||
let regionA: RegionAFixture
|
||
let regionB: RegionB
|
||
|
||
beforeAll(async () => {
|
||
const admin = await staffClient()
|
||
const sa = await superadminClient()
|
||
|
||
// --- Region B + its own staff -------------------------------------------------
|
||
const createdRegion = await createRegion()
|
||
const roles: any = await sa.superadmin.staff.roles.query()
|
||
const roleId = Number(roles.roles.find((r: any) => r.name === 'admin')?.id ?? roles.roles[0].id)
|
||
const bStaffName = `e2e_iso_${uniqueSuffix().replace(/[^a-z0-9]/gi, '')}`
|
||
await sa.superadmin.staff.create.mutate({
|
||
name: bStaffName,
|
||
password: PASSWORD,
|
||
roleId,
|
||
regionId: createdRegion.regionId,
|
||
})
|
||
const bLogin: any = await apiClient().admin.staffUser.login.mutate({
|
||
name: bStaffName,
|
||
password: PASSWORD,
|
||
})
|
||
const bClient = apiClient(bLogin.token)
|
||
|
||
const bStore: any = await bClient.admin.store.createStore.mutate({
|
||
name: `E2E ISO-B Store ${uniqueSuffix()}`,
|
||
})
|
||
const bProduct = await createProductVia(
|
||
bClient,
|
||
Number(bStore.store.id),
|
||
`E2E ISO-B Product ${uniqueSuffix()}`,
|
||
321
|
||
)
|
||
|
||
regionB = {
|
||
regionId: createdRegion.regionId,
|
||
boundId: Number(createdRegion.boundId),
|
||
client: bClient,
|
||
storeId: Number(bStore.store.id),
|
||
productId: bProduct.productId,
|
||
skuId: bProduct.skuId,
|
||
}
|
||
|
||
// --- Region A (seeded region 1) fixture --------------------------------------
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId, price: 199 })
|
||
const slot = await createFutureSlot([product.skuId])
|
||
|
||
const tag: any = await admin.admin.product.createProductTag.mutate({
|
||
tagName: `E2E ISO Tag ${uniqueSuffix()}`,
|
||
})
|
||
const banner: any = await admin.admin.banner.createBanner.mutate({
|
||
name: `E2E ISO Banner ${uniqueSuffix()}`,
|
||
imageUrl: `https://assets2.freshyo.in/home-banners/iso-${uniqueSuffix()}.png`,
|
||
})
|
||
const coupon = await createCoupon()
|
||
const snippet: any = await admin.admin.vendorSnippets.create.mutate({
|
||
snippetCode: `ISO${uniqueSuffix().replace(/[^a-z0-9]/gi, '').toUpperCase()}`,
|
||
slotId: slot.slotId,
|
||
skuIds: [product.skuId],
|
||
isPermanent: true,
|
||
})
|
||
|
||
const user = await registerThrowawayUser()
|
||
const address = await createAddress(user.token)
|
||
const orders = await placeOrder(user.token, {
|
||
addressId: address.id,
|
||
skuId: product.skuId,
|
||
slotId: slot.slotId,
|
||
})
|
||
|
||
regionA = {
|
||
admin,
|
||
storeId: store.storeId,
|
||
productId: product.productId,
|
||
skuId: product.skuId,
|
||
slotId: slot.slotId,
|
||
tagId: Number(tag.tag.id),
|
||
bannerId: Number(banner.id),
|
||
couponId: Number(coupon.id),
|
||
couponCode: coupon.couponCode,
|
||
snippetId: Number(snippet.id),
|
||
snippetCode: snippet.snippetCode,
|
||
userToken: user.token,
|
||
userMobile: user.mobile,
|
||
userId: user.userId,
|
||
orderId: Number(orders[0].id),
|
||
}
|
||
})
|
||
|
||
describe('region isolation — admin reads (ISO-01)', () => {
|
||
it('ISO-01: every region-scoped admin read is blind to the other region', async () => {
|
||
const b = regionB.client
|
||
|
||
const stores: any = await b.admin.store.getStores.query()
|
||
expect(stores.stores.some((s: any) => Number(s.id) === regionA.storeId)).toBe(false)
|
||
|
||
const products: any = await b.admin.product.getProducts.query()
|
||
expect(products.products.some((p: any) => Number(p.id) === regionA.productId)).toBe(false)
|
||
|
||
const tags: any = await b.admin.product.getProductTags.query()
|
||
expect(tags.tags.some((t: any) => Number(t.id) === regionA.tagId)).toBe(false)
|
||
|
||
const banners: any = await b.admin.banner.getBanners.query()
|
||
expect(banners.banners.some((x: any) => Number(x.id) === regionA.bannerId)).toBe(false)
|
||
|
||
const coupons: any = await b.admin.coupon.getAll.query({ search: regionA.couponCode })
|
||
expect(coupons.coupons.some((c: any) => Number(c.id) === regionA.couponId)).toBe(false)
|
||
|
||
const snippets: any = await b.admin.vendorSnippets.getAll.query()
|
||
expect(snippets.some((s: any) => Number(s.id) === regionA.snippetId)).toBe(false)
|
||
|
||
const users: any = await b.admin.user.getAllUsers.query({ search: regionA.userMobile, limit: 50 })
|
||
expect(users.users.some((u: any) => Number(u.id) === regionA.userId)).toBe(false)
|
||
|
||
const orders: any = await b.admin.order.getAll.query({ limit: 50 })
|
||
expect(orders.orders.some((o: any) => Number(o.id) === regionA.orderId)).toBe(false)
|
||
|
||
// Direct get-by-id is region-scoped too.
|
||
await expectTrpcError(
|
||
() => b.admin.product.getProductById.query({ id: regionA.productId }),
|
||
'NOT_FOUND'
|
||
)
|
||
await expectTrpcError(
|
||
() => b.admin.slots.getSlotById.query({ id: regionA.slotId }),
|
||
'NOT_FOUND'
|
||
)
|
||
|
||
// Sanity: region A sees its own data.
|
||
const aOrders: any = await regionA.admin.admin.order.getAll.query({ limit: 50 })
|
||
expect(aOrders.orders.some((o: any) => Number(o.id) === regionA.orderId)).toBe(true)
|
||
const aSlot: any = await regionA.admin.admin.slots.getSlotById.query({ id: regionA.slotId })
|
||
expect(Number(aSlot.slot.id)).toBe(regionA.slotId)
|
||
})
|
||
})
|
||
|
||
describe('region isolation — user reads (ISO-02)', () => {
|
||
it('ISO-02 (current): user product/slot/cache reads are scoped to the requested region', async () => {
|
||
const anon = apiClient()
|
||
|
||
// `getProductDetails` is keyed by the SKU id (the id products.json exposes);
|
||
// `productId` is the parent product id on the response.
|
||
const inRegion: any = await anon.user.product.getProductDetails.query({
|
||
id: String(regionA.skuId),
|
||
regionId: REGION_A,
|
||
})
|
||
expect(Number(inRegion.id)).toBe(regionA.skuId)
|
||
if (inRegion.productId != null) expect(Number(inRegion.productId)).toBe(regionA.productId)
|
||
|
||
// Foreign region: the SKU's own region wins and the read is refused. The
|
||
// handler throws a raw Error -> INTERNAL_SERVER_ERROR (not 404).
|
||
await expectTrpcError(
|
||
() =>
|
||
anon.user.product.getProductDetails.query({
|
||
id: String(regionA.skuId),
|
||
regionId: regionB.regionId,
|
||
}),
|
||
'INTERNAL_SERVER_ERROR',
|
||
'Product not found'
|
||
)
|
||
|
||
const aSlots: any = await anon.user.slots.getSlots.query({ regionId: REGION_A })
|
||
expect(aSlots.slots.some((s: any) => Number(s.id) === regionA.slotId)).toBe(true)
|
||
const bSlots: any = await anon.user.slots.getSlots.query({ regionId: regionB.regionId })
|
||
expect(bSlots.slots.some((s: any) => Number(s.id) === regionA.slotId)).toBe(false)
|
||
|
||
// The cache identity a client reads is bound to the requested bound's region.
|
||
const constsA = await getEssentialConsts(BOUND_A)
|
||
expect(constsA.regionId).toBe(REGION_A)
|
||
const constsB = await getEssentialConsts(regionB.boundId)
|
||
expect(constsB.regionId).toBe(regionB.regionId)
|
||
})
|
||
})
|
||
|
||
describe('region isolation — foreign-id writes (ISO-03)', () => {
|
||
it('ISO-03: writes carrying a foreign region id are rejected or land in the address region', async () => {
|
||
const admin = regionA.admin
|
||
const b = regionB.client
|
||
|
||
// Address in region B with region-A coordinates -> outside the region.
|
||
const user = await registerThrowawayUser()
|
||
await expectTrpcError(
|
||
() =>
|
||
apiClient(user.token).user.address.createAddress.mutate({
|
||
regionId: regionB.regionId,
|
||
name: 'Foreign address',
|
||
phone: '9876543210',
|
||
addressLine1: `Foreign ${uniqueSuffix()}`,
|
||
city: 'Mahabubnagar',
|
||
state: 'Telangana',
|
||
isDefault: true,
|
||
latitude: 16.7421312,
|
||
longitude: 78.01191145,
|
||
} as any),
|
||
'UNPROCESSABLE_CONTENT',
|
||
'outside this region'
|
||
)
|
||
|
||
// Region A cannot read or edit region B's store/product.
|
||
await expectTrpcError(() => admin.admin.store.getStoreById.query({ id: regionB.storeId }), 'NOT_FOUND')
|
||
await expectTrpcError(
|
||
() => admin.admin.store.updateStore.mutate({ id: regionB.storeId, name: `Nope ${uniqueSuffix()}` }),
|
||
'NOT_FOUND'
|
||
)
|
||
await expectTrpcError(
|
||
() => admin.admin.product.getProductById.query({ id: regionB.productId }),
|
||
'NOT_FOUND'
|
||
)
|
||
|
||
// Creating a region-A product that points at region B's store is rejected.
|
||
const foreignStoreName = `E2E ISO ForeignStore ${uniqueSuffix()}`
|
||
await expectTrpcError(
|
||
() =>
|
||
admin.admin.product.createProduct.mutate({
|
||
name: foreignStoreName,
|
||
shortDescription: 'foreign store',
|
||
storeId: regionB.storeId,
|
||
productType: 'item',
|
||
skus: [
|
||
{
|
||
name: '1pc',
|
||
price: 100,
|
||
marketPrice: 150,
|
||
images: [],
|
||
isFlashAvailable: false,
|
||
flashPrice: null,
|
||
isOutOfStock: false,
|
||
isOffer: false,
|
||
isComboOnly: false,
|
||
isSuspended: false,
|
||
features: [{ featureName: 'quantity', featureValue: '1pc' }],
|
||
},
|
||
],
|
||
} as any),
|
||
'INTERNAL_SERVER_ERROR'
|
||
)
|
||
const products: any = await admin.admin.product.getProducts.query()
|
||
expect(products.products.some((p: any) => p.name === foreignStoreName)).toBe(false)
|
||
|
||
// Creating a region-A slot that carries region B's SKU is rejected (nothing written).
|
||
const slotsBefore: any = await admin.admin.slots.getAll.query()
|
||
await expectTrpcError(
|
||
() =>
|
||
admin.admin.slots.createSlot.mutate({
|
||
deliveryTime: new Date(Date.now() + 3 * 3_600_000).toISOString(),
|
||
freezeTime: new Date(Date.now() + 2 * 3_600_000).toISOString(),
|
||
isActive: true,
|
||
skuIds: [regionB.skuId],
|
||
}),
|
||
'INTERNAL_SERVER_ERROR'
|
||
)
|
||
const slotsAfter: any = await admin.admin.slots.getAll.query()
|
||
expect(slotsAfter.count).toBe(slotsBefore.count)
|
||
|
||
// A stale client regionId cannot move an order out of its address region.
|
||
const defaultAddress: any = await apiClient(regionA.userToken).user.address.getDefaultAddress.query()
|
||
const placed = await placeOrder(regionA.userToken, {
|
||
addressId: Number(defaultAddress.data!.id),
|
||
skuId: regionA.skuId,
|
||
slotId: regionA.slotId,
|
||
regionId: regionB.regionId,
|
||
})
|
||
expect(Number(placed[0].regionId)).toBe(REGION_A)
|
||
})
|
||
})
|
||
|
||
describe('region isolation — cache files (ISO-04)', () => {
|
||
it('ISO-04: region A’s cache files contain no region B ids', async () => {
|
||
const productsDoc: any = await scaffoldCache('products', { regionId: REGION_A })
|
||
expect(productsDoc.products.some((p: any) => Number(p.id) === regionB.skuId)).toBe(false)
|
||
|
||
const storesDoc: any = await scaffoldCache('stores', { regionId: REGION_A })
|
||
expect(storesDoc.stores.some((s: any) => Number(s.id) === regionB.storeId)).toBe(false)
|
||
})
|
||
})
|
||
|
||
describe('region isolation — notifications (ISO-05)', () => {
|
||
})
|
||
|
||
describe('region isolation — globals (ISO-06)', () => {
|
||
it('ISO-06: a seeded global product/store is visible in every region’s cache', async () => {
|
||
const sa = await superadminClient()
|
||
const globals: any = await sa.superadmin.globalProducts.list.query()
|
||
const globalProducts: any[] = globals.products ?? []
|
||
expect(globalProducts.length).toBeGreaterThan(0)
|
||
const globalSkuId = Number(
|
||
globalProducts.flatMap((p: any) => p.skus ?? []).map((s: any) => s.id)[0]
|
||
)
|
||
expect(globalSkuId).toBeGreaterThan(0)
|
||
|
||
const globalStores: any = await sa.superadmin.globalStores.list.query()
|
||
const globalStoreList: any[] = Array.isArray(globalStores) ? globalStores : globalStores.stores ?? []
|
||
expect(globalStoreList.length).toBeGreaterThan(0)
|
||
const globalStoreId = Number(globalStoreList[0].id)
|
||
|
||
// Region A cache (scaffold — read straight from D1).
|
||
const aProducts: any = await scaffoldCache('products', { regionId: REGION_A })
|
||
expect(aProducts.products.some((p: any) => Number(p.id) === globalSkuId)).toBe(true)
|
||
|
||
// Region B cache (scaffold — read straight from D1).
|
||
const bStores: any = await scaffoldCache('stores', { regionId: regionB.regionId })
|
||
expect(bStores.stores.some((s: any) => Number(s.id) === globalStoreId)).toBe(true)
|
||
})
|
||
})
|
||
|
||
describe('region isolation — superadmin global views (ISO-07)', () => {
|
||
it('ISO-07: superadmin products/complaints are explicitly global (not region-filtered)', async () => {
|
||
const sa = await superadminClient()
|
||
|
||
const all: any = await sa.superadmin.products.list.query({ limit: 100 })
|
||
const regionIds = new Set(
|
||
(all.products ?? []).map((p: any) => p.regionId).filter((id: any) => id != null)
|
||
)
|
||
expect(regionIds.size).toBeGreaterThanOrEqual(2)
|
||
|
||
const complaints: any = await sa.superadmin.complaint.getAll.query({ limit: 20 })
|
||
expect(Array.isArray(complaints.complaints)).toBe(true)
|
||
for (const c of complaints.complaints) {
|
||
expect(c).toHaveProperty('regionId')
|
||
}
|
||
})
|
||
})
|
||
|
||
describe('region isolation — public vendor links (ISO-08)', () => {
|
||
it('ISO-08: a vendor snippet is looked up globally by code from an anonymous client', async () => {
|
||
const res: any = await apiClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||
snippetCode: regionA.snippetCode,
|
||
})
|
||
expect(res.success).toBe(true)
|
||
expect(res.snippet.snippetCode).toBe(regionA.snippetCode)
|
||
expect(Number(res.snippet.id)).toBe(regionA.snippetId)
|
||
})
|
||
})
|