bcgov / bcgov/connect

[TASK]: Upstream API Mocking & Validation with Stoplight Prism

Open
#106 0 comments 0 reactions 0 assignees View on GitHub
impact: high-blast
Dominant language
No language data
Stars
0
Forks
4
Avg merge
1m
Merged PRs (30d)
2

Description

# Technical Specification: Upstream API Mocking & Validation with Stoplight Prism

## 1. Overview & Objectives

When testing server-side account provisioning (`POST /api/accounts`) and other upstream integrations, our Nitro backend communicates directly with the Connect Auth REST API (`https://test.api.connect.gov.bc.ca/auth`). Relying on live remote environments during automated testing introduces several challenges:
- External network latency and transient timeouts.
- Accumulation of dirty test state and collision with real service account limits.
- Difficulty simulating edge conditions (e.g., 400 validation errors, 409 name conflicts, 502 gateway timeouts).

This specification outlines the integration of **[Stoplight Prism](https://stoplight.io/open-source/prism)** (`@stoplight/prism-cli`) to serve as a fast, deterministic, schema-validating mock HTTP server for all upstream REST dependencies during integration and E2E testing.

---

## 2. Architecture & Data Flow

```
┌─────────────────────────────────────────────────────────────┐
│ E2E / Integration Tests │
│ (Playwright / Vitest / Nitro API) │
└──────────────────────────────┬──────────────────────────────┘

Calls POST /api/accounts

┌─────────────────────────────────────────────────────────────┐
│ Nuxt Hub Nitro Backend │
│ │
│ • Reads process.env.AUTH_API_URL │
│ • Normal: https://test.api.connect.gov.bc.ca/auth │
│ • Testing: http://127.0.0.1:4010 │
└──────────────────────────────┬──────────────────────────────┘

Upstream REST Calls (JSON over HTTP)

┌─────────────────────────────────────────────────────────────┐
│ Stoplight Prism Mock │
│ hub/test-data/specs/auth-api.oas.yaml │
│ │
│ • POST /api/v1/orgs │
│ - Validates Bearer & x-apikey headers │
│ - Validates GOVM accessType & mailingAddress schema │
│ - Returns 201 Created Organization │
│ • POST /api/v1/orgs/{org_id}/members/invite/{user_email} │
│ - Validates path parameters and role assignment │
│ - Returns 201 Invitation Dispatched │
└─────────────────────────────────────────────────────────────┘
```

### Key Capabilities of Prism
1. **Request Schema Validation**: Prism strictly validates headers (`Authorization`, `x-apikey`), path variables, query parameters, and JSON bodies against the OAS schema. If our Nitro backend sends malformed fields, Prism rejects the request with HTTP 422.
2. **Realistic Mock Responses**: Generates dynamic or example-based responses matching the upstream Connect Auth API contracts.
3. **No External Network Dependencies**: Runs locally in-memory on `127.0.0.1:4010`, ensuring millisecond test execution times.

---

## 3. OpenAPI Contract Definition

The mock server will be driven by an OpenAPI 3.1 specification located at:
`hub/test-data/specs/auth-api.oas.yaml`

### Key Endpoints Defined:
1. **`POST /api/v1/orgs`**:
- **Request Headers**:
- `Authorization`: `Bearer ` (Required)
- `x-apikey`: `` (Required)
- **Request Body**:
- `name`: `string`
- `branchName`: `string` (Optional)
- `accessType`: Enum `["GOVM", "REGULAR", "EXTRA_PROVINCIAL"]`
- `productSubscriptions`: Array of objects with `productCode` (e.g., `"BUSINESS_SEARCH"`)
- `mailingAddress`: Street, city, region (`"BC"`), postalCode, country (`"CA"`)
- **Response (201 Created)**:
- Returns complete organization entity with `id`, `name`, `accessType`, `orgStatus: "ACTIVE"`.

2. **`POST /api/v1/orgs/{org_id}/members/invite/{user_email}`**:
- **Path Parameters**:
- `org_id`: `integer`
- `user_email`: `string` (format: email)
- **Response (201 Created)**:
- Returns invitation object with `id`, `recipientEmail`, `status: "PENDING"`.

3. **`GET /api/v1/users/{guid}/settings`**:
- Returns list of user account affiliations matching the `UserSetting[]` interface in `hub/server/utils/auth.ts`.

---

## 4. Test Orchestration & Environment Configuration

### 4.1. Package Management
Add `@stoplight/prism-cli` to `hub/devDependencies`:
```json
{
"devDependencies": {
"@stoplight/prism-cli": "^5.16.0"
}
}
```

### 4.2. Playwright Test Integration
Prism can be launched either via Playwright's `webServer` configuration or within test setup hooks:

```ts
// Example: In Playwright test setup or test fixture
import { spawn } from 'child_process'

let prismProcess: ChildProcess

test.beforeAll(async () => {
prismProcess = spawn('pnpm', [
'exec',
'prism',
'mock',
'test-data/specs/auth-api.oas.yaml',
'-p',
'4010'
], { stdio: 'inherit' })
})

test.afterAll(async () => {
prismProcess.kill()
})
```

### 4.3. Nitro Environment Redirection
During test runs, `AUTH_API_URL` is set to:
```env
AUTH_API_URL=http://127.0.0.1:4010
```
Our existing server utility [`hub/server/utils/auth.ts`](file:///Users/thor/Developer/thorwolpert/ServiceBC/connect/.worktrees/feature-hub-01/hub/server/utils/auth.ts) and the upcoming [`accounts.post.ts`](file:///Users/thor/Developer/thorwolpert/ServiceBC/connect/.worktrees/feature-hub-01/hub/server/api/accounts.post.ts) already read `AUTH_API_URL` dynamically, so zero application code changes are needed to route traffic through the Prism mock.

---

## 5. Deliverables & Implementation Plan

| Step | Item | Location |
|---|---|---|
| **Step 1** | OpenAPI Contract | `hub/e2e/contracts/auth-api.oas.yaml` |
| **Step 2** | NPM Dependency | Add `@stoplight/prism-cli` to `hub/package.json` |
| **Step 3** | E2E Test Suite | `hub/e2e/account-creation.spec.ts` using Prism mock server |

Contributor guide

Open the contributing guide

Research direction

Start with hub/server/utils/auth.ts and the planned hub/server/api/accounts.post.ts to confirm how AUTH_API_URL is used. Review the proposed OpenAPI contract location and hub/e2e/account-creation.spec.ts, then run the Playwright suite with Prism on port 4010. Done means upstream calls use the local mock, request validation and example responses cover the listed endpoints, and account-creation tests pass without external network access.

Written by the indexing model from the issue text.

Assessment

Tech stack
nuxt, openapi, playwright, typescript
Domain
api, backend, testing
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.