Add Kiro specs, hooks, and steering files — development tooling archive

This commit is contained in:
Jordan Ramos
2026-05-01 21:30:05 +00:00
parent b9fa1281a9
commit 05d95309b4
90 changed files with 12312 additions and 0 deletions

View File

@@ -0,0 +1 @@
{"specId": "0334e0b6-7ae7-4284-95a0-caed55c59af1", "workflowType": "requirements-first", "specType": "feature"}

View File

@@ -0,0 +1,339 @@
# Design Document: CARD API Integration
## Overview
This design integrates the CARD Asset Ownership API into the STEAM Security Dashboard, enabling users to confirm, decline, and redirect CARD assets directly from the Ivanti Queue. The integration follows the existing architectural patterns established by the Atlas API integration (`atlasApi.js` / `atlas.js` route), adding OAuth Bearer token management with automatic caching and refresh.
The implementation is split into three layers:
1. **Helper module** (`backend/helpers/cardApi.js`) — already built and UAT-tested. Handles HTTP transport, OAuth token lifecycle, and high-level CARD API wrappers.
2. **Route module** (`backend/routes/cardApi.js`) — new Express router that proxies CARD operations, validates queue items, orchestrates the two-step update_token flow, and logs audit entries.
3. **Frontend UI** — CARD action buttons (Confirm, Decline, Redirect) on queue items, team selection dropdowns, and an asset search panel.
### Key Findings from UAT Testing
- Token endpoint is `POST /api/v1/auth/get_token` (not GET)
- Team name field in API responses is `card_team_name` or `_id`
- The `update_token` is nested at `owner.update_token` in the owner record
- The assets endpoint **requires** a `disposition` query parameter (returns 500 without it)
- The helper module and UAT test script are already built and validated
## Architecture
```mermaid
graph TD
subgraph Frontend
QP[Ivanti Queue Panel] --> AB[CARD Action Buttons]
AB --> CF[Confirm Form]
AB --> DF[Decline Form]
AB --> RF[Redirect Form]
QP --> AS[Asset Search Panel]
end
subgraph Backend
CR[cardApi Route<br>/api/card/*] --> CM[cardApi Helper]
CR --> DB[(SQLite DB<br>ivanti_todo_queue)]
CR --> AL[Audit Logger]
CM --> TM[Token Manager]
end
subgraph External
CARD[CARD API<br>card.charter.com]
end
CF --> CR
DF --> CR
RF --> CR
AS --> CR
CM --> CARD
TM --> CARD
```
### Request Flow for Mutations (Confirm/Decline/Redirect)
```mermaid
sequenceDiagram
participant UI as Frontend
participant Route as cardApi Route
participant DB as SQLite
participant Helper as cardApi Helper
participant CARD as CARD API
UI->>Route: POST /api/card/queue/:id/confirm
Route->>DB: Validate queue item (exists, user, CARD, pending)
DB-->>Route: Queue item record
Route->>Helper: getOwner(assetId)
Helper->>CARD: GET /api/v1/owner/{assetId}
CARD-->>Helper: Owner record with update_token
Helper-->>Route: { owner: { update_token: "..." } }
Route->>Helper: confirmAsset(assetId, team, token, comment)
Helper->>CARD: POST /api/v2/owner/{assetId}/confirm?update_token=...
CARD-->>Helper: Success response
Helper-->>Route: { status: 200, body: "..." }
Route->>DB: UPDATE status = 'complete'
Route->>AL: logAudit(card_confirm, ...)
Route-->>UI: { success: true, cardResponse: ... }
```
## Components and Interfaces
### 1. CARD API Helper (`backend/helpers/cardApi.js`) — Already Built
The helper module is complete and UAT-tested. It exports:
| Export | Type | Description |
|--------|------|-------------|
| `isConfigured` | `boolean` | `true` when `CARD_API_URL`, `CARD_API_USER`, `CARD_API_PASS` are all set |
| `missingVars` | `string[]` | List of missing env var names |
| `cardGet(urlPath, options)` | `function` | GET request with Bearer auth, returns `{ status, body }` |
| `cardPost(urlPath, body, options)` | `function` | POST request with Bearer auth, returns `{ status, body }` |
| `getTeams()` | `function` | `GET /api/v1/teams` — returns `{ status, body, ok }` |
| `getTeamAssets(teamName, opts)` | `function` | `GET /api/v1/team/{name}/assets` with disposition, page, pageSize |
| `getOwner(assetId)` | `function` | `GET /api/v1/owner/{assetId}` — returns owner record with `update_token` |
| `confirmAsset(assetId, team, token, comment)` | `function` | `POST /api/v2/owner/{id}/confirm` |
| `declineAsset(assetId, team, token, comment)` | `function` | `POST /api/v2/owner/{id}/decline` |
| `redirectAsset(assetId, from, to, token)` | `function` | `POST /api/v2/owner/{id}/{from}/redirect` |
| `invalidateToken()` | `function` | Clears cached Bearer token |
| `testConnection()` | `function` | Acquires token and returns `{ ok, token }` or `{ ok, error }` |
**Token Manager** (internal to helper):
- Acquires tokens via `POST /api/v1/auth/get_token` with Basic Auth
- Caches in memory with 1-hour TTL, refreshes when within 60s of expiry
- Automatically retries once on HTTP 401 (invalidate → re-acquire → retry)
### 2. CARD API Route (`backend/routes/cardApi.js`) — New
Factory function: `createCardApiRouter(db, requireAuth)` → Express Router
**Endpoints:**
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/card/status` | Returns `{ configured: boolean }` |
| GET | `/api/card/teams` | Proxies CARD teams list |
| GET | `/api/card/teams/:teamName/assets` | Proxies team assets with `disposition` (required), `page`, `page_size` (default 50) |
| GET | `/api/card/owner/:assetId` | Proxies owner record lookup |
| POST | `/api/card/queue/:queueItemId/confirm` | Confirm asset — body: `{ teamName, assetId, comment? }` |
| POST | `/api/card/queue/:queueItemId/decline` | Decline asset — body: `{ teamName, assetId, comment? }` |
| POST | `/api/card/queue/:queueItemId/redirect` | Redirect asset — body: `{ fromTeam, toTeam, assetId }` |
**Middleware:** All endpoints use `requireAuth(db)` + `requireGroup('Admin', 'Standard_User')`.
**Mutation flow** (confirm/decline/redirect):
1. Validate queue item: exists, belongs to `req.user.id`, `workflow_type = 'CARD'`, `status = 'pending'`
2. Fetch owner record via `getOwner(assetId)` to get fresh `update_token`
3. Extract `update_token` from `owner.update_token` (nested path)
4. Execute CARD mutation with the `update_token`
5. On success: update queue item `status = 'complete'`, log audit, return response
6. On failure: leave queue item as `pending`, log audit failure, return error
### 3. Frontend Components
**Modified:** Ivanti Queue panel in the existing queue UI
**New UI elements:**
- **CARD Action Buttons**: Confirm, Decline, Redirect buttons rendered on pending CARD queue items
- **Confirm/Decline Form**: Team dropdown (from `/api/card/teams`) + optional comment field
- **Redirect Form**: From Team dropdown + To Team dropdown
- **Asset Search Panel**: Team dropdown + disposition filter + paginated results table
- **Loading/Error States**: Inline loading indicators and error messages per queue item
**Session-level caching:** Teams list fetched once per browser session and reused across all forms.
### 4. Server Integration (`backend/server.js`)
Mount the new route:
```javascript
const createCardApiRouter = require('./routes/cardApi');
// ...
app.use('/api/card', createCardApiRouter(db, requireAuth));
```
## Data Models
### Existing: `ivanti_todo_queue` Table
No schema changes required. CARD items use `workflow_type = 'CARD'`.
| Column | Type | Notes |
|--------|------|-------|
| `id` | INTEGER | Primary key |
| `user_id` | INTEGER | FK to users |
| `finding_id` | TEXT | Ivanti finding identifier |
| `finding_title` | TEXT | Finding description |
| `cves_json` | TEXT | JSON array of CVE IDs |
| `ip_address` | TEXT | Asset IP address (used as CARD Asset_ID with suffix) |
| `hostname` | TEXT | Asset hostname |
| `vendor` | TEXT | Empty string for CARD items |
| `workflow_type` | TEXT | `'CARD'` for this integration |
| `status` | TEXT | `'pending'` or `'complete'` |
| `created_at` | DATETIME | Auto-set |
| `updated_at` | DATETIME | Auto-updated |
### CARD API Response Shapes (from UAT testing)
**Teams response** (`GET /api/v1/teams`):
```json
[
{ "_id": "NTS-AEO-STEAM", "card_team_name": "NTS-AEO-STEAM", ... },
{ "_id": "NTS-ACCESS-ENG", "card_team_name": "NTS-ACCESS-ENG", ... }
]
```
Team name extraction: `t.card_team_name || t._id`
**Owner record** (`GET /api/v1/owner/{assetId}`):
```json
{
"owner": {
"update_token": "abc123...",
"dispositions": [
{ "team": "NTS-AEO-STEAM", "disposition": "confirmed", ... }
],
...
}
}
```
Update token path: `response.owner.update_token`
**Team assets** (`GET /api/v1/team/{name}/assets?disposition=confirmed&page_size=50`):
```json
{
"assets": [ { "asset_id": "98.8.142.56-NATL", ... } ],
"total": 150,
"page": 1,
"page_size": 50
}
```
### Audit Log Entries
| Action | entityType | entityId | Details |
|--------|-----------|----------|---------|
| `card_confirm` | `ivanti_todo_queue` | queue item ID | `{ assetId, teamName, comment, cardStatus }` |
| `card_decline` | `ivanti_todo_queue` | queue item ID | `{ assetId, teamName, comment, cardStatus }` |
| `card_redirect` | `ivanti_todo_queue` | queue item ID | `{ assetId, fromTeam, toTeam, cardStatus }` |
| `card_search` | `card_asset` | team name | `{ disposition, resultCount }` |
| `card_action_failed` | `ivanti_todo_queue` | queue item ID | `{ actionType, assetId, error, cardStatus }` |
## Correctness Properties
*A property is a characteristic or behavior that should hold true across all valid executions of a system — essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*
### Property 1: isConfigured reflects environment variable presence
*For any* combination of the three required environment variables (`CARD_API_URL`, `CARD_API_USER`, `CARD_API_PASS`) being present/non-empty or absent/empty, `isConfigured` SHALL be `true` if and only if all three are present and non-empty.
**Validates: Requirements 1.1, 3.3**
### Property 2: All CARD API responses have consistent shape
*For any* successful CARD API call (any HTTP method and URL path), the resolved Promise SHALL contain an object with a numeric `status` field and a string `body` field.
**Validates: Requirements 1.7**
### Property 3: Token acquisition errors include status and body
*For any* non-success HTTP status code and response body returned by the token acquisition endpoint, the rejected Promise error message SHALL include both the HTTP status code and the response body text.
**Validates: Requirements 2.7**
### Property 4: CARD API error status codes are forwarded through proxy
*For any* HTTP error status code (4xx or 5xx) returned by the CARD API on a proxied request, the route SHALL return that same status code to the client along with a JSON error body containing the upstream error message.
**Validates: Requirements 4.9**
### Property 5: Queue item validation rejects invalid states for mutations
*For any* CARD mutation request (confirm, decline, or redirect), if the referenced queue item does not exist, does not belong to the requesting user, has `workflow_type` other than `'CARD'`, or has `status` other than `'pending'`, the endpoint SHALL reject the request with the appropriate HTTP error code (404 or 400) without calling the CARD API.
**Validates: Requirements 5.4, 5.5, 5.6**
### Property 6: Mutation input validation enforces required fields
*For any* CARD mutation request, the endpoint SHALL reject with HTTP 400 if any required field is missing or empty: `teamName` and `assetId` for confirm/decline; `fromTeam`, `toTeam`, and `assetId` for redirect. Optional fields (e.g., `comment`) SHALL be accepted when absent.
**Validates: Requirements 5.11, 5.12, 5.13**
### Property 7: CARD mutation audit entries contain required fields
*For any* CARD mutation action (confirm, decline, or redirect) executed through the dashboard, the audit log entry SHALL contain the correct `action` name (`card_confirm`, `card_decline`, or `card_redirect`), `entityType` of `'ivanti_todo_queue'`, the queue item ID as `entityId`, the requesting user's `userId`, `username`, and `ipAddress`, and a `details` object containing the `assetId` and CARD API response status.
**Validates: Requirements 9.1, 9.2, 9.3, 9.6**
## Error Handling
### CARD Helper Error Handling
| Scenario | Behavior |
|----------|----------|
| CARD API unreachable / timeout | Reject with `[card-api] {METHOD} {path} failed: {reason}` |
| Token endpoint returns non-2xx | Reject with `[card-api] Token acquisition failed with HTTP {status}: {body}` |
| Token endpoint returns unparseable JSON | Fall back to raw body as token string; reject if empty |
| Token endpoint returns empty token | Reject with `[card-api] Token parse failure: empty token in response body.` |
| Non-auth request returns 401 | Invalidate token, re-acquire, retry once. If retry also 401, return the 401 |
### Route Error Handling
| CARD API Status | Route Response | Error Message |
|----------------|----------------|---------------|
| 401 (token endpoint) | 401 | `CARD authorization failed. Check service account credentials.` |
| 403 (token endpoint) | 403 | `CARD access denied. The service account may not be onboarded with the CARD team.` |
| 525 (token endpoint) | 502 | `CARD LDAP error. The service account may not be provisioned correctly.` |
| 401 (API call, after retry) | 401 | `CARD token expired or invalid. The request has been retried once automatically.` |
| 403 (API call) | 403 | `Insufficient CARD permissions for this operation.` |
| Any unhandled error | 502 | `CARD API request failed.` + details |
| Not configured | 503 | `CARD API is not configured.` + missing vars |
All errors are logged to console with `[card-api]` prefix for consistent log filtering.
### Frontend Error Handling
- Inline error messages on the affected queue item (no modal popups)
- Loading state disables action buttons to prevent double-submission
- Network errors display a generic "Unable to reach server" message
- CARD-specific errors display the backend error message verbatim
## Testing Strategy
### Property-Based Tests (fast-check)
The project uses Jest as the test runner. Property-based tests will use [fast-check](https://github.com/dubzzz/fast-check) with a minimum of 100 iterations per property.
Each property test references its design document property:
| Property | Test File | What It Validates |
|----------|-----------|-------------------|
| Property 1: isConfigured | `backend/__tests__/card-isConfigured.property.test.js` | Env var combinations → isConfigured correctness |
| Property 2: Response shape | `backend/__tests__/card-response-shape.property.test.js` | All API responses have { status, body } |
| Property 3: Token error messages | `backend/__tests__/card-token-errors.property.test.js` | Error messages include status + body |
| Property 4: Error forwarding | `backend/__tests__/card-error-forwarding.property.test.js` | Proxy forwards CARD error status codes |
| Property 5: Queue validation | `backend/__tests__/card-queue-validation.property.test.js` | Invalid queue states rejected correctly |
| Property 6: Input validation | `backend/__tests__/card-input-validation.property.test.js` | Required fields enforced on mutations |
| Property 7: Audit entries | `backend/__tests__/card-audit-entries.property.test.js` | Mutation audit logs have correct shape |
Tag format: `Feature: card-api-integration, Property {N}: {title}`
### Unit Tests (example-based)
- Token acquisition flow (mock HTTP, verify Basic Auth header)
- Token caching and refresh timing
- 401 retry logic (mock 401 → 200 sequence)
- Two-step update_token flow (getOwner → mutation)
- Specific CARD API endpoint URL construction
- Default page_size=50 on assets endpoint
- TLS skip configuration
### Integration Tests
- Route mounting at `/api/card` prefix
- Auth middleware enforcement (401 without session)
- End-to-end confirm/decline/redirect with mocked CARD API
- Asset search with pagination
### Frontend Tests
- CARD action buttons render only on pending CARD items
- Form submission sends correct request body
- Loading state disables buttons
- Error messages display inline
- Teams list caching (single fetch per session)

View File

@@ -0,0 +1,163 @@
# Requirements Document
## Introduction
This feature integrates the CARD API into the STEAM Security Dashboard so that CARD workflow items in the Ivanti Queue can trigger real actions — confirm, decline, redirect, and search — via the CARD API. The integration covers OAuth token management, a backend helper module with automatic update_token handling, specific proxy routes for each CARD operation, and frontend UI updates that let users execute CARD actions directly from the queue. A standalone asset search capability supports Granite ID lookups when assets are reassigned.
## Glossary
- **Dashboard**: The STEAM Security Dashboard — the self-hosted vulnerability management application this feature extends.
- **CARD_API**: The external CARD REST API hosted at `card.charter.com` (production) or `card.caas.stage.charterlab.com` (UAT), authenticated via OAuth Bearer tokens. Read endpoints use the `/api/v1/` path prefix; mutation endpoints use the `/api/v2/` path prefix.
- **CARD_Helper**: The new `backend/helpers/cardApi.js` module responsible for CARD API authentication, token management, and HTTP request execution.
- **Token_Manager**: The component within CARD_Helper that handles OAuth token acquisition via Basic Auth, in-memory caching, and automatic refresh before expiry. Tokens have a one-hour TTL.
- **Queue_Item**: A row in the `ivanti_todo_queue` table with `workflow_type = 'CARD'`, representing a finding staged for CARD action.
- **CARD_Route**: The new Express route module at `backend/routes/cardApi.js` that exposes CARD API operations to the frontend through the backend.
- **Audit_Logger**: The existing `logAudit(db, {...})` helper that records state-changing actions to the `audit_logs` table.
- **Auth_Middleware**: The existing `requireAuth(db)` and `requireGroup(...)` middleware that enforces session validation and role-based access.
- **Asset_ID**: A CARD asset identifier in IPN format (e.g., `98.8.142.56-NATL`). Used as the path parameter in owner lookup and mutation endpoints.
- **Update_Token**: A server-generated token returned by the GET owner endpoint. The update_token is mandatory for all mutation calls (confirm, decline, redirect) and ensures optimistic concurrency control.
- **Disposition**: The ownership state of an asset in CARD. Valid values are `confirmed`, `unconfirmed`, `declined`, and `candidate`.
- **Team**: A CARD team name (e.g., `NTS-AEO-STEAM`). Teams are the organizational unit for asset ownership in CARD.
- **Owner_Record**: The JSON object returned by the GET owner endpoint, containing the asset ownership details, disposition states with team names, scores, timestamps, and the update_token field.
## Requirements
### Requirement 1: CARD API Helper Module
**User Story:** As a backend developer, I want a dedicated CARD API helper module that follows the existing atlasApi.js pattern, so that all CARD API communication is centralized and consistent with the codebase.
#### Acceptance Criteria
1. THE CARD_Helper SHALL export an `isConfigured` boolean that is `true` only when all required environment variables (`CARD_API_URL`, `CARD_API_USER`, `CARD_API_PASS`) are present and non-empty.
2. WHEN `isConfigured` is `false`, THE CARD_Helper SHALL log a warning at module load listing the missing environment variables with the prefix `[card-api]`.
3. THE CARD_Helper SHALL use the Node.js built-in `https` module for all HTTP requests to the CARD_API.
4. THE CARD_Helper SHALL export convenience wrapper functions for GET and POST HTTP methods, each accepting a URL path, optional request body, and optional options object.
5. THE CARD_Helper SHALL set `rejectUnauthorized` to `false` on HTTPS requests when the `CARD_SKIP_TLS` environment variable is set to `'true'`.
6. THE CARD_Helper SHALL apply a configurable request timeout defaulting to 15000 milliseconds.
7. THE CARD_Helper SHALL return a Promise that resolves with an object containing `status` (HTTP status code) and `body` (response body string) for each request.
8. THE CARD_Helper SHALL route read requests (GET) through the `/api/v1/` path prefix and mutation requests (POST) through the `/api/v2/` path prefix, matching the CARD_API versioning scheme.
### Requirement 2: OAuth Token Management
**User Story:** As a backend developer, I want the CARD helper to manage OAuth Bearer tokens automatically, so that downstream code does not need to handle authentication directly.
#### Acceptance Criteria
1. WHEN a CARD API request is made and no cached token exists, THE Token_Manager SHALL acquire a new token by sending a request to the CARD_API `/api/v1/auth/get_token` endpoint with a Basic Auth header containing the base64-encoded `CARD_API_USER:CARD_API_PASS` credentials.
2. WHEN a valid token is received, THE Token_Manager SHALL cache the token in memory along with its expiry timestamp (one-hour TTL from acquisition time).
3. WHEN a cached token exists and its expiry timestamp is more than 60 seconds in the future, THE Token_Manager SHALL reuse the cached token for subsequent requests.
4. WHEN a cached token exists and its expiry timestamp is 60 seconds or less in the future, THE Token_Manager SHALL acquire a new token before making the API request.
5. THE Token_Manager SHALL include the cached Bearer token in the `Authorization` header of all non-authentication CARD API requests.
6. IF the CARD_API returns an HTTP 401 response on a non-authentication request, THEN THE Token_Manager SHALL invalidate the cached token, acquire a new token, and retry the original request exactly once.
7. IF the token acquisition request fails or returns a non-success HTTP status, THEN THE Token_Manager SHALL reject the Promise with a descriptive error message including the HTTP status code and the response body.
### Requirement 3: Environment Variable Configuration
**User Story:** As a system administrator, I want CARD API credentials and settings stored in environment variables following the existing pattern, so that configuration is consistent and secrets are not committed to source control.
#### Acceptance Criteria
1. THE Dashboard SHALL read the following environment variables for CARD API configuration: `CARD_API_URL` (base URL), `CARD_API_USER` (service account username), `CARD_API_PASS` (service account password), and `CARD_SKIP_TLS` (TLS verification toggle).
2. THE Dashboard SHALL document all CARD environment variables in `backend/.env.example` with descriptive comments matching the existing documentation style.
3. WHEN any of `CARD_API_URL`, `CARD_API_USER`, or `CARD_API_PASS` is missing or empty, THE CARD_Helper SHALL treat the integration as unconfigured and report `isConfigured` as `false`.
4. THE Dashboard SHALL treat `CARD_SKIP_TLS` as optional, defaulting to `false` when not set.
### Requirement 4: CARD API Proxy Routes
**User Story:** As a dashboard user, I want backend routes that proxy specific CARD API operations, so that the frontend can trigger CARD actions without exposing API credentials to the browser.
#### Acceptance Criteria
1. THE CARD_Route SHALL export a factory function `createCardApiRouter(db, requireAuth)` that returns an Express Router, following the existing route module pattern.
2. THE CARD_Route SHALL protect all endpoints with `requireAuth(db)` for session validation and `requireGroup('Admin', 'Standard_User')` for role-based access.
3. THE CARD_Route SHALL expose a `GET /api/card/status` endpoint that returns `{ configured: boolean }` indicating whether the CARD API integration is configured.
4. THE CARD_Route SHALL expose a `GET /api/card/teams` endpoint that proxies the CARD_API `GET /api/v1/teams` endpoint and returns the list of CARD teams to the client.
5. THE CARD_Route SHALL expose a `GET /api/card/teams/:teamName/assets` endpoint that proxies the CARD_API `GET /api/v1/team/{teamName}/assets` endpoint, accepting `disposition`, `page`, and `page_size` query parameters.
6. WHEN the `page_size` query parameter is not provided on the assets endpoint, THE CARD_Route SHALL default to a page size of 50.
7. THE CARD_Route SHALL expose a `GET /api/card/owner/:assetId` endpoint that proxies the CARD_API `GET /api/v1/owner/{assetId}` endpoint and returns the Owner_Record including disposition states and the update_token.
8. IF `isConfigured` is `false` when a CARD API proxy endpoint is called, THEN THE CARD_Route SHALL return HTTP 503 with `{ error: 'CARD API is not configured.' }`.
9. IF the CARD_API returns an error response, THEN THE CARD_Route SHALL return the CARD_API HTTP status code and a JSON error body containing the upstream error message.
10. THE CARD_Route SHALL be mounted at the `/api/card` path prefix in `server.js`.
### Requirement 5: CARD Asset Mutation Actions
**User Story:** As a dashboard user, I want to confirm, decline, or redirect CARD assets directly from the queue, so that I can process CARD workflow findings without leaving the dashboard.
#### Acceptance Criteria
1. THE CARD_Route SHALL expose a `POST /api/card/queue/:queueItemId/confirm` endpoint that confirms an asset to a specified team via the CARD_API.
2. THE CARD_Route SHALL expose a `POST /api/card/queue/:queueItemId/decline` endpoint that declines an asset from a specified team via the CARD_API.
3. THE CARD_Route SHALL expose a `POST /api/card/queue/:queueItemId/redirect` endpoint that redirects an asset from one team to another team via the CARD_API.
4. WHEN any mutation endpoint is called, THE CARD_Route SHALL verify that the queue item exists, belongs to the requesting user, has `workflow_type = 'CARD'`, and has `status = 'pending'`.
5. IF the queue item does not exist, does not belong to the user, or is not a CARD workflow item, THEN THE CARD_Route SHALL return HTTP 404 with `{ error: 'Queue item not found.' }`.
6. IF the queue item status is not `'pending'`, THEN THE CARD_Route SHALL return HTTP 400 with `{ error: 'Only pending queue items can be executed.' }`.
7. WHEN a mutation endpoint is called, THE CARD_Route SHALL first call `GET /api/v1/owner/{assetId}` to retrieve the current update_token, then use that update_token in the subsequent mutation call, making the two-step flow transparent to the frontend.
8. WHEN the confirm endpoint is called, THE CARD_Route SHALL send `POST /api/v2/owner/{assetId}/confirm?update_token={token}&comment={comment}` with body `{ "name": "TEAM-NAME" }` to the CARD_API.
9. WHEN the decline endpoint is called, THE CARD_Route SHALL send `POST /api/v2/owner/{assetId}/decline?update_token={token}&comment={comment}` with body `{ "name": "TEAM-NAME" }` to the CARD_API.
10. WHEN the redirect endpoint is called, THE CARD_Route SHALL send `POST /api/v2/owner/{assetId}/{fromTeam}/redirect?update_token={token}` with body `{ "name": "TO-TEAM-NAME" }` to the CARD_API, where `fromTeam` is a path parameter and the destination team is in the request body.
11. THE confirm endpoint SHALL accept a request body containing `teamName` (string, required), `comment` (string, optional), and `assetId` (string, required).
12. THE decline endpoint SHALL accept a request body containing `teamName` (string, required), `comment` (string, optional), and `assetId` (string, required).
13. THE redirect endpoint SHALL accept a request body containing `fromTeam` (string, required), `toTeam` (string, required), and `assetId` (string, required).
14. WHEN the CARD_API mutation call succeeds, THE CARD_Route SHALL update the queue item status to `'complete'` and return the CARD_API response to the client.
15. IF the CARD_API mutation call fails, THEN THE CARD_Route SHALL leave the queue item status as `'pending'` and return the error to the client.
### Requirement 6: Frontend CARD Action UI
**User Story:** As a dashboard user, I want specific Confirm, Decline, and Redirect action buttons on CARD queue items, so that I can perform the correct CARD operation for each finding.
#### Acceptance Criteria
1. WHEN a CARD Queue_Item is displayed in the Ivanti Queue panel, THE Dashboard SHALL render three action buttons labeled "Confirm", "Decline", and "Redirect" on pending CARD items.
2. WHEN the user clicks the "Confirm" button, THE Dashboard SHALL display a form with a team selection dropdown (populated from the `/api/card/teams` endpoint) and an optional comment text field, then send a `POST` request to `/api/card/queue/:queueItemId/confirm` with the selected team name, comment, and asset ID.
3. WHEN the user clicks the "Decline" button, THE Dashboard SHALL display a form with a team selection dropdown and an optional comment text field, then send a `POST` request to `/api/card/queue/:queueItemId/decline` with the selected team name, comment, and asset ID.
4. WHEN the user clicks the "Redirect" button, THE Dashboard SHALL display a form with a "From Team" dropdown and a "To Team" dropdown (both populated from the `/api/card/teams` endpoint), then send a `POST` request to `/api/card/queue/:queueItemId/redirect` with the from team, to team, and asset ID.
5. WHILE a CARD action request is in flight, THE Dashboard SHALL disable the action buttons and display a loading indicator on the affected queue item.
6. WHEN the CARD action request succeeds, THE Dashboard SHALL update the queue item status to `'complete'` in the local UI state without requiring a full queue refresh.
7. IF the CARD action request fails, THEN THE Dashboard SHALL display the error message returned by the backend in an inline error indicator on the affected queue item.
8. WHEN the CARD API is not configured (status endpoint returns `configured: false`), THE Dashboard SHALL disable CARD action buttons and display a tooltip indicating the integration is not configured.
9. THE Dashboard SHALL cache the teams list from `/api/card/teams` for the duration of the browser session to avoid redundant API calls.
### Requirement 7: Asset Search UI
**User Story:** As a dashboard user, I want to search CARD for assets by team and disposition, so that I can find Granite IDs when assets get reassigned.
#### Acceptance Criteria
1. THE Dashboard SHALL provide an asset search interface accessible from the Ivanti Queue page.
2. THE asset search interface SHALL include a team selection dropdown (populated from the `/api/card/teams` endpoint) and a disposition filter dropdown with options: `confirmed`, `unconfirmed`, `declined`, `candidate`.
3. WHEN the user initiates a search, THE Dashboard SHALL send a `GET` request to `/api/card/teams/:teamName/assets` with the selected disposition and `page_size=50`.
4. WHEN the first page of results is returned, THE Dashboard SHALL display the total asset count and render the first page of results in a table.
5. WHEN the total asset count exceeds the page size, THE Dashboard SHALL provide pagination controls to navigate through additional pages by sending subsequent requests with incremented `page` parameters.
6. THE asset search results table SHALL display the Asset_ID and any other identifying fields returned by the CARD_API that help the user locate the correct Granite ID.
7. IF the asset search request fails, THEN THE Dashboard SHALL display the error message returned by the backend in the search results area.
### Requirement 8: Error Handling and Resilience
**User Story:** As a dashboard user, I want clear error feedback when CARD API operations fail, so that I can understand what went wrong and take corrective action.
#### Acceptance Criteria
1. IF the CARD_API is unreachable or the request times out, THEN THE CARD_Helper SHALL reject the Promise with an error message that includes the HTTP method, URL path, and failure reason.
2. IF the token acquisition endpoint returns invalid or unparseable JSON, THEN THE Token_Manager SHALL reject the Promise with a descriptive error message indicating a token parse failure.
3. IF the token acquisition endpoint returns HTTP 403, THEN THE CARD_Route SHALL return HTTP 403 with `{ error: 'CARD access denied. The service account may not be onboarded with the CARD team.' }`.
4. IF the token acquisition endpoint returns HTTP 401, THEN THE CARD_Route SHALL return HTTP 401 with `{ error: 'CARD authorization failed. Check service account credentials.' }`.
5. IF the token acquisition endpoint returns HTTP 525, THEN THE CARD_Route SHALL return HTTP 502 with `{ error: 'CARD LDAP error. The service account may not be provisioned correctly.' }`.
6. IF a CARD_API call returns HTTP 401, THEN THE CARD_Route SHALL return HTTP 401 with `{ error: 'CARD token expired or invalid. The request has been retried once automatically.' }`.
7. IF a CARD_API call returns HTTP 403, THEN THE CARD_Route SHALL return HTTP 403 with `{ error: 'Insufficient CARD permissions for this operation.' }`.
8. THE CARD_Route SHALL catch all unhandled errors from CARD_Helper calls and return HTTP 502 with `{ error: 'CARD API request failed.', details: <error message> }`.
9. THE CARD_Route SHALL log all CARD API errors to the server console with the prefix `[card-api]` for consistent log filtering.
10. IF the CARD_Helper is not configured and a proxy endpoint is called, THEN THE CARD_Route SHALL return HTTP 503 with a message indicating which environment variables are missing.
### Requirement 9: Audit Logging for CARD Actions
**User Story:** As an administrator, I want all CARD API actions logged in the audit trail, so that I can review what CARD operations were performed and by whom.
#### Acceptance Criteria
1. WHEN a CARD confirm action is executed through the dashboard, THE Audit_Logger SHALL record an entry with `action: 'card_confirm'`, `entityType: 'ivanti_todo_queue'`, the queue item ID as `entityId`, and `details` containing the asset ID, team name, comment, and CARD_API response status.
2. WHEN a CARD decline action is executed through the dashboard, THE Audit_Logger SHALL record an entry with `action: 'card_decline'`, `entityType: 'ivanti_todo_queue'`, the queue item ID as `entityId`, and `details` containing the asset ID, team name, comment, and CARD_API response status.
3. WHEN a CARD redirect action is executed through the dashboard, THE Audit_Logger SHALL record an entry with `action: 'card_redirect'`, `entityType: 'ivanti_todo_queue'`, the queue item ID as `entityId`, and `details` containing the asset ID, from team, to team, and CARD_API response status.
4. WHEN a CARD asset search is executed through the dashboard, THE Audit_Logger SHALL record an entry with `action: 'card_search'`, `entityType: 'card_asset'`, `entityId` set to the team name, and `details` containing the disposition filter and result count.
5. WHEN a CARD API action fails, THE Audit_Logger SHALL record an entry with `action: 'card_action_failed'`, `entityType: 'ivanti_todo_queue'`, the queue item ID as `entityId`, and `details` containing the action type, asset ID, error message, and CARD_API response status.
6. THE Audit_Logger SHALL record the requesting user's `userId`, `username`, and `ipAddress` on all CARD audit entries.
7. THE Audit_Logger SHALL use fire-and-forget semantics for CARD audit entries, matching the existing audit logging pattern.

View File

@@ -0,0 +1,165 @@
# Implementation Plan: CARD API Integration
## Overview
This plan covers the remaining implementation work for the CARD API integration into the STEAM Security Dashboard. The CARD API helper module (`backend/helpers/cardApi.js`), environment variable configuration, and UAT test script are already built and validated. The remaining work focuses on the backend route module, server mounting, frontend CARD action UI, asset search panel, and property-based tests.
## Tasks
- [x] 1. CARD API Helper Module (Already Complete)
- `backend/helpers/cardApi.js` is built and UAT-tested with all exports: `isConfigured`, `cardGet`, `cardPost`, `getTeams`, `getTeamAssets`, `getOwner`, `confirmAsset`, `declineAsset`, `redirectAsset`, `invalidateToken`, `testConnection`
- Token Manager handles OAuth Bearer token acquisition, 1-hour TTL caching, 60s refresh window, and automatic 401 retry
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7_
- [x] 2. Environment Variable Configuration (Already Complete)
- `backend/.env` and `backend/.env.example` have `CARD_API_URL`, `CARD_API_USER`, `CARD_API_PASS`, `CARD_SKIP_TLS` configured with descriptive comments
- _Requirements: 3.1, 3.2, 3.3, 3.4_
- [x] 3. UAT Test Script (Already Complete)
- `backend/scripts/card-uat-test.js` exercises all 9 CARD API use cases and passes
- _Requirements: 1.1, 1.7, 2.1, 2.3, 2.6_
- [x] 4. Backend CARD API Route Module
- [x] 4.1 Create `backend/routes/cardApi.js` with factory function `createCardApiRouter(db, requireAuth)`
- Follow the existing `atlas.js` route pattern: import `requireGroup` from middleware, import `logAudit` from helpers, import CARD helper functions from `helpers/cardApi.js`
- Add promise-based DB helpers (`dbRun`, `dbGet`) matching the atlas.js pattern
- Protect all endpoints with `requireAuth(db)` and `requireGroup('Admin', 'Standard_User')`
- _Requirements: 4.1, 4.2_
- [x] 4.2 Implement read-only proxy endpoints
- `GET /status` — return `{ configured: isConfigured }`; if not configured, return 503 with missing vars
- `GET /teams` — proxy `getTeams()`, parse JSON response, forward to client
- `GET /teams/:teamName/assets` — proxy `getTeamAssets()` with `disposition` (required), `page`, `page_size` (default 50) query params
- `GET /owner/:assetId` — proxy `getOwner()`, return owner record
- All proxy endpoints: return 503 if not configured, forward CARD API error status codes with JSON error body
- _Requirements: 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9_
- [x] 4.3 Implement mutation endpoints (confirm, decline, redirect) with two-step update_token flow
- `POST /queue/:queueItemId/confirm` — body: `{ teamName, assetId, comment? }`
- `POST /queue/:queueItemId/decline` — body: `{ teamName, assetId, comment? }`
- `POST /queue/:queueItemId/redirect` — body: `{ fromTeam, toTeam, assetId }`
- Validate queue item: exists, belongs to `req.user.id`, `workflow_type = 'CARD'`, `status = 'pending'`; return 404 if not found/wrong user/wrong type, 400 if not pending
- Validate required fields: `teamName` + `assetId` for confirm/decline; `fromTeam` + `toTeam` + `assetId` for redirect; return 400 if missing
- Two-step flow: call `getOwner(assetId)` → extract `update_token` from `owner.update_token` → call mutation with token
- On success: update queue item `status = 'complete'`, return `{ success: true, cardResponse }`
- On failure: leave queue item as `pending`, return error
- _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 5.10, 5.11, 5.12, 5.13, 5.14, 5.15_
- [x] 4.4 Implement error handling for CARD API responses
- Map token endpoint errors: 401 → 401 auth failed, 403 → 403 access denied, 525 → 502 LDAP error
- Map API call errors: 401 after retry → 401 token expired, 403 → 403 insufficient permissions
- Catch unhandled errors → 502 with `{ error: 'CARD API request failed.', details }`
- Log all errors with `[card-api]` prefix via `console.error`
- _Requirements: 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 8.10_
- [x] 4.5 Implement audit logging for all CARD actions
- `card_confirm`: entityType `ivanti_todo_queue`, entityId = queue item ID, details = `{ assetId, teamName, comment, cardStatus }`
- `card_decline`: same pattern with decline details
- `card_redirect`: details = `{ assetId, fromTeam, toTeam, cardStatus }`
- `card_search`: entityType `card_asset`, entityId = team name, details = `{ disposition, resultCount }`
- `card_action_failed`: details = `{ actionType, assetId, error, cardStatus }`
- All entries include `userId`, `username`, `ipAddress`; use fire-and-forget semantics
- _Requirements: 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7_
- [x] 5. Mount CARD route in server.js
- [x] 5.1 Add `const createCardApiRouter = require('./routes/cardApi');` import to server.js alongside existing route imports
- Mount with `app.use('/api/card', createCardApiRouter(db, requireAuth));` after the Atlas route mount
- _Requirements: 4.10_
- [x] 6. Checkpoint — Backend route verification
- Ensure all tests pass, ask the user if questions arise.
- [x] 7. Frontend CARD Action UI
- [x] 7.1 Add CARD teams fetch and session-level caching to ReportingPage
- Fetch `/api/card/status` on mount to check if CARD is configured
- Fetch `/api/card/teams` once per session and cache in component state
- Pass `cardConfigured`, `cardTeams` props down to `QueuePanel`
- _Requirements: 6.8, 6.9_
- [x] 7.2 Add CARD action buttons (Confirm, Decline, Redirect) to queue items in QueuePanel
- Render three action buttons on pending CARD queue items (`workflow_type === 'CARD'` and `status === 'pending'`)
- Disable buttons when CARD is not configured; show tooltip "CARD integration not configured"
- Style buttons to match existing queue item action patterns (compact, inline)
- _Requirements: 6.1, 6.8_
- [x] 7.3 Implement Confirm and Decline action forms
- On Confirm/Decline button click: show inline form with team selection dropdown (populated from cached teams list) and optional comment text field
- On form submit: POST to `/api/card/queue/:queueItemId/confirm` or `/decline` with `{ teamName, assetId: item.ip_address, comment }`
- While request is in flight: disable action buttons, show loading indicator on the queue item
- On success: update queue item status to `complete` in local state without full refresh
- On failure: display backend error message inline on the affected queue item
- _Requirements: 6.2, 6.3, 6.5, 6.6, 6.7_
- [x] 7.4 Implement Redirect action form
- On Redirect button click: show inline form with "From Team" dropdown and "To Team" dropdown (both from cached teams list)
- On form submit: POST to `/api/card/queue/:queueItemId/redirect` with `{ fromTeam, toTeam, assetId: item.ip_address }`
- Same loading/success/error handling as confirm/decline
- _Requirements: 6.4, 6.5, 6.6, 6.7_
- [x] 8. Frontend Asset Search Panel
- [x] 8.1 Create asset search interface accessible from the Ivanti Queue page
- Add a "CARD Asset Search" button/section in the queue panel or as a collapsible panel
- Include team selection dropdown (from cached teams) and disposition filter dropdown (`confirmed`, `unconfirmed`, `declined`, `candidate`)
- On search: GET `/api/card/teams/:teamName/assets?disposition=X&page_size=50`
- Display total asset count and results table with Asset_ID and identifying fields
- Add pagination controls when total exceeds page size (increment `page` param)
- Display error messages inline in the search results area on failure
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7_
- [x] 9. Checkpoint — Full integration verification
- Ensure all tests pass, ask the user if questions arise.
- [ ] 10. Property-based tests for CARD API correctness properties
- [ ]* 10.1 Write property test for isConfigured environment variable logic
- **Property 1: isConfigured reflects environment variable presence**
- For any combination of the three required env vars being present/non-empty or absent/empty, `isConfigured` is `true` iff all three are present and non-empty
- Create `backend/__tests__/card-isConfigured.property.test.js` using Jest + fast-check with 100+ iterations
- **Validates: Requirements 1.1, 3.3**
- [ ]* 10.2 Write property test for CARD API response shape consistency
- **Property 2: All CARD API responses have consistent shape**
- For any successful CARD API call, the resolved Promise contains `{ status: number, body: string }`
- Create `backend/__tests__/card-response-shape.property.test.js`
- **Validates: Requirements 1.7**
- [ ]* 10.3 Write property test for token acquisition error messages
- **Property 3: Token acquisition errors include status and body**
- For any non-success HTTP status and response body from the token endpoint, the rejected error message includes both the status code and body text
- Create `backend/__tests__/card-token-errors.property.test.js`
- **Validates: Requirements 2.7**
- [ ]* 10.4 Write property test for CARD API error status code forwarding
- **Property 4: CARD API error status codes are forwarded through proxy**
- For any 4xx/5xx status from CARD API on a proxied request, the route returns that same status code with a JSON error body
- Create `backend/__tests__/card-error-forwarding.property.test.js`
- **Validates: Requirements 4.9**
- [ ]* 10.5 Write property test for queue item validation on mutations
- **Property 5: Queue item validation rejects invalid states for mutations**
- For any mutation request where the queue item doesn't exist, wrong user, wrong workflow_type, or wrong status, the endpoint rejects with 404 or 400 without calling CARD API
- Create `backend/__tests__/card-queue-validation.property.test.js`
- **Validates: Requirements 5.4, 5.5, 5.6**
- [ ]* 10.6 Write property test for mutation input validation
- **Property 6: Mutation input validation enforces required fields**
- For any mutation request missing required fields (teamName/assetId for confirm/decline; fromTeam/toTeam/assetId for redirect), the endpoint rejects with 400
- Create `backend/__tests__/card-input-validation.property.test.js`
- **Validates: Requirements 5.11, 5.12, 5.13**
- [ ]* 10.7 Write property test for CARD mutation audit log entries
- **Property 7: CARD mutation audit entries contain required fields**
- For any mutation action, the audit log entry contains correct `action` name, `entityType`, `entityId`, `userId`, `username`, `ipAddress`, and `details` with `assetId` and CARD response status
- Create `backend/__tests__/card-audit-entries.property.test.js`
- **Validates: Requirements 9.1, 9.2, 9.3, 9.6**
- [x] 11. Final checkpoint — Ensure all tests pass
- Ensure all tests pass, ask the user if questions arise.
## Notes
- Tasks 13 are marked complete because `backend/helpers/cardApi.js`, `.env`/`.env.example`, and `backend/scripts/card-uat-test.js` are already built and UAT-tested
- Tasks marked with `*` are optional property-based tests and can be skipped for faster MVP
- Each task references specific requirements for traceability
- The backend route module (Task 4) follows the existing `atlas.js` route pattern exactly
- The frontend UI (Tasks 78) extends the existing `QueuePanel` in `ReportingPage.js`
- Property tests use Jest + fast-check matching the existing test pattern in `backend/__tests__/`