Compare commits
197 Commits
1d2a6b2e72
...
fix/jira-a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a179f19a1 | ||
|
|
4f960d0866 | ||
|
|
caa1d539cc | ||
|
|
b1069b1a05 | ||
|
|
1186f9f807 | ||
|
|
e13b18c169 | ||
|
|
05d47c91a8 | ||
|
|
b0c3daba01 | ||
|
|
675847de0c | ||
|
|
623b57ca06 | ||
|
|
06c6821d85 | ||
|
|
8da62f0f14 | ||
|
|
5a9dc007db | ||
|
|
3f9e1da2a3 | ||
|
|
7ea4ceb8df | ||
|
|
00a6f7ae0f | ||
|
|
69809955a9 | ||
|
|
6ee68f5521 | ||
|
|
5ffedad02f | ||
|
|
8bf8dc55dd | ||
|
|
53439b2af8 | ||
|
|
4c04c9870a | ||
|
|
e1b000870c | ||
|
|
f3ba322403 | ||
|
|
0bea387ac9 | ||
|
|
aa3ce3bae9 | ||
|
|
0cdaecf890 | ||
|
|
043c85cc69 | ||
|
|
6082721452 | ||
|
|
a214393723 | ||
|
|
f141fa58a1 | ||
|
|
e1b0236874 | ||
|
|
ed48522932 | ||
|
|
938dda400a | ||
|
|
732873dd6a | ||
|
|
0fe8e94d51 | ||
|
|
28bce28fc9 | ||
|
|
72fd79ea42 | ||
|
|
f63c286458 | ||
|
|
93c144576f | ||
|
|
fa3b045a2f | ||
|
|
4583d09750 | ||
|
|
75ac8c823a | ||
|
|
68e36b4bac | ||
|
|
d24b45b404 | ||
|
|
d64eb7eec4 | ||
|
|
6cb65fddc1 | ||
|
|
0ca83c6736 | ||
|
|
06268880da | ||
|
|
b4f0ddcb78 | ||
|
|
55e3e074a5 | ||
|
|
66bbeb84a5 | ||
|
|
4578f8cd85 | ||
|
|
5469a86e6e | ||
|
|
2b6db1f903 | ||
|
|
7c97bc3a84 | ||
|
|
835fbf26e7 | ||
|
|
c4aaeff2a1 | ||
|
|
df30430956 | ||
|
|
57f11c362b | ||
|
|
4df83d36dd | ||
|
|
0a7a7c2827 | ||
|
|
1963faf9b8 | ||
|
|
9b36a58959 | ||
|
|
690c30aac0 | ||
|
|
fc68097821 | ||
|
|
d9fdaf5cbb | ||
|
|
cb3da6980c | ||
|
|
ccc3576706 | ||
|
|
5405926550 | ||
|
|
328e48ea8c | ||
|
|
41f9c35586 | ||
|
|
729dada05c | ||
|
|
5d417edf82 | ||
|
|
03e60c9daf | ||
|
|
ee9403ab47 | ||
|
|
3d04cd393f | ||
|
|
382bc81a7e | ||
|
|
7302ece958 | ||
|
|
80d80c099f | ||
|
|
a2a43a8685 | ||
|
|
a711972054 | ||
|
|
8a6a3485e9 | ||
|
|
169a0d2337 | ||
|
|
c50fc5d8a8 | ||
|
|
e9e2c0961d | ||
|
|
d910af847e | ||
|
|
73fd747576 | ||
| 1ef57b0504 | |||
|
|
d1fe0bf455 | ||
|
|
3f7887eba6 | ||
|
|
9bd5a52661 | ||
|
|
2b4ec5d8e2 | ||
|
|
62592e9821 | ||
| 2fead2cfef | |||
| 7c0ba41514 | |||
| 9c6c03a518 | |||
| 0d48c109b3 | |||
| 18ad31228e | |||
| 3dcb91a1fc | |||
| 5102a2c5b4 | |||
| a0a8979c63 | |||
| 15ad207464 | |||
| b111273e5a | |||
| a7c74f625f | |||
| 8aef51b59a | |||
| d0087ba9b7 | |||
| 3d6062f3fa | |||
| 7af44608d0 | |||
| 3bb86e8369 | |||
| 4676279a72 | |||
| d3d86ddcf2 | |||
| 558c65807d | |||
| 518cb0a849 | |||
| b0adfa1bda | |||
| 7a2c56a11f | |||
| 89b1f57ef4 | |||
| 6bf6371e51 | |||
| 4d472b0aef | |||
| 887d11610e | |||
| 1520cc994b | |||
| 906066c7fa | |||
| b58bd0650a | |||
| ae04bc981e | |||
| 7314dc16cb | |||
| 602c75bf24 | |||
| 706ef19872 | |||
| 8392124df5 | |||
| fbe4333e9b | |||
| 07894709ba | |||
| 071aef96a1 | |||
| a9404ff82a | |||
| f24cdb5063 | |||
| 3e2546323e | |||
| b1a21e8771 | |||
| bc9e223ab7 | |||
| 2d1acca990 | |||
| 9893460b64 | |||
| 51b1f99b3a | |||
| 669396f635 | |||
| 8b3ea22fa0 | |||
| 75b8ecc61d | |||
| ade3cc25ad | |||
| 3fd6158eb3 | |||
| 5bbaaf5918 | |||
| 1f36d302ea | |||
| 8697ba4ef3 | |||
| d3806e8ce3 | |||
| 931c42faeb | |||
| ea3b72db5c | |||
| d63e7cc9b9 | |||
| 37e183543a | |||
| 337ffe6f35 | |||
| 08c8c8a2a1 | |||
| 4ed7721a71 | |||
| 3fb20c147d | |||
| f2e6069c08 | |||
| c89404cf26 | |||
| af7a5becef | |||
| 7145117518 | |||
| 30739dc162 | |||
| b0d2f915bd | |||
| 112eb8dac1 | |||
| 3b37646b6d | |||
| 241ff16bb4 | |||
| 0e89251bac | |||
| fa9f4229a6 | |||
| eea226a9d5 | |||
| 79a1a23002 | |||
| 6fda7de7a3 | |||
| 0d67a99c7e | |||
| bf3d01becf | |||
| 9384ded04f | |||
| 0c9c3b5514 | |||
| 4a50cd100b | |||
| c22a3a70ab | |||
| 626d0cac3a | |||
| ba4d16396c | |||
| 83d944fa70 | |||
| 26abd55e0f | |||
| eae4594baf | |||
| 84803a353e | |||
| d520c4ae41 | |||
| da109a6f8b | |||
| 260ae48f77 | |||
| fbdf05392a | |||
| 1a578b23c1 | |||
| 41c8a1ef27 | |||
| 8947a2864d | |||
| 792467930d | |||
| 1a6b51dea3 | |||
| 836a9f3774 | |||
| 788ad389c4 | |||
| 38dcbb1122 | |||
| 696569e6c7 | |||
| da14c92d98 | |||
| 3eb608617c |
BIN
.compliance-staging/.gitkeep
Normal file
BIN
.compliance-staging/.gitkeep
Normal file
Binary file not shown.
84
.gitea/issue_template/enhancement.yaml
Normal file
84
.gitea/issue_template/enhancement.yaml
Normal file
@@ -0,0 +1,84 @@
|
||||
name: Enhancement
|
||||
about: Suggest an improvement to an existing feature or functionality
|
||||
title: "[Enhancement] "
|
||||
labels:
|
||||
- kind/enhancement
|
||||
- status/triage
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for taking the time to suggest an improvement! This template is for enhancements to **existing** features. If you'd like to request a brand new feature, please use the Feature Request template instead.
|
||||
|
||||
- type: textarea
|
||||
id: current-behavior
|
||||
attributes:
|
||||
label: Current Behavior
|
||||
description: Describe how the existing feature currently works.
|
||||
placeholder: "Currently, when I do X, it works like..."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposed-improvement
|
||||
attributes:
|
||||
label: Proposed Improvement
|
||||
description: Describe how you'd like the existing feature to be improved.
|
||||
placeholder: "I'd like it to also do Y, or behave differently by..."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: use-case
|
||||
attributes:
|
||||
label: Use Case
|
||||
description: Why would this improvement be valuable? What problem does it solve?
|
||||
placeholder: "This would help because..."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area of the Application
|
||||
description: Which part of the application does this enhancement relate to?
|
||||
options:
|
||||
- Dashboard / CVE List
|
||||
- CVE Details
|
||||
- Document Management
|
||||
- User Management
|
||||
- Authentication
|
||||
- Audit Logging
|
||||
- API
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: priority
|
||||
attributes:
|
||||
label: Priority
|
||||
description: How important is this enhancement to your workflow?
|
||||
options:
|
||||
- Nice to have
|
||||
- Important
|
||||
- Critical
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives or Workarounds
|
||||
description: Are there any current workarounds or alternative approaches you've considered?
|
||||
placeholder: "Currently I work around this by..."
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: Additional Context
|
||||
description: Add any other context, screenshots, or mockups about the enhancement here.
|
||||
validations:
|
||||
required: false
|
||||
32
.gitignore
vendored
32
.gitignore
vendored
@@ -37,3 +37,35 @@ frontend.pid
|
||||
|
||||
# Temporary files
|
||||
backend/uploads/temp/
|
||||
feature_request*.md
|
||||
|
||||
# Planning docs
|
||||
docs/aeo-compliance-ui-plan.md
|
||||
docs/aeo-compliance-wireframe.md
|
||||
|
||||
# AI tooling config
|
||||
.claude/
|
||||
ai_notes.md
|
||||
ai_status.md
|
||||
backend/add_vendor_to_documents.js
|
||||
backend/fix_multivendor_constraint.js
|
||||
backend/server.js-backup
|
||||
backend/setup.js-backup
|
||||
|
||||
# Compliance staging — keep folder, ignore contents
|
||||
.compliance-staging/*
|
||||
!.compliance-staging/.gitkeep
|
||||
|
||||
# Kiro agents (local only)
|
||||
.kiro/agents/
|
||||
|
||||
# Kiro implementation summary (internal only)
|
||||
docs/kiro-implementation-summary.md
|
||||
|
||||
# Diagnostic scripts (troubleshooting only)
|
||||
backend/scripts/drift-check.js
|
||||
backend/scripts/bu-reassignment-check.js
|
||||
backend/scripts/export-reassigned-findings.js
|
||||
|
||||
# Investigation exports
|
||||
docs/reassigned-findings-*.xlsx
|
||||
|
||||
121
.gitlab-ci.yml
Normal file
121
.gitlab-ci.yml
Normal file
@@ -0,0 +1,121 @@
|
||||
# =============================================================================
|
||||
# GitLab CI/CD Pipeline — STEAM Security Dashboard
|
||||
# =============================================================================
|
||||
#
|
||||
# Pipeline stages:
|
||||
# 1. install — install dependencies for backend and frontend
|
||||
# 2. lint — run linters / static checks
|
||||
# 3. test — run backend (Jest) and frontend (react-scripts) tests
|
||||
# 4. build — produce the production frontend bundle
|
||||
# 5. deploy — restart services on the local machine (manual trigger)
|
||||
#
|
||||
# Executor: shell (runs directly on dashboard-dev using system Node.js)
|
||||
# Uses cache (not artifacts) for node_modules to avoid upload size limits.
|
||||
# =============================================================================
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Global cache — persists node_modules between pipeline runs on this runner
|
||||
# ---------------------------------------------------------------------------
|
||||
cache:
|
||||
key: ${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- node_modules/
|
||||
- frontend/node_modules/
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stages run in order; jobs within a stage run in parallel
|
||||
# ---------------------------------------------------------------------------
|
||||
stages:
|
||||
- install
|
||||
- lint
|
||||
- test
|
||||
- build
|
||||
- deploy
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 1: Install dependencies
|
||||
# =============================================================================
|
||||
|
||||
install-backend:
|
||||
stage: install
|
||||
script:
|
||||
- npm install
|
||||
|
||||
install-frontend:
|
||||
stage: install
|
||||
script:
|
||||
- cd frontend
|
||||
- npm install
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 2: Lint / static analysis
|
||||
# =============================================================================
|
||||
|
||||
lint-frontend:
|
||||
stage: lint
|
||||
script:
|
||||
- cd frontend
|
||||
- npm install
|
||||
- npx eslint src/ --max-warnings 0
|
||||
allow_failure: true # non-blocking until the team cleans up existing warnings
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 3: Tests
|
||||
# =============================================================================
|
||||
|
||||
test-backend:
|
||||
stage: test
|
||||
script:
|
||||
- npm install
|
||||
- npx jest --ci --forceExit --detectOpenHandles backend/__tests__/
|
||||
timeout: 5 minutes
|
||||
|
||||
test-frontend:
|
||||
stage: test
|
||||
script:
|
||||
- cd frontend
|
||||
- npm install
|
||||
- CI=true npx react-scripts test --watchAll=false --ci --forceExit
|
||||
timeout: 5 minutes
|
||||
allow_failure: true # 2 test suites have pre-existing ESM/env issues — fix separately
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 4: Build the production frontend bundle
|
||||
# =============================================================================
|
||||
|
||||
build-frontend:
|
||||
stage: build
|
||||
script:
|
||||
- cd frontend
|
||||
- npm install
|
||||
- CI=false REACT_APP_API_BASE=/api REACT_APP_API_HOST="" npm run build
|
||||
artifacts:
|
||||
paths:
|
||||
- frontend/build/
|
||||
expire_in: 7 days
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 5: Deploy
|
||||
# =============================================================================
|
||||
# Since the runner IS the app server (dashboard-dev), deploy just restarts
|
||||
# the services locally. No SSH needed.
|
||||
#
|
||||
# Manual trigger only, and only from the main/master branch.
|
||||
# =============================================================================
|
||||
|
||||
deploy:
|
||||
stage: deploy
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "master"
|
||||
when: manual
|
||||
environment:
|
||||
name: production
|
||||
script:
|
||||
- echo "Deploying on dashboard-dev..."
|
||||
- cd /home/cve-dashboard
|
||||
- git pull origin ${CI_COMMIT_BRANCH}
|
||||
- npm install
|
||||
- cd frontend && npm install && npm run build && cd ..
|
||||
- ./stop-servers.sh || true
|
||||
- ./start-servers.sh
|
||||
- echo "Deploy complete."
|
||||
35
.gitlab/issue_templates/Bug Report.md
Normal file
35
.gitlab/issue_templates/Bug Report.md
Normal file
@@ -0,0 +1,35 @@
|
||||
<!-- Labels: kind/bug, status/triage -->
|
||||
|
||||
Please provide as much detail as possible so we can reproduce and fix the issue!
|
||||
|
||||
## Description
|
||||
|
||||
<!-- What is currently happening? -->
|
||||
|
||||
|
||||
|
||||
## Steps to Reproduce
|
||||
|
||||
<!--
|
||||
1. Go to '...'
|
||||
2. Click on '...'
|
||||
3. See error
|
||||
-->
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
## Environment
|
||||
|
||||
<!-- Which browser/OS are you using? (e.g., Chrome on Windows 11) -->
|
||||
|
||||
|
||||
|
||||
## Relevant Log Output
|
||||
|
||||
<!-- Please paste any error logs or console output here. -->
|
||||
|
||||
```
|
||||
(paste logs here)
|
||||
```
|
||||
27
.gitlab/issue_templates/Feature Request.md
Normal file
27
.gitlab/issue_templates/Feature Request.md
Normal file
@@ -0,0 +1,27 @@
|
||||
<!-- Labels: kind/feature, status/triage -->
|
||||
|
||||
Thanks for taking the time to suggest a new feature!
|
||||
|
||||
## Is your feature request related to a problem?
|
||||
|
||||
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
|
||||
|
||||
|
||||
|
||||
## Describe the solution you'd like
|
||||
|
||||
<!-- A clear and concise description of what you want to happen. -->
|
||||
|
||||
|
||||
|
||||
## Describe alternatives you've considered
|
||||
|
||||
<!-- A clear and concise description of any alternative solutions or features you've considered. -->
|
||||
|
||||
|
||||
|
||||
## Additional context
|
||||
|
||||
<!-- Add any other context or screenshots about the feature request here. -->
|
||||
|
||||
|
||||
16
.kiro/hooks/check-component-conventions.kiro.hook
Normal file
16
.kiro/hooks/check-component-conventions.kiro.hook
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Check Component Conventions",
|
||||
"description": "On save of files in frontend/src/components/, verifies the component follows project conventions and flags deviations as inline comments.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "fileEdited",
|
||||
"patterns": [
|
||||
"frontend/src/components/**/*.js"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "Review the saved component file and verify it follows these project conventions:\n\n1. Functional component with hooks (no class components)\n2. Uses Lucide icons for iconography (not raw SVGs or other icon libraries)\n3. Uses inline styles or existing CSS classes from App.css (no CSS modules, no styled-components)\n4. Fetches data with fetch() using relative API paths and credentials: 'include' (no axios, no absolute URLs)\n5. Handles loading and error states when fetching data\n\nFor any deviations found, add inline comments in the code flagging the issue, e.g. // ⚠️ CONVENTION: Use lucide-react icons instead of raw SVGs\n\nOnly flag actual deviations. Do not modify working logic or refactor the component."
|
||||
}
|
||||
}
|
||||
13
.kiro/hooks/compliance-schema-watcher.kiro.hook
Normal file
13
.kiro/hooks/compliance-schema-watcher.kiro.hook
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Compliance Schema Watcher",
|
||||
"description": "Manually triggered before uploading a compliance xlsx to the dashboard. Diffs the xlsx structure against the parser's hand-maintained dicts (METRIC_CATEGORIES, CORE_COLS, SKIP_SHEETS) and flags anything that would cause silent data loss or misclassification. Prompts for the xlsx path and report mode.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "userTriggered"
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "You are the Compliance Schema Watcher agent. Follow the instructions in `.kiro/agents/compliance-schema-watcher.md` exactly.\n\nAsk the user to provide the following two inputs:\n\n1. **Path to the xlsx file:** Absolute path, or a filename to look for in `.compliance-staging/` then `~/Downloads/`. Example: `.compliance-staging/NTS_AEO_2026_04_15.xlsx`\n2. **Mode:** \"report only\" (surface drift findings in chat, no file edits) or \"report + propose edits\" (surface drift and draft specific dict changes for `backend/scripts/parse_compliance_xlsx.py`)\n\nOnce you have both inputs, follow the full schema drift workflow described in `.kiro/agents/compliance-schema-watcher.md`: resolve the file path, read the parser dicts, run the helper script to extract xlsx structure, diff against the parser's expectations, and output a categorised report with a pre-upload verdict."
|
||||
}
|
||||
}
|
||||
13
.kiro/hooks/doc-review-trigger.kiro.hook
Normal file
13
.kiro/hooks/doc-review-trigger.kiro.hook
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Doc Review",
|
||||
"description": "Manually triggered after merging to master. Reads the recent git diff, classifies the changes, and proposes documentation updates following the doc-updater decision tree and doc-standards.md conventions.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "userTriggered"
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "Run a documentation review against the latest changes on master. Follow these steps exactly:\n\n1. Run `git log --oneline -10` to see recent commits. If any commit message contains `[skip-docs]`, stop and report NO_DOC_UPDATE_NEEDED.\n\n2. Run `git diff HEAD~1 --stat` to get the list of changed files, then `git diff HEAD~1` to get the full diff. If the diff is larger than 500 lines, report NEEDS_HUMAN_REVIEW with a summary of which areas likely need docs.\n\n3. Read `.kiro/agents/doc-updater.md` for the full decision tree and `.kiro/steering/doc-standards.md` for formatting conventions.\n\n4. Follow the doc-updater decision tree: triage the change, decide if docs need updating, survey existing docs (README.md, docs/ folder), and propose surgical edits.\n\n5. For any proposed changes, apply them directly to the doc files. Only touch README.md and files under docs/. Never touch code files.\n\n6. After applying changes, output the SUMMARY block from the decision tree so Jordan can review what was changed and why."
|
||||
}
|
||||
}
|
||||
13
.kiro/hooks/ivanti-api-debugger.kiro.hook
Normal file
13
.kiro/hooks/ivanti-api-debugger.kiro.hook
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Ivanti API Debugger",
|
||||
"description": "Manually triggered when debugging a failing Ivanti API call. Prompts for the endpoint, request payload, and error response, then invokes the ivanti-api-debugger agent to diagnose the issue and update ivanti-api-reference.md with any findings.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "userTriggered"
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "You are the Ivanti API Debugger agent. Follow the instructions in `.kiro/agents/ivanti-api-debugger.md` exactly.\n\nAsk the user to provide the following (one clarifying question, not five — accept whatever they paste and infer the rest):\n\n1. The failing endpoint or route — either the Ivanti API path (e.g. `/workflowBatch/falsePositive/request`) or the backend route file/handler that makes the call (e.g. `backend/routes/ivantiWorkflows.js`)\n2. The request payload they sent (curl, JSON body, or code snippet)\n3. The response or error they got back (HTTP status, response body, or error message)\n\nOnce you have that context, follow the full diagnostic workflow described in `.kiro/agents/ivanti-api-debugger.md`: read the relevant route/service code, cross-reference `docs/ivanti-api-reference.md`, check for common Ivanti failure modes, form a hypothesis, and propose a concrete next request to try. If the user confirms a finding, update `docs/ivanti-api-reference.md` using its existing structure."
|
||||
}
|
||||
}
|
||||
16
.kiro/hooks/jsdoc-route-docs.kiro.hook
Normal file
16
.kiro/hooks/jsdoc-route-docs.kiro.hook
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "JSDoc Route Documentation",
|
||||
"description": "On save of files in backend/routes/, ensures every exported route handler has a JSDoc comment documenting the HTTP method, path, query parameters, request body shape, and response shape. Uses the existing documentation style in the file. Does not add comments to internal helper functions.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "fileEdited",
|
||||
"patterns": [
|
||||
"backend/routes/*.js"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "Review the saved route file and ensure every exported route handler (e.g., router.get, router.post, router.put, router.patch, router.delete) has a JSDoc comment directly above it documenting: the HTTP method, the route path, any query parameters, the request body shape (if applicable), and the response shape. Match the existing documentation style already used in the file. Do NOT add JSDoc comments to internal helper functions that are not route handlers. Only add missing documentation — do not modify or remove existing JSDoc comments that are already correct."
|
||||
}
|
||||
}
|
||||
13
.kiro/hooks/security-audit-tracker.kiro.hook
Normal file
13
.kiro/hooks/security-audit-tracker.kiro.hook
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Security Audit Tracker",
|
||||
"description": "Manually triggered to scan the codebase for security issues and maintain a living audit tracker document. Prompts for scan scope (full repo or specific path) and mode (report only or report + update tracker). Invokes the security-audit-tracker agent for static analysis and doc tracking.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "userTriggered"
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "You are the Security Audit Tracker agent. Follow the instructions in `.kiro/agents/security-audit-tracker.md` exactly.\n\nAsk the user to provide the following two inputs:\n\n1. **Scope:** \"full repo\" to scan the entire codebase, or a specific path/module to focus on (e.g. `backend/routes/`, `frontend/src/components/`, `backend/helpers/ivantiApi.js`)\n2. **Mode:** \"scan only\" (report findings to chat, no file writes) or \"scan + update tracker\" (report findings and merge them into the tracker doc at `docs/security-audit-tracker.md`)\n\nOnce you have both inputs, follow the full diagnostic and tracking workflow described in `.kiro/agents/security-audit-tracker.md`: determine scope, check for the tracker doc (create it if missing), scan for the security failure modes listed in the agent spec, cross-reference against previously tracked findings, and output a prioritised report. In \"scan + update tracker\" mode, also merge findings into the tracker doc and update its metadata."
|
||||
}
|
||||
}
|
||||
16
.kiro/hooks/sqlite3-safety-check.kiro.hook
Normal file
16
.kiro/hooks/sqlite3-safety-check.kiro.hook
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "SQLite3 Safety Check",
|
||||
"description": "On save of files containing db.run, db.get, or db.all, verifies all sqlite3 calls use parameterized queries (? placeholders) instead of string concatenation, handle the error parameter first in every callback, and use hardcoded table/column names. Flags violations as inline comments prefixed with \"// FIXME:\".",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "fileEdited",
|
||||
"patterns": [
|
||||
"backend/**/*.js"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "The saved file may contain sqlite3 calls (db.run, db.get, or db.all). Scan the file and verify all sqlite3 calls follow these rules:\n\n1. Parameterized queries only: All SQL queries must use ? placeholders for dynamic values. Never use string concatenation or template literals to inject values into SQL strings.\n2. Error-first callbacks: Every callback passed to db.run, db.get, or db.all must handle the error parameter first (e.g., `if (err) { ... }`).\n3. Hardcoded table/column names: All table and column names in SQL strings must be hardcoded string literals, never sourced from variables or parameters.\n\nIf the file does not contain any db.run, db.get, or db.all calls, skip the check silently.\n\nFor any violations found, add an inline comment on the offending line prefixed with \"// FIXME:\" describing the specific issue. Do not modify any other code."
|
||||
}
|
||||
}
|
||||
16
.kiro/hooks/verify-migration-pattern.kiro.hook
Normal file
16
.kiro/hooks/verify-migration-pattern.kiro.hook
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Verify Migration Pattern",
|
||||
"description": "On save or create of migration files (migrate*.js), verifies the migration follows existing project patterns: uses CREATE TABLE IF NOT EXISTS, includes explicit column types, adds appropriate indexes, and wraps multiple statements in transactions. Compares against existing migrations for style consistency.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "fileEdited",
|
||||
"patterns": [
|
||||
"**/migrate*.js"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "A migration file was just saved. Review the edited file and verify it follows the existing migration pattern used in this project. Check the existing migrations in backend/migrations/ for reference, then verify the edited file:\n\n1. Uses CREATE TABLE IF NOT EXISTS (not just CREATE TABLE)\n2. Includes all columns with explicit SQLite types (TEXT, INTEGER, REAL, etc.)\n3. Adds appropriate indexes for foreign keys and frequently queried columns\n4. Wraps operations in a serialized transaction (db.serialize + db.run(\"BEGIN TRANSACTION\") / COMMIT) if there are multiple statements\n5. Follows the same callback-based db.run() style as existing migrations\n6. Includes proper error handling\n\nCompare the file against the existing migrations in backend/migrations/ for style consistency. Report any deviations or issues found."
|
||||
}
|
||||
}
|
||||
16
.kiro/hooks/verify-new-migration.kiro.hook
Normal file
16
.kiro/hooks/verify-new-migration.kiro.hook
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Verify New Migration",
|
||||
"description": "On creation of new migration files in backend/migrations/, verifies the migration follows existing project patterns: uses CREATE TABLE IF NOT EXISTS, includes explicit column types, adds appropriate indexes, and wraps multiple statements in transactions.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "fileCreated",
|
||||
"patterns": [
|
||||
"**/migrations/*.js"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"type": "askAgent",
|
||||
"prompt": "A new migration file was just created. Review the file and verify it follows the existing migration pattern used in this project. Check the existing migrations in backend/migrations/ for reference, then verify the new file:\n\n1. Uses CREATE TABLE IF NOT EXISTS (not just CREATE TABLE)\n2. Includes all columns with explicit SQLite types (TEXT, INTEGER, REAL, etc.)\n3. Adds appropriate indexes for foreign keys and frequently queried columns\n4. Wraps operations in a serialized transaction (db.serialize + db.run(\"BEGIN TRANSACTION\") / COMMIT) if there are multiple statements\n5. Follows the same callback-based db.run() style as existing migrations\n6. Includes proper error handling\n\nCompare the file against the existing migrations in backend/migrations/ for style consistency. Report any deviations or issues found."
|
||||
}
|
||||
}
|
||||
1
.kiro/specs/admin-page-overhaul/.config.kiro
Normal file
1
.kiro/specs/admin-page-overhaul/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "30e46443-e636-4df1-bb98-886f403b2e32", "workflowType": "requirements-first", "specType": "feature"}
|
||||
423
.kiro/specs/admin-page-overhaul/design.md
Normal file
423
.kiro/specs/admin-page-overhaul/design.md
Normal file
@@ -0,0 +1,423 @@
|
||||
# Design Document: Admin Page Overhaul
|
||||
|
||||
## Overview
|
||||
|
||||
The Admin Page Overhaul replaces the current inline `UserManagement` modal rendering on the admin page with a full-page, themed admin panel. The new `AdminPage` component follows the same layout conventions as `CompliancePage`, `ExportsPage`, and `KnowledgeBasePage` — a top-level page component rendered in the main content area of `App.js` when `currentPage === 'admin'`.
|
||||
|
||||
The page consolidates three admin functions into a single tabbed interface:
|
||||
|
||||
1. **User Management** — themed table with inline add/edit forms, group badges, and active status toggles
|
||||
2. **Audit Log** — paginated, filterable log table with action-type badges and date range filters
|
||||
3. **System Info** — stat cards showing user counts, audit log totals, and recent activity
|
||||
|
||||
All sections use the dark tactical intelligence theme defined in `DESIGN_SYSTEM.md` and `App.css` — `intel-card` containers, `intel-button` controls, `intel-input` form fields, `status-badge` action labels, and `stat-card` stat displays.
|
||||
|
||||
### Design Decisions
|
||||
|
||||
- **New component, not a wrapper.** The existing `UserManagement.js` and `AuditLog.js` are white-background modals with Tailwind utility classes. Wrapping them would create visual inconsistency. The `AdminPage` component builds themed versions of both panels from scratch, reusing the same backend API endpoints.
|
||||
- **Existing modals preserved.** The `UserMenu` quick-access links ("Manage Users", "Audit Log") continue to open the existing modal components. This keeps the quick-access workflow intact while the admin page provides the full-featured experience.
|
||||
- **No new backend endpoints.** All data comes from existing routes: `GET /api/users`, `POST/PATCH/DELETE /api/users/:id`, `GET /api/audit-logs`, `GET /api/audit-logs/actions`.
|
||||
- **Inline styles + App.css classes.** Follows the project convention of defining style constants in the component file and referencing `App.css` classes (`intel-card`, `intel-button`, `data-row`, etc.) where available.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[App.js] -->|currentPage === 'admin' && isAdmin| B[AdminPage]
|
||||
B --> C[Tab Navigation]
|
||||
C -->|"User Management"| D[UserManagementPanel]
|
||||
C -->|"Audit Log"| E[AuditLogPanel]
|
||||
C -->|"System Info"| F[SystemInfoPanel]
|
||||
|
||||
D -->|GET /api/users| G[Backend: users.js]
|
||||
D -->|POST /api/users| G
|
||||
D -->|PATCH /api/users/:id| G
|
||||
D -->|DELETE /api/users/:id| G
|
||||
|
||||
E -->|GET /api/audit-logs| H[Backend: auditLog.js]
|
||||
E -->|GET /api/audit-logs/actions| H
|
||||
|
||||
F -->|GET /api/users| G
|
||||
F -->|GET /api/audit-logs?limit=10| H
|
||||
```
|
||||
|
||||
### Component Hierarchy
|
||||
|
||||
```
|
||||
AdminPage
|
||||
├── PageHeader (title + accent glow)
|
||||
├── TabNavigation (User Management | Audit Log | System Info)
|
||||
├── UserManagementPanel
|
||||
│ ├── AddUserButton / InlineForm
|
||||
│ ├── UserTable
|
||||
│ │ └── UserRow (group badge, status toggle, edit/delete actions)
|
||||
│ ├── ErrorBanner
|
||||
│ └── SuccessToast
|
||||
├── AuditLogPanel
|
||||
│ ├── FilterBar (username, action, entity type, start date, end date)
|
||||
│ ├── LogTable
|
||||
│ │ └── LogRow (timestamp, user, action badge, entity, details, IP)
|
||||
│ ├── Pagination
|
||||
│ ├── EmptyState
|
||||
│ └── ErrorBanner
|
||||
└── SystemInfoPanel
|
||||
├── StatCards (total users, active users, audit entries, recent logins)
|
||||
└── RecentActivityList (10 most recent audit entries)
|
||||
```
|
||||
|
||||
### Data Flow
|
||||
|
||||
1. `App.js` renders `<AdminPage />` when `currentPage === 'admin'` and `isAdmin()` returns true. Non-admin users are redirected to home.
|
||||
2. `AdminPage` manages the active tab in local state (default: `'users'`).
|
||||
3. Each panel fetches its own data on mount using `fetch()` with `credentials: 'include'`.
|
||||
4. Mutations (create, update, delete user) trigger a re-fetch of the user list. Success/error feedback is shown inline.
|
||||
5. Audit log panel manages its own pagination and filter state, re-fetching on filter apply or page change.
|
||||
6. System info panel fetches user list and recent audit logs on mount, computing derived stats client-side.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### AdminPage (main component)
|
||||
|
||||
```javascript
|
||||
// frontend/src/components/pages/AdminPage.js
|
||||
export default function AdminPage() {
|
||||
// Props: none (reads auth context internally)
|
||||
// State:
|
||||
// activeTab: 'users' | 'audit' | 'system'
|
||||
// Renders: PageHeader, TabNavigation, conditional panel
|
||||
}
|
||||
```
|
||||
|
||||
### TabNavigation
|
||||
|
||||
```javascript
|
||||
// Internal to AdminPage
|
||||
// Props:
|
||||
// activeTab: string
|
||||
// onTabChange: (tab: string) => void
|
||||
// Tabs: [
|
||||
// { id: 'users', label: 'User Management', icon: Shield },
|
||||
// { id: 'audit', label: 'Audit Log', icon: Clock },
|
||||
// { id: 'system', label: 'System Info', icon: Activity },
|
||||
// ]
|
||||
```
|
||||
|
||||
Styling: monospace uppercase text, `--intel-accent` border and background on active tab, transparent with muted text on inactive tabs. Matches the tab pattern used in `CompliancePage` (team tabs).
|
||||
|
||||
### UserManagementPanel
|
||||
|
||||
```javascript
|
||||
// Internal to AdminPage
|
||||
// State:
|
||||
// users: Array<User>
|
||||
// loading: boolean
|
||||
// error: string | null
|
||||
// showForm: boolean
|
||||
// editingUser: User | null
|
||||
// formData: { username, email, password, group }
|
||||
// formError: string
|
||||
// successMessage: string
|
||||
//
|
||||
// API calls:
|
||||
// GET /api/users → fetch all users
|
||||
// POST /api/users → create user
|
||||
// PATCH /api/users/:id → update user (fields, group, is_active)
|
||||
// DELETE /api/users/:id → delete user
|
||||
//
|
||||
// Group badge colors (themed):
|
||||
// Admin: --intel-danger (#EF4444)
|
||||
// Standard_User: --intel-accent (#0EA5E9)
|
||||
// Leadership: --intel-warning (#F59E0B)
|
||||
// Read_Only: --text-muted (#94A3B8)
|
||||
```
|
||||
|
||||
### AuditLogPanel
|
||||
|
||||
```javascript
|
||||
// Internal to AdminPage
|
||||
// State:
|
||||
// logs: Array<AuditLogEntry>
|
||||
// loading: boolean
|
||||
// error: string | null
|
||||
// pagination: { page, limit, total, totalPages }
|
||||
// filters: { user, action, entityType, startDate, endDate }
|
||||
// actions: string[] (populated from /api/audit-logs/actions)
|
||||
//
|
||||
// API calls:
|
||||
// GET /api/audit-logs?page=&limit=25&user=&action=&entityType=&startDate=&endDate=
|
||||
// GET /api/audit-logs/actions
|
||||
//
|
||||
// Action badge colors (themed):
|
||||
// login/logout: --intel-success (#10B981)
|
||||
// *_create: --intel-accent (#0EA5E9)
|
||||
// *_update/*_edit: --intel-warning (#F59E0B)
|
||||
// *_delete: --intel-danger (#EF4444)
|
||||
// default: --text-muted (#94A3B8)
|
||||
```
|
||||
|
||||
### SystemInfoPanel
|
||||
|
||||
```javascript
|
||||
// Internal to AdminPage
|
||||
// State:
|
||||
// users: Array<User>
|
||||
// recentLogs: Array<AuditLogEntry>
|
||||
// loading: boolean
|
||||
// errors: { users: string | null, logs: string | null }
|
||||
//
|
||||
// Derived stats:
|
||||
// totalUsers: users.length
|
||||
// activeUsers: users.filter(u => u.is_active).length
|
||||
// recentLogins: users.filter(u => u.last_login && withinLast7Days(u.last_login)).length
|
||||
// totalAuditEntries: fetched from audit-logs pagination.total
|
||||
//
|
||||
// API calls:
|
||||
// GET /api/users
|
||||
// GET /api/audit-logs?limit=10&page=1
|
||||
```
|
||||
|
||||
### Integration with App.js
|
||||
|
||||
```javascript
|
||||
// In App.js, replace:
|
||||
// {currentPage === 'admin' && isAdmin() && (
|
||||
// <div className="space-y-6">
|
||||
// <UserManagement onClose={() => setCurrentPage('home')} />
|
||||
// </div>
|
||||
// )}
|
||||
//
|
||||
// With:
|
||||
// {currentPage === 'admin' && isAdmin() && <AdminPage />}
|
||||
// {currentPage === 'admin' && !isAdmin() && /* redirect to home */}
|
||||
//
|
||||
// Keep existing modal triggers:
|
||||
// {showUserManagement && <UserManagement onClose={...} />}
|
||||
// {showAuditLog && <AuditLog onClose={...} />}
|
||||
```
|
||||
|
||||
## Data Models
|
||||
|
||||
### User (from GET /api/users)
|
||||
|
||||
```javascript
|
||||
{
|
||||
id: number,
|
||||
username: string,
|
||||
email: string,
|
||||
group: 'Admin' | 'Standard_User' | 'Leadership' | 'Read_Only',
|
||||
is_active: 0 | 1,
|
||||
created_at: string, // ISO datetime
|
||||
last_login: string | null // ISO datetime
|
||||
}
|
||||
```
|
||||
|
||||
### AuditLogEntry (from GET /api/audit-logs)
|
||||
|
||||
```javascript
|
||||
{
|
||||
id: number,
|
||||
user_id: number,
|
||||
username: string,
|
||||
action: string, // e.g. 'login', 'user_create', 'cve_delete'
|
||||
entity_type: string, // e.g. 'auth', 'user', 'cve', 'document'
|
||||
entity_id: string | null,
|
||||
details: string | null, // JSON string
|
||||
ip_address: string | null,
|
||||
created_at: string // ISO datetime
|
||||
}
|
||||
```
|
||||
|
||||
### AuditLogPagination (from GET /api/audit-logs response)
|
||||
|
||||
```javascript
|
||||
{
|
||||
logs: AuditLogEntry[],
|
||||
pagination: {
|
||||
page: number,
|
||||
limit: number,
|
||||
total: number,
|
||||
totalPages: number
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Tab Configuration
|
||||
|
||||
```javascript
|
||||
const TABS = [
|
||||
{ id: 'users', label: 'User Management', icon: Shield },
|
||||
{ id: 'audit', label: 'Audit Log', icon: Clock },
|
||||
{ id: 'system', label: 'System Info', icon: Activity },
|
||||
];
|
||||
```
|
||||
|
||||
### Group Badge Theme Map
|
||||
|
||||
```javascript
|
||||
const GROUP_BADGE_THEMED = {
|
||||
Admin: { bg: 'rgba(239,68,68,0.15)', border: '#EF4444', text: '#FCA5A5' },
|
||||
Standard_User: { bg: 'rgba(14,165,233,0.15)', border: '#0EA5E9', text: '#7DD3FC' },
|
||||
Leadership: { bg: 'rgba(245,158,11,0.15)', border: '#F59E0B', text: '#FCD34D' },
|
||||
Read_Only: { bg: 'rgba(148,163,184,0.15)', border: '#94A3B8', text: '#CBD5E1' },
|
||||
};
|
||||
```
|
||||
|
||||
### Action Badge Theme Map
|
||||
|
||||
```javascript
|
||||
const ACTION_BADGE_THEMED = {
|
||||
login: { bg: 'rgba(16,185,129,0.15)', border: '#10B981', text: '#6EE7B7' },
|
||||
logout: { bg: 'rgba(148,163,184,0.15)', border: '#94A3B8', text: '#CBD5E1' },
|
||||
login_failed: { bg: 'rgba(239,68,68,0.15)', border: '#EF4444', text: '#FCA5A5' },
|
||||
user_create: { bg: 'rgba(14,165,233,0.15)', border: '#0EA5E9', text: '#7DD3FC' },
|
||||
user_update: { bg: 'rgba(245,158,11,0.15)', border: '#F59E0B', text: '#FCD34D' },
|
||||
user_delete: { bg: 'rgba(239,68,68,0.15)', border: '#EF4444', text: '#FCA5A5' },
|
||||
cve_create: { bg: 'rgba(14,165,233,0.15)', border: '#0EA5E9', text: '#7DD3FC' },
|
||||
cve_edit: { bg: 'rgba(245,158,11,0.15)', border: '#F59E0B', text: '#FCD34D' },
|
||||
cve_delete: { bg: 'rgba(239,68,68,0.15)', border: '#EF4444', text: '#FCA5A5' },
|
||||
document_upload: { bg: 'rgba(139,92,246,0.15)', border: '#8B5CF6', text: '#C4B5FD' },
|
||||
document_delete: { bg: 'rgba(239,68,68,0.15)', border: '#EF4444', text: '#FCA5A5' },
|
||||
};
|
||||
```
|
||||
|
||||
## 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: Group badge color mapping is total and correct
|
||||
|
||||
*For any* valid user group string (`Admin`, `Standard_User`, `Leadership`, `Read_Only`), the group badge styling function SHALL return a non-null object with `bg`, `border`, and `text` fields matching the themed color for that group. *For any* string that is not one of the four valid groups, the function SHALL return the default muted styling.
|
||||
|
||||
**Validates: Requirements 3.3**
|
||||
|
||||
### Property 2: Edit form population preserves user data
|
||||
|
||||
*For any* user object with arbitrary `username`, `email`, and `group` values, populating the edit form from that user SHALL result in `formData.username === user.username`, `formData.email === user.email`, and `formData.group === user.group`, with `formData.password` set to an empty string.
|
||||
|
||||
**Validates: Requirements 3.5**
|
||||
|
||||
### Property 3: Self-modification prevention
|
||||
|
||||
*For any* user list that contains the currently authenticated admin user, the admin user's own row SHALL have the group dropdown disabled and the active status toggle disabled. *For any* other user in the list, those controls SHALL be enabled.
|
||||
|
||||
**Validates: Requirements 3.8**
|
||||
|
||||
### Property 4: Action badge color mapping is total and correct
|
||||
|
||||
*For any* known audit log action string (from the set of defined actions: `login`, `logout`, `login_failed`, `user_create`, `user_update`, `user_delete`, `cve_create`, `cve_edit`, `cve_delete`, `document_upload`, `document_delete`), the action badge styling function SHALL return the correct themed color object. *For any* unknown action string, the function SHALL return the default muted styling.
|
||||
|
||||
**Validates: Requirements 4.4**
|
||||
|
||||
### Property 5: Applying filters resets pagination to page 1
|
||||
|
||||
*For any* combination of filter values (username text, action type, entity type, start date, end date) and *for any* current page number, applying the filters SHALL result in a fetch call with `page=1`.
|
||||
|
||||
**Validates: Requirements 4.7**
|
||||
|
||||
### Property 6: Recent login count computation
|
||||
|
||||
*For any* list of user objects with random `last_login` timestamps (including null values), the computed "recent logins" count SHALL equal the number of users whose `last_login` is non-null and falls within the last 7 days from the current time.
|
||||
|
||||
**Validates: Requirements 5.1**
|
||||
|
||||
### Property 7: Admin-only access control
|
||||
|
||||
*For any* user object, the admin page content SHALL be rendered if and only if `user.group === 'Admin'`. When `user.group` is any value other than `'Admin'`, the system SHALL redirect to the home page.
|
||||
|
||||
**Validates: Requirements 6.1, 6.2**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### User Management Panel
|
||||
|
||||
| Error Scenario | Handling |
|
||||
|---|---|
|
||||
| `GET /api/users` fails | Display error banner with `--intel-danger` styling. User table is hidden. Retry on next tab switch or manual refresh. |
|
||||
| `POST /api/users` fails (validation) | Display `formError` message below the form in danger color. Form remains open for correction. |
|
||||
| `POST /api/users` fails (409 conflict) | Display "Username or email already exists" in `formError`. |
|
||||
| `PATCH /api/users/:id` fails | Display inline error. Revert optimistic UI changes if any. |
|
||||
| `DELETE /api/users/:id` fails | Display alert with error message. User list unchanged. |
|
||||
| Self-demotion attempt | Group dropdown disabled for current user. Backend returns 400 if bypassed. |
|
||||
| Self-deactivation attempt | Toggle disabled for current user. Backend returns 400 if bypassed. |
|
||||
|
||||
### Audit Log Panel
|
||||
|
||||
| Error Scenario | Handling |
|
||||
|---|---|
|
||||
| `GET /api/audit-logs` fails | Display error banner with `--intel-danger` styling. Table hidden. |
|
||||
| `GET /api/audit-logs/actions` fails | Action filter dropdown shows no options. Non-critical — silently ignored. |
|
||||
| Invalid date range (start > end) | Client-side: no validation needed — backend handles gracefully by returning empty results. |
|
||||
| Empty result set | Display "No audit log entries found" message in `--text-muted` color. |
|
||||
|
||||
### System Info Panel
|
||||
|
||||
| Error Scenario | Handling |
|
||||
|---|---|
|
||||
| `GET /api/users` fails | Affected stat cards (total users, active users, recent logins) show "Unable to load" fallback text. |
|
||||
| `GET /api/audit-logs` fails | Audit entries stat card and recent activity list show "Unable to load" fallback. |
|
||||
| Partial failure (one endpoint fails) | Only the affected cards show fallback. Successfully loaded cards display normally. |
|
||||
|
||||
### Success Feedback
|
||||
|
||||
- Create user: green success toast "User created successfully" auto-dismisses after 2 seconds.
|
||||
- Update user: green success toast "User updated successfully" auto-dismisses after 2 seconds.
|
||||
- Delete user: green success toast "User deleted" auto-dismisses after 2 seconds.
|
||||
- Toggle active status: immediate UI update, no toast (inline visual feedback is sufficient).
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (Example-Based)
|
||||
|
||||
Unit tests cover specific rendering, interaction, and integration scenarios:
|
||||
|
||||
**AdminPage structure:**
|
||||
- Renders page header with "Admin Panel" title
|
||||
- Defaults to User Management tab on mount
|
||||
- Switches panels when tabs are clicked
|
||||
- Only renders when user is admin (access control)
|
||||
|
||||
**UserManagementPanel:**
|
||||
- Renders user table with all required columns
|
||||
- Displays themed group badges for each group type
|
||||
- Shows inline form when "Add User" is clicked
|
||||
- Populates form with user data when edit is clicked
|
||||
- Shows confirmation dialog on delete
|
||||
- Disables self-modification controls for current user
|
||||
- Displays error banner on API failure
|
||||
- Displays success toast on successful operations
|
||||
|
||||
**AuditLogPanel:**
|
||||
- Renders log table with all required columns
|
||||
- Displays themed action badges
|
||||
- Renders filter controls (username, action, entity type, dates)
|
||||
- Fetches page 1 when filters are applied
|
||||
- Navigates pages with pagination controls
|
||||
- Shows empty state when no results
|
||||
- Shows error banner on API failure
|
||||
|
||||
**SystemInfoPanel:**
|
||||
- Renders four stat cards with correct labels
|
||||
- Computes derived stats correctly from mock data
|
||||
- Shows recent activity list with up to 10 entries
|
||||
- Shows fallback message when an API call fails
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based tests use [fast-check](https://github.com/dubzzz/fast-check) to verify universal properties across generated inputs. Each test runs a minimum of 100 iterations.
|
||||
|
||||
| Property | Test Description | Tag |
|
||||
|---|---|---|
|
||||
| Property 1 | Generate random group strings (valid + invalid), verify badge function returns correct colors | Feature: admin-page-overhaul, Property 1: Group badge color mapping is total and correct |
|
||||
| Property 2 | Generate random user objects, verify edit form population matches user fields exactly | Feature: admin-page-overhaul, Property 2: Edit form population preserves user data |
|
||||
| Property 3 | Generate random user lists containing the current admin, verify self-edit controls are disabled | Feature: admin-page-overhaul, Property 3: Self-modification prevention |
|
||||
| Property 4 | Generate random action strings (known + unknown), verify badge function returns correct colors | Feature: admin-page-overhaul, Property 4: Action badge color mapping is total and correct |
|
||||
| Property 5 | Generate random filter states and current page numbers, verify fetch is called with page=1 | Feature: admin-page-overhaul, Property 5: Applying filters resets pagination to page 1 |
|
||||
| Property 6 | Generate random user lists with random last_login timestamps, verify recent login count matches manual computation | Feature: admin-page-overhaul, Property 6: Recent login count computation |
|
||||
| Property 7 | Generate random user objects with random groups, verify admin page renders iff group === 'Admin' | Feature: admin-page-overhaul, Property 7: Admin-only access control |
|
||||
|
||||
### Test Configuration
|
||||
|
||||
- **Library:** fast-check (JavaScript property-based testing)
|
||||
- **Runner:** Jest (via react-scripts test)
|
||||
- **Iterations:** Minimum 100 per property test (`fc.assert(property, { numRuns: 100 })`)
|
||||
- **Tag format:** Comment at top of each property test referencing the design property
|
||||
108
.kiro/specs/admin-page-overhaul/requirements.md
Normal file
108
.kiro/specs/admin-page-overhaul/requirements.md
Normal file
@@ -0,0 +1,108 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The STEAM Security Dashboard currently has an Admin page (`currentPage === 'admin'`) that renders the `UserManagement` modal component inline — the same modal triggered from the top-right `UserMenu`. The page does not follow the dashboard's dark "tactical intelligence" theme and provides no audit log viewing or other administrative capabilities. This feature overhauls the admin page into a dedicated, full-page admin panel that matches the design system and consolidates user management, audit log viewing, and system administration into a single cohesive interface accessible only to Admin-group users.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Admin_Page**: The full-page admin panel rendered when `currentPage === 'admin'`, replacing the current inline modal rendering
|
||||
- **Dashboard**: The STEAM Security Dashboard application
|
||||
- **Design_System**: The color palette, typography, component specs, and interaction patterns defined in `DESIGN_SYSTEM.md` and `App.css`
|
||||
- **Audit_Log_Panel**: The section of the Admin_Page that displays paginated, filterable audit log entries
|
||||
- **User_Management_Panel**: The section of the Admin_Page that displays the user list and provides create, edit, delete, and activate/deactivate operations
|
||||
- **Admin_User**: A user whose `user_group` is `Admin`
|
||||
- **Tab_Navigation**: The in-page navigation component that switches between Admin_Page sections (User Management, Audit Log, System Info)
|
||||
- **System_Info_Panel**: The section of the Admin_Page that displays system metadata such as active user count, recent login activity, and database statistics
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Admin Page Layout and Theme Compliance
|
||||
|
||||
**User Story:** As an admin, I want the admin page to follow the same dark tactical intelligence theme as the rest of the dashboard, so that the experience is visually consistent.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Admin_Page SHALL use the Design_System color palette — `--intel-darkest` for the page background, `--intel-dark` and `--intel-medium` for card backgrounds, and `--intel-accent` for interactive elements
|
||||
2. THE Admin_Page SHALL render as a full-page view within the main content area, matching the layout pattern used by other page components (CompliancePage, ExportsPage, KnowledgeBasePage)
|
||||
3. THE Admin_Page SHALL display a page header with the title "Admin Panel" styled in monospace uppercase with the accent text glow defined in the Design_System
|
||||
4. THE Admin_Page SHALL use `intel-card` styled containers for each content section, with the standard gradient backgrounds, border glow, and shadow depth defined in the Design_System
|
||||
5. THE Admin_Page SHALL use `intel-button` styled controls for all interactive buttons, with primary, danger, and success variants as appropriate
|
||||
6. THE Admin_Page SHALL use `intel-input` styled form fields for all text inputs, selects, and date pickers
|
||||
|
||||
### Requirement 2: Tab-Based Section Navigation
|
||||
|
||||
**User Story:** As an admin, I want to navigate between admin sections using tabs, so that I can quickly switch between user management, audit logs, and system information without leaving the page.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Admin_Page SHALL display a Tab_Navigation component with tabs for "User Management", "Audit Log", and "System Info"
|
||||
2. WHEN an Admin_User clicks a tab, THE Tab_Navigation SHALL switch the visible content section to the selected tab and visually indicate the active tab using the `--intel-accent` color
|
||||
3. THE Admin_Page SHALL default to the "User Management" tab when first loaded
|
||||
4. THE Tab_Navigation SHALL use monospace uppercase text with letter spacing consistent with the Design_System label typography
|
||||
|
||||
### Requirement 3: Themed User Management Panel
|
||||
|
||||
**User Story:** As an admin, I want to manage users directly within the themed admin page instead of a white modal overlay, so that user management feels integrated into the dashboard.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE User_Management_Panel SHALL display a table of all users with columns for username, email, group, active status, and last login
|
||||
2. THE User_Management_Panel SHALL style the user table with dark theme rows using `data-row` hover effects and `--text-primary` / `--text-secondary` text colors from the Design_System
|
||||
3. THE User_Management_Panel SHALL display group badges using severity-style badge coloring — Admin in danger color, Standard_User in accent color, Leadership in warning color, Read_Only in muted color
|
||||
4. WHEN an Admin_User clicks "Add User", THE User_Management_Panel SHALL display an inline form styled with `intel-input` fields and `intel-button` controls
|
||||
5. WHEN an Admin_User clicks the edit action on a user row, THE User_Management_Panel SHALL populate the inline form with that user's current data for editing
|
||||
6. WHEN an Admin_User clicks the delete action on a user row, THE User_Management_Panel SHALL display a confirmation prompt before sending the delete request
|
||||
7. WHEN an Admin_User toggles a user's active status, THE User_Management_Panel SHALL send a PATCH request and update the displayed status without a full page reload
|
||||
8. THE User_Management_Panel SHALL prevent an Admin_User from changing their own group or deactivating their own account
|
||||
9. IF a user management API request fails, THEN THE User_Management_Panel SHALL display an error message styled with the `--intel-danger` color
|
||||
|
||||
### Requirement 4: Themed Audit Log Panel
|
||||
|
||||
**User Story:** As an admin, I want to view audit logs in a themed, filterable table within the admin page, so that I can monitor system activity without opening a separate modal.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Audit_Log_Panel SHALL fetch and display paginated audit log entries from the `/api/audit-logs` endpoint
|
||||
2. THE Audit_Log_Panel SHALL display columns for timestamp, username, action, entity type, entity ID, details, and IP address
|
||||
3. THE Audit_Log_Panel SHALL style the log table with dark theme rows, monospace font for timestamps and IP addresses, and `data-row` hover effects
|
||||
4. THE Audit_Log_Panel SHALL display action type badges using color-coded `status-badge` styling — login actions in success color, delete actions in danger color, create actions in accent color, update actions in warning color
|
||||
5. THE Audit_Log_Panel SHALL provide filter controls for username (text search), action type (dropdown populated from `/api/audit-logs/actions`), entity type (dropdown), start date, and end date
|
||||
6. THE Audit_Log_Panel SHALL style all filter controls using `intel-input` and `intel-button` components from the Design_System
|
||||
7. WHEN an Admin_User applies filters, THE Audit_Log_Panel SHALL re-fetch audit logs from page 1 with the selected filter parameters
|
||||
8. WHEN an Admin_User clicks a pagination control, THE Audit_Log_Panel SHALL fetch the requested page and display a page indicator showing current page, total pages, and total entry count
|
||||
9. THE Audit_Log_Panel SHALL display a "No audit log entries found" message styled with `--text-muted` color when the query returns zero results
|
||||
10. IF the audit log API request fails, THEN THE Audit_Log_Panel SHALL display an error message styled with the `--intel-danger` color
|
||||
|
||||
### Requirement 5: System Info Panel
|
||||
|
||||
**User Story:** As an admin, I want to see a summary of system health and usage statistics, so that I can quickly assess the state of the dashboard.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE System_Info_Panel SHALL display stat cards showing: total user count, active user count, total audit log entries, and count of users who logged in within the last 7 days
|
||||
2. THE System_Info_Panel SHALL style each stat card using the `stat-card` pattern from the Design_System with the accent-colored top bar and hover lift effect
|
||||
3. THE System_Info_Panel SHALL display a "Recent Activity" section showing the 10 most recent audit log entries in a compact list format
|
||||
4. WHEN the System_Info_Panel loads, THE System_Info_Panel SHALL fetch statistics from the existing `/api/users` and `/api/audit-logs` endpoints
|
||||
5. IF any statistics API request fails, THEN THE System_Info_Panel SHALL display a fallback "Unable to load" message in the affected stat card
|
||||
|
||||
### Requirement 6: Access Control
|
||||
|
||||
**User Story:** As a non-admin user, I want to be prevented from accessing the admin page, so that sensitive administrative functions are protected.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL render the Admin_Page content only when the authenticated user belongs to the Admin group
|
||||
2. WHEN a non-admin user navigates to the admin page, THE Dashboard SHALL redirect the user to the home page
|
||||
3. THE NavDrawer SHALL continue to display the "Admin Panel" navigation item only for Admin-group users
|
||||
4. THE UserMenu SHALL continue to provide "Manage Users" and "Audit Log" quick-access links for Admin-group users, opening the respective modals as before
|
||||
|
||||
### Requirement 7: Loading and Error States
|
||||
|
||||
**User Story:** As an admin, I want to see clear loading indicators and error messages, so that I know when data is being fetched and when something goes wrong.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHILE data is being fetched for any Admin_Page section, THE Admin_Page SHALL display a loading spinner styled with the `loading-spinner` class and `--intel-accent` color
|
||||
2. IF an API request returns an error, THEN THE Admin_Page SHALL display the error message in a container styled with `--intel-danger` border and text color
|
||||
3. WHEN an Admin_User performs a successful create, update, or delete operation, THE Admin_Page SHALL display a brief success notification styled with `--intel-success` color
|
||||
160
.kiro/specs/admin-page-overhaul/tasks.md
Normal file
160
.kiro/specs/admin-page-overhaul/tasks.md
Normal file
@@ -0,0 +1,160 @@
|
||||
# Implementation Plan: Admin Page Overhaul
|
||||
|
||||
## Overview
|
||||
|
||||
Replace the current inline `UserManagement` modal rendering on the admin page with a full-page, themed `AdminPage` component. The new component lives at `frontend/src/components/pages/AdminPage.js` and provides three tabbed panels — User Management, Audit Log, and System Info — all styled with the dark tactical intelligence theme. No new backend endpoints are needed; the component reuses existing `/api/users` and `/api/audit-logs` routes. Existing modal components (`UserManagement`, `AuditLog`) are preserved for quick-access from `UserMenu`.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Create AdminPage component with page header and tab navigation
|
||||
- [x] 1.1 Create `frontend/src/components/pages/AdminPage.js` with the page shell
|
||||
- Import React, useState, useAuth from AuthContext, and lucide-react icons (Shield, Clock, Activity)
|
||||
- Define `API_BASE` constant matching project convention
|
||||
- Define `TABS` array: `[{ id: 'users', label: 'User Management', icon: Shield }, { id: 'audit', label: 'Audit Log', icon: Clock }, { id: 'system', label: 'System Info', icon: Activity }]`
|
||||
- Render page header with "Admin Panel" title in monospace uppercase with `--intel-accent` text glow
|
||||
- Render tab navigation bar with monospace uppercase text, `--intel-accent` active styling, and muted inactive styling matching the CompliancePage team-tab pattern
|
||||
- Manage `activeTab` state defaulting to `'users'`
|
||||
- Conditionally render placeholder `<div>` for each panel based on `activeTab`
|
||||
- _Requirements: 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4_
|
||||
|
||||
- [x] 1.2 Integrate AdminPage into App.js
|
||||
- Import `AdminPage` from `./components/pages/AdminPage`
|
||||
- Replace the existing `{currentPage === 'admin' && isAdmin() && (<div className="space-y-6"><UserManagement onClose={() => setCurrentPage('home')} /></div>)}` block with `{currentPage === 'admin' && isAdmin() && <AdminPage />}`
|
||||
- Add non-admin redirect: `{currentPage === 'admin' && !isAdmin() && setCurrentPage('home')}` (or useEffect equivalent)
|
||||
- Keep existing `{showUserManagement && <UserManagement onClose={...} />}` and `{showAuditLog && <AuditLog onClose={...} />}` modal triggers unchanged
|
||||
- _Requirements: 1.2, 6.1, 6.2, 6.3, 6.4_
|
||||
|
||||
- [-] 2. Implement UserManagementPanel
|
||||
- [x] 2.1 Build the themed user table and group badges
|
||||
- Define `GROUP_BADGE_THEMED` map with themed colors: Admin → danger, Standard_User → accent, Leadership → warning, Read_Only → muted
|
||||
- Fetch users from `GET /api/users` with `credentials: 'include'` on panel mount
|
||||
- Render user table with columns: username, email, group, active status, last login
|
||||
- Style table with dark theme rows using `data-row` hover effects and `--text-primary` / `--text-secondary` text colors
|
||||
- Render group badges using the themed color map with severity-style badge coloring
|
||||
- Display loading spinner (`loading-spinner` class, `--intel-accent` color) while fetching
|
||||
- Display error banner with `--intel-danger` styling on fetch failure
|
||||
- _Requirements: 3.1, 3.2, 3.3, 7.1, 7.2_
|
||||
|
||||
- [x] 2.2 Implement inline add/edit form and CRUD operations
|
||||
- Add "Add User" button styled with `intel-button` primary variant
|
||||
- Show inline form with `intel-input` styled fields for username, email, password, and group dropdown
|
||||
- On edit action: populate form with selected user's data (username, email, group; password blank)
|
||||
- On form submit: POST (create) or PATCH (update) to `/api/users` or `/api/users/:id`
|
||||
- On delete action: show confirmation prompt, then DELETE to `/api/users/:id`
|
||||
- On active status toggle: PATCH to `/api/users/:id` with `is_active` toggled, update UI without full reload
|
||||
- Prevent self-modification: disable group dropdown and active toggle for the current authenticated user's row
|
||||
- Display form validation errors with `--intel-danger` color
|
||||
- Display success toast with `--intel-success` color, auto-dismiss after 2 seconds
|
||||
- _Requirements: 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 7.3_
|
||||
|
||||
- [ ] 2.3 Write property test: Group badge color mapping is total and correct
|
||||
- **Property 1: Group badge color mapping is total and correct**
|
||||
- Install `fast-check` as a dev dependency in `frontend/`
|
||||
- Create test file `frontend/src/components/pages/__tests__/AdminPage.property.test.js`
|
||||
- Generate random strings including the four valid groups and arbitrary invalid strings
|
||||
- Verify the badge function returns correct themed colors for valid groups and default muted styling for invalid groups
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 3.3**
|
||||
|
||||
- [ ] 2.4 Write property test: Edit form population preserves user data
|
||||
- **Property 2: Edit form population preserves user data**
|
||||
- Generate random user objects with arbitrary username, email, and group values
|
||||
- Verify that populating the edit form results in `formData.username === user.username`, `formData.email === user.email`, `formData.group === user.group`, and `formData.password === ''`
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 3.5**
|
||||
|
||||
- [ ] 2.5 Write property test: Self-modification prevention
|
||||
- **Property 3: Self-modification prevention**
|
||||
- Generate random user lists that include a user matching the current admin's ID
|
||||
- Verify the admin's own row has group dropdown disabled and active toggle disabled
|
||||
- Verify all other users have those controls enabled
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 3.8**
|
||||
|
||||
- [x] 3. Checkpoint — Verify user management panel
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [-] 4. Implement AuditLogPanel
|
||||
- [x] 4.1 Build the themed audit log table with action badges and filters
|
||||
- Define `ACTION_BADGE_THEMED` map with themed colors: login/success → green, delete → danger, create → accent, update → warning, default → muted
|
||||
- Fetch audit logs from `GET /api/audit-logs?page=1&limit=25` with `credentials: 'include'` on panel mount
|
||||
- Fetch action types from `GET /api/audit-logs/actions` for the action filter dropdown
|
||||
- Render log table with columns: timestamp, username, action, entity type, entity ID, details, IP address
|
||||
- Style timestamps and IP addresses with monospace font
|
||||
- Render action type badges using the themed color map
|
||||
- Style table with dark theme rows and `data-row` hover effects
|
||||
- Display loading spinner while fetching, error banner on failure
|
||||
- Display "No audit log entries found" message with `--text-muted` color when results are empty
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.9, 4.10, 7.1, 7.2_
|
||||
|
||||
- [x] 4.2 Implement filter controls and pagination
|
||||
- Render filter bar with: username text input, action type dropdown, entity type dropdown, start date picker, end date picker
|
||||
- Style all filter controls with `intel-input` and `intel-button` components
|
||||
- On filter apply: re-fetch audit logs from page 1 with selected filter parameters
|
||||
- Render pagination controls showing current page, total pages, and total entry count
|
||||
- On page change: fetch the requested page
|
||||
- _Requirements: 4.5, 4.6, 4.7, 4.8_
|
||||
|
||||
- [ ] 4.3 Write property test: Action badge color mapping is total and correct
|
||||
- **Property 4: Action badge color mapping is total and correct**
|
||||
- Generate random action strings including all known actions and arbitrary unknown strings
|
||||
- Verify the badge function returns correct themed colors for known actions and default muted styling for unknown actions
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 4.4**
|
||||
|
||||
- [ ] 4.4 Write property test: Applying filters resets pagination to page 1
|
||||
- **Property 5: Applying filters resets pagination to page 1**
|
||||
- Generate random filter combinations (username text, action type, entity type, start date, end date) and random current page numbers
|
||||
- Verify that applying filters results in a fetch call with `page=1`
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 4.7**
|
||||
|
||||
- [-] 5. Implement SystemInfoPanel
|
||||
- [x] 5.1 Build stat cards and recent activity list
|
||||
- Fetch users from `GET /api/users` and recent audit logs from `GET /api/audit-logs?limit=10&page=1` on panel mount
|
||||
- Compute derived stats: total users (`users.length`), active users (`users.filter(u => u.is_active)`), recent logins (users with `last_login` within last 7 days), total audit entries (from pagination.total)
|
||||
- Render four stat cards using the `stat-card` pattern with accent-colored top bar and hover lift effect
|
||||
- Render "Recent Activity" section showing the 10 most recent audit log entries in a compact list format
|
||||
- Show "Unable to load" fallback in affected stat cards when individual API requests fail
|
||||
- Display loading spinner while fetching
|
||||
- _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5, 7.1_
|
||||
|
||||
- [ ] 5.2 Write property test: Recent login count computation
|
||||
- **Property 6: Recent login count computation**
|
||||
- Generate random user lists with random `last_login` timestamps (including null values)
|
||||
- Verify the computed "recent logins" count equals the number of users whose `last_login` is non-null and falls within the last 7 days
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 5.1**
|
||||
|
||||
- [x] 6. Checkpoint — Verify all panels and integration
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [-] 7. Access control and final wiring
|
||||
- [x] 7.1 Verify access control integration
|
||||
- Confirm `AdminPage` reads auth context via `useAuth()` and only renders content for Admin-group users
|
||||
- Confirm `App.js` redirects non-admin users to home when `currentPage === 'admin'`
|
||||
- Confirm `NavDrawer` continues to show "Admin Panel" only for Admin-group users (no changes needed — verify existing behavior)
|
||||
- Confirm `UserMenu` quick-access links ("Manage Users", "Audit Log") continue to open existing modal components (no changes needed — verify existing behavior)
|
||||
- _Requirements: 6.1, 6.2, 6.3, 6.4_
|
||||
|
||||
- [ ] 7.2 Write property test: Admin-only access control
|
||||
- **Property 7: Admin-only access control**
|
||||
- Generate random user objects with random group values
|
||||
- Verify admin page content renders if and only if `user.group === 'Admin'`
|
||||
- Verify non-Admin groups trigger redirect to home
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 6.1, 6.2**
|
||||
|
||||
- [x] 8. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests validate universal correctness properties from the design document using fast-check
|
||||
- Unit tests validate specific examples and edge cases
|
||||
- Existing `UserManagement.js` and `AuditLog.js` modal components are not modified — they remain for UserMenu quick-access
|
||||
- All styling follows the project convention of inline styles + App.css classes (no Tailwind in the new component)
|
||||
- The `fast-check` library must be installed as a dev dependency before running property tests
|
||||
1
.kiro/specs/archive-finding-clarity/.config.kiro
Normal file
1
.kiro/specs/archive-finding-clarity/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "acff93bd-0045-4fcd-b948-cc52c7cc5ec6", "workflowType": "requirements-first", "specType": "feature"}
|
||||
196
.kiro/specs/archive-finding-clarity/design.md
Normal file
196
.kiro/specs/archive-finding-clarity/design.md
Normal file
@@ -0,0 +1,196 @@
|
||||
# Design Document: Archive Finding Clarity
|
||||
|
||||
## Overview
|
||||
|
||||
This feature enhances the Ivanti Archive Findings panel on the STEAM Security Dashboard homepage to provide clearer context for archived findings. The changes span both backend (related active finding detection) and frontend (card rendering improvements).
|
||||
|
||||
The core additions are:
|
||||
1. **Finding ID display** — Show the Ivanti finding ID on each archive card for cross-referencing
|
||||
2. **Historical severity labeling** — Prefix severity with "Last seen:" to clarify it's a snapshot
|
||||
3. **Related active finding detection** — Server-side matching of archived findings against the current findings cache by hostname + title
|
||||
4. **Visual status indicators** — Icon and border color distinctions based on whether a related active finding exists
|
||||
|
||||
All matching is performed server-side in a single pass to avoid per-card API calls and keep the archive panel responsive.
|
||||
|
||||
## Architecture
|
||||
|
||||
The feature touches two layers:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Backend
|
||||
A[GET /api/ivanti/archive?state=X] --> B[Query ivanti_finding_archives]
|
||||
B --> C[Parse ivanti_findings_cache JSON once]
|
||||
C --> D[Match each archive record against active findings]
|
||||
D --> E[Return archives with related_active field]
|
||||
end
|
||||
subgraph Frontend
|
||||
E --> F[App.js archiveList.map]
|
||||
F --> G[Render enhanced Archive Cards]
|
||||
end
|
||||
```
|
||||
|
||||
**Key design decision:** The related finding lookup is embedded in the existing `GET /api/ivanti/archive` endpoint rather than exposed as a separate endpoint. This avoids N+1 API calls from the frontend and keeps the archive panel's fetch pattern unchanged (single request per state filter click).
|
||||
|
||||
### Data Flow
|
||||
|
||||
1. User clicks a state card in `ArchiveSummaryBar` → triggers `handleArchiveStateClick(state)` in `App.js`
|
||||
2. Frontend calls `GET /api/ivanti/archive?state={state}`
|
||||
3. Backend queries `ivanti_finding_archives` for matching state
|
||||
4. Backend reads `ivanti_findings_cache` row (id=1), parses `findings_json` once
|
||||
5. For each archive record, backend runs the matching function against the parsed active findings
|
||||
6. Backend returns `{ archives: [...], total: N }` where each archive object now includes a `related_active` field
|
||||
7. Frontend renders each archive card with the new fields: finding ID, "Last seen:" severity, optional badge, icon/border
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend: Modified Archive Route (`backend/routes/ivantiArchive.js`)
|
||||
|
||||
**Changes to `GET /` handler:**
|
||||
|
||||
```javascript
|
||||
// New matching function added to the module
|
||||
function findRelatedActive(archive, activeFindings) {
|
||||
// Returns { id, title, severity } or null
|
||||
}
|
||||
```
|
||||
|
||||
**`findRelatedActive(archive, activeFindings)` logic:**
|
||||
- Input: one archive record, array of parsed active findings
|
||||
- Filter active findings where:
|
||||
- `hostName` exactly matches `archive.host_name` (case-sensitive, matching existing DB convention)
|
||||
- AND the archive's `finding_title` is a case-insensitive substring of the active finding's `title`, OR vice versa
|
||||
- AND the active finding's `id` is NOT equal to `archive.finding_id`
|
||||
- If multiple matches, return the one with the highest `severity`
|
||||
- If no matches, return `null`
|
||||
|
||||
**Modified response shape:**
|
||||
```javascript
|
||||
// Before
|
||||
{ id, finding_id, finding_title, host_name, ip_address, current_state, last_severity, ... }
|
||||
|
||||
// After — same fields plus:
|
||||
{ ...existing, related_active: null | { id: string, title: string, severity: number } }
|
||||
```
|
||||
|
||||
### Frontend: Modified Archive Card Rendering (`frontend/src/App.js`)
|
||||
|
||||
The `archiveList.map()` block in `App.js` is updated to render:
|
||||
|
||||
1. **Finding title** (existing, unchanged)
|
||||
2. **Finding ID** — new line below title, monospace, muted color (`#64748B`), font size `0.6rem`. Truncated with ellipsis at 20 characters, full value in `title` attribute for tooltip.
|
||||
3. **Severity badge** — changed from raw number to "Last seen: X.X" format. Null/zero shows "Last seen: —".
|
||||
4. **Related active badge** — conditional. When `related_active` is non-null, shows "Similar finding active" with the related finding's ID and severity, styled with accent color (`#0EA5E9`).
|
||||
5. **Icon** — `AlertTriangle` (from lucide-react) when `related_active` is non-null, `CheckCircle` when null.
|
||||
6. **Left border** — `#F59E0B` (amber) when `related_active` is non-null, `#10B981` (green) when null.
|
||||
|
||||
### No New Components
|
||||
|
||||
The archive card is rendered inline in `App.js` (not a separate component), consistent with the existing pattern. The changes modify the existing `archiveList.map()` JSX block. No new React components are introduced.
|
||||
|
||||
### No New API Endpoints
|
||||
|
||||
The related finding detection is added to the existing `GET /api/ivanti/archive` route. The `ArchiveSummaryBar` component and its `/stats` endpoint are unchanged.
|
||||
|
||||
## Data Models
|
||||
|
||||
### Existing Tables (unchanged)
|
||||
|
||||
**`ivanti_finding_archives`**
|
||||
| Column | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| id | INTEGER PK | Auto-increment row ID |
|
||||
| finding_id | TEXT UNIQUE | Ivanti finding identifier |
|
||||
| finding_title | TEXT | Finding title at archive time |
|
||||
| host_name | TEXT | Hostname |
|
||||
| ip_address | TEXT | IP address |
|
||||
| current_state | TEXT | ARCHIVED, RETURNED, or CLOSED |
|
||||
| last_severity | REAL | Severity at last transition |
|
||||
| first_archived_at | DATETIME | First archive timestamp |
|
||||
| last_transition_at | DATETIME | Last state change timestamp |
|
||||
|
||||
**`ivanti_findings_cache`** (row id=1)
|
||||
| Column | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| findings_json | TEXT | JSON array of active findings |
|
||||
| total | INTEGER | Count of cached findings |
|
||||
|
||||
Each entry in `findings_json` has the shape produced by `extractFinding()` in `ivantiFindings.js`:
|
||||
```javascript
|
||||
{ id, title, severity, vrrGroup, hostName, ipAddress, dns, status, slaStatus, dueDate, lastFoundOn, buOwnership, cves, workflow }
|
||||
```
|
||||
|
||||
### No Schema Changes
|
||||
|
||||
This feature requires no database migrations. All data needed for the matching logic already exists in the two tables above.
|
||||
|
||||
## 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: Finding ID display with truncation
|
||||
|
||||
*For any* archive record, the rendered card SHALL display the finding_id. If the finding_id is longer than 20 characters, the displayed text SHALL be truncated to 20 characters followed by an ellipsis. If the finding_id is 20 characters or fewer, it SHALL be displayed in full.
|
||||
|
||||
**Validates: Requirements 1.1, 1.2**
|
||||
|
||||
### Property 2: Historical severity labeling
|
||||
|
||||
*For any* archive record, the rendered severity display SHALL contain the text "Last seen:" followed by the severity value formatted to one decimal place. When the severity is null or zero, the display SHALL show "Last seen: —".
|
||||
|
||||
**Validates: Requirements 2.1, 2.3**
|
||||
|
||||
### Property 3: API response structure — related_active always present
|
||||
|
||||
*For any* request to the archive API and *for any* archive record in the response, the record SHALL contain a `related_active` field that is either `null` or an object with `id` (string), `title` (string), and `severity` (number) properties.
|
||||
|
||||
**Validates: Requirements 3.1, 3.4**
|
||||
|
||||
### Property 4: Matching logic — hostname and title substring
|
||||
|
||||
*For any* archived finding and *for any* active finding, the active finding is a related match if and only if: (a) the active finding's hostname exactly equals the archive's hostname, AND (b) the archive's title is a case-insensitive substring of the active finding's title OR the active finding's title is a case-insensitive substring of the archive's title, AND (c) the active finding's ID is not equal to the archive's finding_id.
|
||||
|
||||
**Validates: Requirements 3.2, 3.5**
|
||||
|
||||
### Property 5: Highest severity selection
|
||||
|
||||
*For any* archived finding with multiple matching active findings, the `related_active` field SHALL contain the match with the highest severity value.
|
||||
|
||||
**Validates: Requirements 3.3**
|
||||
|
||||
### Property 6: Badge visibility matches related_active presence
|
||||
|
||||
*For any* archive record, the "Similar finding active" badge SHALL be displayed if and only if the `related_active` field is non-null. When displayed, the badge SHALL include the related finding's ID and severity.
|
||||
|
||||
**Validates: Requirements 4.1, 4.3**
|
||||
|
||||
### Property 7: Icon and border determined by related_active, not lifecycle state
|
||||
|
||||
*For any* archive record, regardless of its lifecycle state (ARCHIVED, RETURNED, or CLOSED), the icon and left border color SHALL be determined solely by whether `related_active` is non-null (alert icon + amber border) or null (check icon + green border).
|
||||
|
||||
**Validates: Requirements 5.1, 5.2, 5.3**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Backend
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| `findings_json` is malformed or unparseable | Catch JSON.parse error, log warning, treat as empty array (all `related_active` fields become `null`) |
|
||||
| `findings_json` column is NULL | Default to empty array |
|
||||
| `ivanti_findings_cache` row missing (id=1) | Default to empty array — no related matches |
|
||||
| Database query failure on archive records | Return 500 with `{ error: 'Failed to fetch archive records' }` (existing behavior) |
|
||||
| Database query failure on findings cache | Log error, continue with empty active findings (graceful degradation) |
|
||||
|
||||
### Frontend
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| `related_active` field missing from response | Treat as `null` (no badge, green/check styling) |
|
||||
| `finding_id` is empty string | Display finding title only (existing fallback behavior) |
|
||||
| `last_severity` is undefined | Display "Last seen: —" |
|
||||
| API returns error | Existing error handling in `handleArchiveStateClick` already catches and shows empty state |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
Testing is performed manually on the dev server. No automated tests are required for this feature.
|
||||
82
.kiro/specs/archive-finding-clarity/requirements.md
Normal file
82
.kiro/specs/archive-finding-clarity/requirements.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The Ivanti Archive Findings panel on the STEAM Security Dashboard homepage displays findings that have transitioned through the archive lifecycle (Active, Archived, Returned, Closed). The current archive cards show the finding title, hostname, IP address, and a raw severity number — but lack clarity in several areas. Users cannot see the Ivanti finding ID for cross-referencing, the severity score appears to be a current value when it is actually a historical snapshot, and there is no indication when a related finding with the same title still exists on the same host under a different Ivanti finding ID.
|
||||
|
||||
This feature improves archive card clarity by adding finding IDs, labeling severity as historical, introducing a "related active finding" indicator, and using visual icon distinctions to communicate resolution status at a glance.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Archive_Card**: A single rendered entry in the archive findings list on the homepage, representing one row from the `ivanti_finding_archives` table.
|
||||
- **Archive_Panel**: The section of the homepage that contains the ArchiveSummaryBar stat cards and the expandable archive findings list.
|
||||
- **Finding_ID**: The stable Ivanti-assigned identifier for a host finding (stored as `finding_id` in `ivanti_finding_archives`). Finding IDs do not change with score drift or rescoring.
|
||||
- **Last_Severity**: The severity score recorded at the time a finding was archived or last transitioned between states. It is a historical snapshot, not a live risk assessment.
|
||||
- **Current_Findings_Cache**: The `ivanti_findings_cache` table containing the latest synced findings as a JSON array. Each cached finding has fields including `id`, `title`, `severity`, `hostName`, and `ipAddress`.
|
||||
- **Related_Active_Finding**: A finding in the Current_Findings_Cache that shares the same hostname and a similar title with an archived finding but has a different Finding_ID, indicating a genuinely distinct but related finding is still open on the same host.
|
||||
- **Archive_API**: The backend endpoint `GET /api/ivanti/archive` that returns archive records filtered by lifecycle state.
|
||||
- **Related_Findings_Endpoint**: A new backend endpoint that accepts archived finding details and returns matching active findings from the Current_Findings_Cache.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Display Finding ID on Archive Cards
|
||||
|
||||
**User Story:** As a security analyst, I want to see the Ivanti finding ID on each archive card, so that I can cross-reference archived findings with the Reporting page.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Archive_Card SHALL display the Finding_ID in monospace font below the finding title.
|
||||
2. WHEN the Finding_ID is longer than 20 characters, THE Archive_Card SHALL truncate the Finding_ID with an ellipsis and display the full value in a tooltip on hover.
|
||||
3. THE Archive_Card SHALL render the Finding_ID with a visually distinct style (muted color, smaller font size) so it is clearly secondary to the finding title.
|
||||
|
||||
### Requirement 2: Historical Severity Labeling
|
||||
|
||||
**User Story:** As a security analyst, I want the severity score on archive cards to be clearly labeled as a historical value, so that I do not mistake it for a current risk assessment.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Archive_Card SHALL display the Last_Severity with a "Last seen:" prefix label (e.g., "Last seen: 9.4").
|
||||
2. THE Archive_Card SHALL render the severity label in a muted, secondary style that visually distinguishes it from live severity badges used elsewhere in the dashboard.
|
||||
3. WHEN the Last_Severity value is null or zero, THE Archive_Card SHALL display "Last seen: —" as a placeholder.
|
||||
|
||||
### Requirement 3: Related Active Finding Detection API
|
||||
|
||||
**User Story:** As a security analyst, I want the system to detect when an archived finding has a related active finding on the same host, so that I can understand whether similar risk still exists.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Archive_API SHALL return a `related_active` field for each archive record, containing either `null` (no match) or an object with the matching active finding's `id`, `title`, and `severity`.
|
||||
2. WHEN matching archived findings to active findings, THE Related_Findings_Endpoint SHALL compare by exact hostname match AND case-insensitive substring containment of the archived finding title within the active finding title (or vice versa).
|
||||
3. WHEN multiple active findings match a single archived finding, THE Related_Findings_Endpoint SHALL return the match with the highest severity.
|
||||
4. IF the Current_Findings_Cache contains no findings or is empty, THEN THE Related_Findings_Endpoint SHALL return `null` for all `related_active` fields.
|
||||
5. THE Related_Findings_Endpoint SHALL exclude matches where the active finding's `id` is identical to the archived finding's Finding_ID.
|
||||
|
||||
### Requirement 4: Related Active Finding Indicator on Archive Cards
|
||||
|
||||
**User Story:** As a security analyst, I want to see a visual indicator on archive cards when a related active finding exists on the same host, so that I can quickly identify findings that may still represent active risk.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN an archive record has a non-null `related_active` field, THE Archive_Card SHALL display a badge reading "Similar finding active" with the related finding's ID and current severity.
|
||||
2. THE Archive_Card SHALL render the related active badge using the dashboard accent color (#0EA5E9) to distinguish it from the archive card's own severity display.
|
||||
3. WHEN an archive record has a null `related_active` field, THE Archive_Card SHALL not display any related-finding badge.
|
||||
|
||||
### Requirement 5: Visual Icon Distinction by Resolution Status
|
||||
|
||||
**User Story:** As a security analyst, I want archive cards to use different icons and border colors based on whether a related active finding exists, so that I can scan the list and quickly distinguish fully resolved findings from those with ongoing similar risk.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN an archive record has a non-null `related_active` field, THE Archive_Card SHALL display an alert-style icon (e.g., `AlertTriangle` from lucide-react) and use a warning-toned left border color (#F59E0B).
|
||||
2. WHEN an archive record has a null `related_active` field, THE Archive_Card SHALL display a check-style icon (e.g., `CheckCircle` from lucide-react) and use a success-toned left border color (#10B981).
|
||||
3. THE Archive_Card SHALL apply the icon and border color consistently regardless of the archive lifecycle state (ARCHIVED, RETURNED, or CLOSED).
|
||||
|
||||
### Requirement 6: Performance of Related Finding Lookup
|
||||
|
||||
**User Story:** As a security analyst, I want the archive panel to load promptly even when checking for related active findings, so that the feature does not degrade the homepage experience.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Archive_API SHALL compute related active finding matches server-side within the existing archive list query, avoiding separate per-card API calls from the frontend.
|
||||
2. WHEN the Current_Findings_Cache JSON is parsed for matching, THE Archive_API SHALL parse the cache once per request and reuse the parsed result across all archive records in the response.
|
||||
3. THE Archive_API response time for a filtered archive list SHALL remain under 500ms for up to 200 archive records.
|
||||
70
.kiro/specs/archive-finding-clarity/tasks.md
Normal file
70
.kiro/specs/archive-finding-clarity/tasks.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Implementation Plan: Archive Finding Clarity
|
||||
|
||||
## Overview
|
||||
|
||||
Enhance the Ivanti Archive Findings panel to display finding IDs, label severity as historical, detect related active findings server-side, and apply visual icon/border distinctions based on resolution status. Changes span `backend/routes/ivantiArchive.js` (matching logic + enriched response) and `frontend/src/App.js` (card rendering updates). No new components, endpoints, or migrations.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Add `findRelatedActive` function and enrich the GET `/` handler in `backend/routes/ivantiArchive.js`
|
||||
- [x] 1.1 Add the `findRelatedActive(archive, activeFindings)` helper function
|
||||
- Add function above `createIvantiArchiveRouter` or inside the module scope
|
||||
- Filter active findings where `hostName` exactly matches `archive.host_name`
|
||||
- AND the archive's `finding_title` is a case-insensitive substring of the active finding's `title`, or vice versa
|
||||
- AND the active finding's `id` is NOT equal to `archive.finding_id`
|
||||
- If multiple matches, return the one with the highest `severity` as `{ id, title, severity }`
|
||||
- If no matches, return `null`
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.5_
|
||||
|
||||
- [x] 1.2 Modify the `GET /` handler to parse findings cache and enrich archive records
|
||||
- After fetching archive rows, query `ivanti_findings_cache` (id=1) for `findings_json`
|
||||
- Parse `findings_json` once with `JSON.parse`; default to empty array if NULL, missing row, or parse error
|
||||
- Log a warning on parse failure, do not throw
|
||||
- For each archive record, call `findRelatedActive(archive, parsedFindings)` and attach the result as `related_active`
|
||||
- Return the enriched archives array in the existing `{ archives, total }` response shape
|
||||
- _Requirements: 3.1, 3.4, 6.1, 6.2_
|
||||
|
||||
- [x] 2. Checkpoint — Verify backend changes
|
||||
- Ensure the backend starts without errors, ask the user if questions arise.
|
||||
|
||||
- [x] 3. Update archive card rendering in `frontend/src/App.js`
|
||||
- [x] 3.1 Add `AlertTriangle` and `CheckCircle` to the lucide-react import
|
||||
- Locate the existing lucide-react import statement in `App.js`
|
||||
- Add `AlertTriangle` and `CheckCircle` if not already imported
|
||||
- _Requirements: 5.1, 5.2_
|
||||
|
||||
- [x] 3.2 Add Finding ID display below the finding title
|
||||
- Inside the `archiveList.map()` block, add a new line below the title `<span>`
|
||||
- Render `a.finding_id` in monospace font, `0.6rem` size, muted color `#64748B`
|
||||
- If `finding_id` length exceeds 20 characters, truncate displayed text to 20 chars + ellipsis
|
||||
- Set the full `finding_id` as the `title` attribute for hover tooltip
|
||||
- _Requirements: 1.1, 1.2, 1.3_
|
||||
|
||||
- [x] 3.3 Change severity badge to "Last seen: X.X" format
|
||||
- In the severity `<span>` within the archive card, replace `{a.last_severity?.toFixed(1) ?? '—'}` with `Last seen: {a.last_severity?.toFixed(1) ?? '—'}`
|
||||
- Null or zero severity displays as "Last seen: —"
|
||||
- _Requirements: 2.1, 2.2, 2.3_
|
||||
|
||||
- [x] 3.4 Add conditional "Similar finding active" badge
|
||||
- When `a.related_active` is non-null, render a badge below the host info line
|
||||
- Badge text: "Similar finding active" with the related finding's ID and severity
|
||||
- Style with accent color `#0EA5E9`, monospace font, `0.6rem` size
|
||||
- When `a.related_active` is null, render nothing
|
||||
- _Requirements: 4.1, 4.2, 4.3_
|
||||
|
||||
- [x] 3.5 Add icon and left border color based on `related_active`
|
||||
- When `a.related_active` is non-null: render `AlertTriangle` icon and set left border to `3px solid #F59E0B` (amber)
|
||||
- When `a.related_active` is null: render `CheckCircle` icon and set left border to `3px solid #10B981` (green)
|
||||
- Place the icon at the left side of the card header row, before the title
|
||||
- Apply consistently regardless of archive lifecycle state (ARCHIVED, RETURNED, CLOSED)
|
||||
- _Requirements: 5.1, 5.2, 5.3_
|
||||
|
||||
- [x] 4. Final checkpoint — Verify full feature
|
||||
- Ensure the frontend compiles without errors, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- No automated tests — feature is validated manually on the dev server per user preference
|
||||
- No new components, endpoints, or database migrations required
|
||||
- The `findRelatedActive` function parses the findings cache once per request for performance (Requirement 6.2)
|
||||
- Each task references specific requirements for traceability
|
||||
1
.kiro/specs/atlas-action-plans/.config.kiro
Normal file
1
.kiro/specs/atlas-action-plans/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "aa138cae-9fbf-47bf-9dc3-1169456f5706", "workflowType": "requirements-first", "specType": "feature"}
|
||||
497
.kiro/specs/atlas-action-plans/design.md
Normal file
497
.kiro/specs/atlas-action-plans/design.md
Normal file
@@ -0,0 +1,497 @@
|
||||
# Design Document: Atlas Action Plans Integration
|
||||
|
||||
## Overview
|
||||
|
||||
This feature integrates the Atlas InfoSec action plans API into the STEAM Security Dashboard, allowing users to view and manage compliance action plans for host findings directly from the ReportingPage. The integration follows the existing proxy-and-cache pattern used by the Ivanti integration — a backend helper handles HTTP communication with the external API, a SQLite cache stores host-level status for fast page loads, and Express routes expose both cached status and proxied CRUD operations to the React frontend.
|
||||
|
||||
The frontend adds two visual elements to the ReportingPage: a small badge in the Host column indicating action plan coverage, and a slide-out panel for viewing, creating, and updating plans. A manual sync button — matching the existing Ivanti sync button pattern — lets users refresh cached Atlas data on demand.
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
- **Proxy pattern over direct frontend calls**: The frontend never talks to Atlas directly. All Atlas API calls go through the STEAM backend, which handles authentication, TLS configuration, and audit logging. This keeps Atlas credentials server-side and provides a single audit trail.
|
||||
- **Cache-then-fetch**: The ReportingPage loads cached badge data from SQLite on mount (fast), and users trigger a manual sync to refresh from Atlas (slow, one API call per host). This matches the existing Ivanti sync UX.
|
||||
- **Sequential host sync (not bulk GET)**: The Atlas API only exposes per-host `GET /hosts/{host_id}/action-plans`. There is no bulk status endpoint, so the sync iterates over unique host IDs from the Ivanti cache. Concurrency is limited to avoid overwhelming Atlas.
|
||||
- **Basic Auth with runtime base64 encoding**: Atlas uses `Authorization: Basic <base64(user:pass)>` rather than the API key pattern used by Ivanti. The helper computes this at request time from environment variables.
|
||||
- **ID mapping**: Ivanti `host.hostId` maps directly to Atlas `host_id` in URL paths. Ivanti `f.id` maps to Atlas `active_host_findings_id` in request bodies. No translation layer is needed.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph Frontend
|
||||
RP[ReportingPage]
|
||||
AB[AtlasBadge]
|
||||
SP[AtlasSlideOutPanel]
|
||||
end
|
||||
|
||||
subgraph Backend
|
||||
AR[Atlas Router<br/>/api/atlas/*]
|
||||
AH[Atlas Helper<br/>atlasApi.js]
|
||||
AC[(Atlas Cache<br/>SQLite)]
|
||||
IC[(Ivanti Cache<br/>SQLite)]
|
||||
AL[Audit Log]
|
||||
end
|
||||
|
||||
subgraph External
|
||||
ATLAS[Atlas InfoSec API<br/>https://atlas-infosec.caas.charterlab.com]
|
||||
end
|
||||
|
||||
RP -->|GET /api/atlas/status| AR
|
||||
RP -->|POST /api/atlas/sync| AR
|
||||
AB -->|click| SP
|
||||
SP -->|GET /api/atlas/hosts/:id/action-plans| AR
|
||||
SP -->|PUT /api/atlas/hosts/:id/action-plans| AR
|
||||
SP -->|PATCH /api/atlas/hosts/:id/action-plans| AR
|
||||
|
||||
AR -->|read cached status| AC
|
||||
AR -->|read host IDs| IC
|
||||
AR -->|GET, PUT, PATCH, POST| AH
|
||||
AR -->|logAudit| AL
|
||||
AH -->|HTTPS + Basic Auth| ATLAS
|
||||
AR -->|upsert cache| AC
|
||||
```
|
||||
|
||||
### Data Flow: Page Load
|
||||
|
||||
1. ReportingPage mounts, fetches Ivanti findings from existing cache (existing behavior)
|
||||
2. ReportingPage fetches `GET /api/atlas/status` — returns all cached Atlas rows
|
||||
3. Frontend builds a `Map<hostId, atlasStatus>` and passes it to table rendering
|
||||
4. Each Host column cell checks the map — if a match exists, renders an AtlasBadge
|
||||
|
||||
### Data Flow: Manual Sync
|
||||
|
||||
1. User clicks Atlas sync button
|
||||
2. Frontend sends `POST /api/atlas/sync`
|
||||
3. Backend extracts unique `hostId` values from `ivanti_findings_cache.findings_json`
|
||||
4. Backend calls `GET /hosts/{host_id}/action-plans` for each host (with concurrency limit of 5)
|
||||
5. Backend upserts each result into `atlas_action_plans_cache`
|
||||
6. Backend returns summary `{ synced, withPlans, failed }`
|
||||
7. Frontend re-fetches `GET /api/atlas/status` and updates badges
|
||||
|
||||
### Data Flow: Create/Update Plan
|
||||
|
||||
1. User clicks AtlasBadge → slide-out panel opens
|
||||
2. Panel fetches `GET /api/atlas/hosts/:hostId/action-plans` for live data
|
||||
3. User fills create form or edits existing plan
|
||||
4. Frontend sends `PUT` (create) or `PATCH` (update) to `/api/atlas/hosts/:hostId/action-plans`
|
||||
5. Backend validates request body, proxies to Atlas API, logs audit entry
|
||||
6. On success, panel refreshes plan list and frontend re-fetches cached status
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend: Atlas API Helper (`backend/helpers/atlasApi.js`)
|
||||
|
||||
A new helper module following the same pattern as `ivantiApi.js` — promise-based HTTP using Node's `https` module, with TLS skip support.
|
||||
|
||||
```javascript
|
||||
// Exported functions
|
||||
function atlasRequest(method, urlPath, body, options)
|
||||
// method: 'GET' | 'PUT' | 'PATCH' | 'POST'
|
||||
// urlPath: e.g. '/hosts/29329662/action-plans'
|
||||
// body: object | null (null for GET)
|
||||
// options: { timeout?: number }
|
||||
// Returns: Promise<{ status: number, body: string }>
|
||||
|
||||
// Convenience wrappers
|
||||
function atlasGet(urlPath, options)
|
||||
function atlasPut(urlPath, body, options)
|
||||
function atlasPatch(urlPath, body, options)
|
||||
function atlasPost(urlPath, body, options)
|
||||
```
|
||||
|
||||
**Configuration** (read from `process.env` at module load):
|
||||
- `ATLAS_API_URL` — base URL (e.g. `https://atlas-infosec.caas.charterlab.com`)
|
||||
- `ATLAS_API_USER` — service account username
|
||||
- `ATLAS_API_PASS` — service account password
|
||||
- `ATLAS_SKIP_TLS` — `'true'` to disable certificate verification
|
||||
|
||||
**Auth header**: `Authorization: Basic ${Buffer.from(user + ':' + pass).toString('base64')}`
|
||||
|
||||
**Timeouts**: 15s default for single-host endpoints, 60s for bulk. Passed via `options.timeout`.
|
||||
|
||||
**Error handling**: Network errors and timeouts reject the promise. Non-2xx responses resolve normally with `{ status, body }` — the caller decides how to handle them.
|
||||
|
||||
### Backend: Migration (`backend/migrations/add_atlas_action_plans_cache.js`)
|
||||
|
||||
Creates the `atlas_action_plans_cache` table following the existing migration pattern.
|
||||
|
||||
```javascript
|
||||
// Table schema
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS atlas_action_plans_cache (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL UNIQUE,
|
||||
has_action_plan INTEGER NOT NULL DEFAULT 0,
|
||||
plan_count INTEGER NOT NULL DEFAULT 0,
|
||||
plans_json TEXT NOT NULL DEFAULT '[]',
|
||||
synced_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
db.run(`
|
||||
CREATE INDEX IF NOT EXISTS idx_atlas_cache_host_id
|
||||
ON atlas_action_plans_cache(host_id)
|
||||
`);
|
||||
```
|
||||
|
||||
### Backend: Atlas Router (`backend/routes/atlas.js`)
|
||||
|
||||
Factory function pattern: `createAtlasRouter(db, requireAuth)` returns an Express Router mounted at `/api/atlas`.
|
||||
|
||||
| Method | Path | Auth | Group | Description |
|
||||
|--------|------|------|-------|-------------|
|
||||
| `GET` | `/status` | requireAuth | any | Return all cached Atlas rows |
|
||||
| `POST` | `/sync` | requireAuth | Admin, Standard_User | Sync Atlas data for all Ivanti hosts |
|
||||
| `GET` | `/hosts/:hostId/action-plans` | requireAuth | any | Proxy to Atlas GET plans |
|
||||
| `PUT` | `/hosts/:hostId/action-plans` | requireAuth | Admin, Standard_User | Proxy to Atlas create plan |
|
||||
| `PATCH` | `/hosts/:hostId/action-plans` | requireAuth | Admin, Standard_User | Proxy to Atlas update plan |
|
||||
| `POST` | `/hosts/bulk-action-plans` | requireAuth | Admin, Standard_User | Proxy to Atlas bulk create |
|
||||
|
||||
**Sync implementation**:
|
||||
1. Parse `ivanti_findings_cache.findings_json` to extract unique `hostId` values (skip nulls)
|
||||
2. Process hosts in batches of 5 concurrent requests using `Promise.allSettled`
|
||||
3. For each host, call `atlasGet('/hosts/' + hostId + '/action-plans')`
|
||||
4. On 2xx: upsert cache row with plan count and summary JSON
|
||||
5. On non-2xx: increment failure counter, log warning, continue
|
||||
6. Return `{ synced: N, withPlans: N, failed: N }`
|
||||
|
||||
**Validation (PUT create)**:
|
||||
- `plan_type` must be one of: `decommission`, `remediation`, `false_positive`, `risk_acceptance`, `scan_exclusion`
|
||||
- `commit_date` must match `/^\d{4}-\d{2}-\d{2}$/`
|
||||
- `hostId` param must be a positive integer
|
||||
|
||||
**Validation (PATCH update)**:
|
||||
- `action_plan_id` must be a non-empty string
|
||||
- `updates` must be a non-null object
|
||||
|
||||
**Validation (POST bulk)**:
|
||||
- `host_ids` must be a non-empty array of positive integers
|
||||
- `plan_type` and `commit_date` validated same as PUT
|
||||
|
||||
### Frontend: AtlasBadge Component
|
||||
|
||||
A small inline badge rendered inside the Host column cell, next to the hostname. Clicking it opens the slide-out panel.
|
||||
|
||||
**Props**: `{ hostId, atlasStatus, onClick }`
|
||||
|
||||
**Rendering logic**:
|
||||
- If `atlasStatus` is `undefined` (host not in Atlas cache): render nothing
|
||||
- If `atlasStatus.has_action_plan === 0`: render warning badge (amber border, "0" text)
|
||||
- If `atlasStatus.plan_count > 0`: render success badge (emerald border, count text)
|
||||
|
||||
**Style**: Small pill badge using the design system's badge pattern — monospace font, 0.58rem, inline-flex, with border color indicating status. Positioned after the hostname text in the OverrideCell wrapper.
|
||||
|
||||
### Frontend: AtlasSlideOutPanel Component
|
||||
|
||||
A right-side drawer panel, similar in concept to the existing FP submission detail panels. Renders over the table content with a semi-transparent backdrop.
|
||||
|
||||
**Props**: `{ hostId, hostName, onClose, canWrite }`
|
||||
|
||||
**Sections**:
|
||||
1. **Header**: hostname, host ID, close button
|
||||
2. **Plan list**: fetched from `GET /api/atlas/hosts/:hostId/action-plans` on open. Each plan shows type, commit date, status, and optional VNR/EXC references
|
||||
3. **Create form** (if `canWrite`): plan type dropdown, commit date picker, optional fields (qualys_id, active_host_findings_id, jira_vnr, archer_exc)
|
||||
4. **Edit capability** (if `canWrite`): inline edit on existing plans, submits via PATCH
|
||||
|
||||
**State management**: Local component state — plan list, loading, error, form values. No global state needed since the panel is ephemeral.
|
||||
|
||||
### Frontend: Atlas Sync Button
|
||||
|
||||
A new button in the ReportingPage toolbar, placed adjacent to the existing Ivanti sync button. Uses the same styling pattern — `RefreshCw` icon, monospace uppercase text, sky blue accent color. Differentiated by a `Database` icon prefix and "Atlas" label.
|
||||
|
||||
**State**: `atlasSyncing` boolean, `atlasStatus` map (keyed by hostId), `atlasError` string.
|
||||
|
||||
### Server.js Integration
|
||||
|
||||
```javascript
|
||||
const createAtlasRouter = require('./routes/atlas');
|
||||
// ...
|
||||
app.use('/api/atlas', createAtlasRouter(db, requireAuth));
|
||||
```
|
||||
|
||||
## Data Models
|
||||
|
||||
### Atlas Cache Table (`atlas_action_plans_cache`)
|
||||
|
||||
| Column | Type | Constraints | Description |
|
||||
|--------|------|-------------|-------------|
|
||||
| `id` | INTEGER | PRIMARY KEY AUTOINCREMENT | Row ID |
|
||||
| `host_id` | INTEGER | NOT NULL UNIQUE | Ivanti host ID (= Atlas host_id) |
|
||||
| `has_action_plan` | INTEGER | NOT NULL DEFAULT 0 | 1 if any plans exist, 0 otherwise |
|
||||
| `plan_count` | INTEGER | NOT NULL DEFAULT 0 | Number of action plans |
|
||||
| `plans_json` | TEXT | NOT NULL DEFAULT '[]' | JSON array of plan summaries |
|
||||
| `synced_at` | DATETIME | NOT NULL DEFAULT CURRENT_TIMESTAMP | Last sync timestamp |
|
||||
|
||||
**Index**: `idx_atlas_cache_host_id` on `host_id`
|
||||
|
||||
### Plan Summary JSON Shape (stored in `plans_json`)
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"action_plan_id": "ap-123",
|
||||
"plan_type": "remediation",
|
||||
"commit_date": "2026-07-01",
|
||||
"status": "active",
|
||||
"qualys_id": "QID-12345",
|
||||
"active_host_findings_id": 2281281250,
|
||||
"jira_vnr": null,
|
||||
"archer_exc": null
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
The exact shape depends on what the Atlas API returns. The backend stores the raw response array as-is, extracting only `plan_count` and `has_action_plan` for the cache columns.
|
||||
|
||||
### Atlas API Request/Response Shapes
|
||||
|
||||
**Create (PUT `/hosts/{host_id}/action-plans`)**:
|
||||
```json
|
||||
{
|
||||
"plan_type": "remediation",
|
||||
"commit_date": "2026-07-01",
|
||||
"active_host_findings_id": 2281281250
|
||||
}
|
||||
```
|
||||
|
||||
**Update (PATCH `/hosts/{host_id}/action-plans`)**:
|
||||
```json
|
||||
{
|
||||
"action_plan_id": "ap-123",
|
||||
"updates": {
|
||||
"commit_date": "2026-08-01"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Bulk Create (POST `/hosts/create-bulk-action-plans`)**:
|
||||
```json
|
||||
{
|
||||
"host_ids": [29329662, 29329663],
|
||||
"plan_type": "decommission",
|
||||
"commit_date": "2026-07-01"
|
||||
}
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Required | Description |
|
||||
|----------|----------|-------------|
|
||||
| `ATLAS_API_URL` | Yes | Atlas InfoSec API base URL |
|
||||
| `ATLAS_API_USER` | Yes | Service account username for Basic Auth |
|
||||
| `ATLAS_API_PASS` | Yes | Service account password for Basic Auth |
|
||||
| `ATLAS_SKIP_TLS` | No | Set to `true` to skip TLS cert verification (default: `false`) |
|
||||
|
||||
### Frontend State Shape
|
||||
|
||||
```javascript
|
||||
// Atlas status map — keyed by hostId (number)
|
||||
const atlasStatusMap = new Map([
|
||||
[29329662, { host_id: 29329662, has_action_plan: 1, plan_count: 2, synced_at: '2026-07-01 12:00:00' }],
|
||||
[29329663, { host_id: 29329663, has_action_plan: 0, plan_count: 0, synced_at: '2026-07-01 12:00:00' }],
|
||||
]);
|
||||
```
|
||||
|
||||
|
||||
## 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: Basic Auth header round-trip
|
||||
|
||||
*For any* pair of (username, password) strings, the Authorization header produced by the Atlas helper should decode (via base64) to exactly `username:password`.
|
||||
|
||||
**Validates: Requirements 1.2**
|
||||
|
||||
### Property 2: Non-2xx responses resolve with status and body
|
||||
|
||||
*For any* HTTP status code in the range 400–599 and any response body string, the Atlas helper should resolve the promise with an object containing that exact status code and body, rather than rejecting.
|
||||
|
||||
**Validates: Requirements 1.7**
|
||||
|
||||
### Property 3: Error messages contain method and path
|
||||
|
||||
*For any* HTTP method string and URL path string, when a network error or timeout occurs, the Atlas helper's rejection error message should contain both the method and the path.
|
||||
|
||||
**Validates: Requirements 1.8**
|
||||
|
||||
### Property 4: Unique host ID extraction
|
||||
|
||||
*For any* array of finding objects (each with an optional `hostId` field), the sync operation should extract exactly the set of unique, non-null `hostId` values — no duplicates, no nulls.
|
||||
|
||||
**Validates: Requirements 3.2**
|
||||
|
||||
### Property 5: Cache upsert derives correct plan_count and has_action_plan
|
||||
|
||||
*For any* host ID and any array of action plan objects returned by the Atlas API, after upserting into the cache, the stored `plan_count` should equal the array length and `has_action_plan` should equal 1 if the array is non-empty, 0 otherwise.
|
||||
|
||||
**Validates: Requirements 3.4**
|
||||
|
||||
### Property 6: Sync response count invariant
|
||||
|
||||
*For any* sync operation over N unique hosts where M hosts fail, the response should satisfy: `synced + failed = N` and `withPlans <= synced`.
|
||||
|
||||
**Validates: Requirements 3.6**
|
||||
|
||||
### Property 7: Status endpoint returns all cached rows with required fields
|
||||
|
||||
*For any* set of rows inserted into the Atlas cache table, the `GET /api/atlas/status` endpoint should return exactly that many rows, and each row should contain `host_id`, `has_action_plan`, `plan_count`, and `synced_at` fields.
|
||||
|
||||
**Validates: Requirements 4.2, 4.3**
|
||||
|
||||
### Property 8: plan_type validation
|
||||
|
||||
*For any* string, the PUT endpoint's plan_type validation should accept the string if and only if it is one of: `decommission`, `remediation`, `false_positive`, `risk_acceptance`, `scan_exclusion`.
|
||||
|
||||
**Validates: Requirements 5.3**
|
||||
|
||||
### Property 9: commit_date validation
|
||||
|
||||
*For any* string, the PUT endpoint's commit_date validation should accept the string if and only if it matches the pattern `YYYY-MM-DD` (four digits, hyphen, two digits, hyphen, two digits).
|
||||
|
||||
**Validates: Requirements 5.4**
|
||||
|
||||
### Property 10: PATCH body validation
|
||||
|
||||
*For any* request body object, the PATCH endpoint should accept it if and only if `action_plan_id` is a non-empty string and `updates` is a non-null object.
|
||||
|
||||
**Validates: Requirements 5.7**
|
||||
|
||||
### Property 11: Bulk request validation
|
||||
|
||||
*For any* request body object, the bulk POST endpoint should accept it if and only if `host_ids` is a non-empty array of positive integers, `plan_type` is one of the five valid types, and `commit_date` matches `YYYY-MM-DD`.
|
||||
|
||||
**Validates: Requirements 5.10**
|
||||
|
||||
### Property 12: Non-2xx Atlas response passthrough
|
||||
|
||||
*For any* non-2xx status code and error body returned by the Atlas API, the proxy route should return that same status code and body to the frontend client.
|
||||
|
||||
**Validates: Requirements 5.12**
|
||||
|
||||
### Property 13: Badge visibility and content
|
||||
|
||||
*For any* finding with a `hostId` and any atlas status map, the AtlasBadge should render if and only if the `hostId` exists as a key in the map. When rendered with `plan_count > 0`, the badge text should contain the plan count value.
|
||||
|
||||
**Validates: Requirements 6.2, 6.5, 6.6**
|
||||
|
||||
### Property 14: Panel displays all plan fields
|
||||
|
||||
*For any* action plan object containing `plan_type`, `commit_date`, `status`, and optional reference fields (`jira_vnr`, `archer_exc`), the rendered slide-out panel should include all non-null field values in its output.
|
||||
|
||||
**Validates: Requirements 7.3**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Atlas API Communication Errors
|
||||
|
||||
| Error Scenario | Handling | User Impact |
|
||||
|----------------|----------|-------------|
|
||||
| Network timeout (15s/60s) | Helper rejects promise with descriptive error | Sync: host skipped, counted as failed. Proxy: 502 returned to frontend with error message |
|
||||
| DNS resolution failure | Helper rejects promise | Same as timeout |
|
||||
| TLS certificate error (when `ATLAS_SKIP_TLS` is false) | Helper rejects promise | Same as timeout |
|
||||
| Atlas API returns 401 (bad credentials) | Helper resolves with `{ status: 401, body }` | Sync: all hosts fail. Proxy: 401 forwarded to frontend. Error banner shown |
|
||||
| Atlas API returns 404 (host not found) | Helper resolves with `{ status: 404, body }` | Sync: host skipped. Proxy: 404 forwarded to frontend |
|
||||
| Atlas API returns 422 (validation error) | Helper resolves with `{ status: 422, body }` | Proxy: 422 forwarded to frontend. Panel shows validation error |
|
||||
| Atlas API returns 500 (server error) | Helper resolves with `{ status: 500, body }` | Sync: host skipped. Proxy: 500 forwarded to frontend |
|
||||
|
||||
### Backend Validation Errors
|
||||
|
||||
| Error Scenario | HTTP Status | Response |
|
||||
|----------------|-------------|----------|
|
||||
| Missing or invalid `plan_type` | 400 | `{ error: 'plan_type must be one of: decommission, remediation, ...' }` |
|
||||
| Missing or invalid `commit_date` | 400 | `{ error: 'commit_date must be a valid YYYY-MM-DD date string' }` |
|
||||
| Missing `action_plan_id` on PATCH | 400 | `{ error: 'action_plan_id is required and must be a non-empty string' }` |
|
||||
| Missing `updates` on PATCH | 400 | `{ error: 'updates is required and must be an object' }` |
|
||||
| Empty or invalid `host_ids` on bulk | 400 | `{ error: 'host_ids must be a non-empty array of positive integers' }` |
|
||||
| Non-integer `hostId` URL param | 400 | `{ error: 'hostId must be a positive integer' }` |
|
||||
| Unauthenticated request | 401 | `{ error: 'Authentication required' }` |
|
||||
| Viewer group on restricted endpoint | 403 | `{ error: 'Insufficient permissions', required: [...], current: 'Viewer' }` |
|
||||
|
||||
### Frontend Error Handling
|
||||
|
||||
- **Sync failure**: Error banner displayed below the Atlas sync button (matching existing Ivanti sync error pattern). Button re-enabled.
|
||||
- **Panel fetch failure**: "Failed to load action plans" message inside the panel with a retry button.
|
||||
- **Create/update failure**: Error message displayed inline in the form, preserving user input for correction.
|
||||
- **Network error**: Generic "Unable to reach server" message with retry option.
|
||||
|
||||
### Environment Configuration Errors
|
||||
|
||||
- If `ATLAS_API_URL`, `ATLAS_API_USER`, or `ATLAS_API_PASS` are not set, the Atlas helper logs a warning at module load time. All Atlas API calls will fail with a descriptive error rather than crashing the server.
|
||||
- The Atlas router checks for helper availability and returns 503 if Atlas is not configured.
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
|
||||
Unit tests cover specific examples, edge cases, and integration points:
|
||||
|
||||
**Atlas Helper (`atlasApi.js`)**:
|
||||
- Correct URL construction from base URL + path
|
||||
- Basic Auth header format for known credentials
|
||||
- TLS skip flag respected (rejectUnauthorized option)
|
||||
- Timeout values for single vs bulk endpoints
|
||||
- GET, PUT, PATCH, POST methods set correctly
|
||||
|
||||
**Atlas Router validation**:
|
||||
- Valid plan_type values accepted, invalid rejected
|
||||
- Valid commit_date formats accepted, invalid rejected
|
||||
- PATCH body with missing action_plan_id rejected
|
||||
- Bulk request with empty host_ids rejected
|
||||
- Non-integer hostId param rejected
|
||||
- Auth middleware applied to correct endpoints (401/403 responses)
|
||||
|
||||
**Atlas Cache operations**:
|
||||
- Upsert creates new row when host_id doesn't exist
|
||||
- Upsert updates existing row when host_id exists
|
||||
- Status endpoint returns empty array when cache is empty
|
||||
- Migration is idempotent (runs twice without error)
|
||||
|
||||
**Frontend components**:
|
||||
- AtlasBadge renders nothing when host not in status map
|
||||
- AtlasBadge renders warning style when plan_count is 0
|
||||
- AtlasBadge renders success style when plan_count > 0
|
||||
- AtlasSlideOutPanel shows create form for Admin/Standard_User
|
||||
- AtlasSlideOutPanel hides create form for Viewer
|
||||
- Sync button disabled during sync, re-enabled after
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based tests verify universal properties across generated inputs. Each test runs a minimum of 100 iterations.
|
||||
|
||||
**Library**: [fast-check](https://github.com/dubzzz/fast-check) — the standard PBT library for JavaScript/Node.js.
|
||||
|
||||
**Configuration**: Each property test runs with `{ numRuns: 100 }` minimum.
|
||||
|
||||
**Tag format**: Each test includes a comment referencing its design property:
|
||||
```javascript
|
||||
// Feature: atlas-action-plans, Property 1: Basic Auth header round-trip
|
||||
```
|
||||
|
||||
| Property | Test Description | Generator Strategy |
|
||||
|----------|-----------------|-------------------|
|
||||
| Property 1 | Encode then decode Basic Auth header | Generate random (user, pass) string pairs, verify round-trip |
|
||||
| Property 2 | Non-2xx status codes resolve | Generate integers 400–599 and random body strings |
|
||||
| Property 3 | Error messages contain method and path | Generate random method names and URL path strings |
|
||||
| Property 4 | Unique host ID extraction | Generate arrays of objects with optional numeric hostId fields |
|
||||
| Property 5 | Cache upsert correctness | Generate (hostId, planArray) pairs, verify derived fields |
|
||||
| Property 6 | Sync count invariant | Generate (totalHosts, failureCount) pairs, verify arithmetic |
|
||||
| Property 7 | Status returns all cached rows | Generate N cache rows, verify response count and fields |
|
||||
| Property 8 | plan_type validation | Generate random strings, verify acceptance matches valid set |
|
||||
| Property 9 | commit_date validation | Generate random strings, verify acceptance matches date pattern |
|
||||
| Property 10 | PATCH body validation | Generate random objects with varying field presence |
|
||||
| Property 11 | Bulk validation | Generate objects with varying host_ids, plan_type, commit_date |
|
||||
| Property 12 | Error passthrough | Generate non-2xx codes and body strings, verify forwarding |
|
||||
| Property 13 | Badge visibility and content | Generate findings and status maps, verify render logic |
|
||||
| Property 14 | Panel plan field display | Generate plan objects, verify all non-null fields appear |
|
||||
|
||||
### Integration Tests
|
||||
|
||||
Integration tests verify end-to-end behavior with mocked Atlas API:
|
||||
|
||||
- Full sync flow: populate Ivanti cache → trigger sync → verify Atlas cache populated
|
||||
- Create plan flow: send PUT → verify Atlas API called → verify audit logged
|
||||
- Update plan flow: send PATCH → verify Atlas API called → verify audit logged
|
||||
- Bulk create flow: send POST → verify Atlas API called with correct body
|
||||
- Error resilience: mix of successful and failing hosts during sync
|
||||
- Auth enforcement: verify 401/403 for each endpoint with wrong credentials/group
|
||||
164
.kiro/specs/atlas-action-plans/requirements.md
Normal file
164
.kiro/specs/atlas-action-plans/requirements.md
Normal file
@@ -0,0 +1,164 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
Integrate the Atlas InfoSec action plans API into the STEAM Security Dashboard so that users can view and manage compliance action plans for host findings directly from the ReportingPage. This eliminates the need to context-switch to the separate Atlas InfoSec web tool. The integration uses STEAM's Ivanti findings as the source of truth and checks which hosts also exist in Atlas, displaying action plan status badges and providing a slide-out panel for plan creation and management.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Dashboard**: The STEAM Security Dashboard frontend React application
|
||||
- **Backend**: The STEAM Security Dashboard Express.js API server
|
||||
- **Atlas_API**: The Atlas InfoSec REST API at `https://atlas-infosec.caas.charterlab.com`, documented in `docs/atlasinfosec-api-spec.json`
|
||||
- **Atlas_Helper**: The backend helper module (`backend/helpers/atlasApi.js`) responsible for HTTP communication with the Atlas_API
|
||||
- **Atlas_Cache**: A SQLite table storing host-level action plan status per `hostId`, refreshed on-demand via manual sync
|
||||
- **Atlas_Router**: The backend Express route module (`backend/routes/atlas.js`) exposing Atlas-related endpoints under `/api/atlas`
|
||||
- **ReportingPage**: The existing frontend page (`frontend/src/components/pages/ReportingPage.js`) displaying Ivanti host findings
|
||||
- **Action_Plan**: A compliance plan created in Atlas InfoSec for a host finding, with a type (decommission, remediation, false_positive, risk_acceptance, scan_exclusion), a commit date, and optional reference fields
|
||||
- **Host_ID**: The shared numeric identifier linking an Ivanti host finding (`host.hostId`) to an Atlas host (`host_id` URL parameter)
|
||||
- **Finding_ID**: The Ivanti finding-level identifier (`f.id`) that maps to Atlas's `active_host_findings_id`
|
||||
- **Slide_Out_Panel**: A right-side drawer component on the ReportingPage for viewing and managing action plans for a specific host
|
||||
- **Atlas_Badge**: A visual indicator on the ReportingPage Host column showing whether a host exists in Atlas and its action plan coverage status
|
||||
- **Ivanti_Cache**: The existing `ivanti_findings_cache` SQLite table holding synced Ivanti host findings
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Atlas API Helper Module
|
||||
|
||||
**User Story:** As a backend developer, I want a centralized helper module for Atlas InfoSec API communication, so that all Atlas HTTP calls use consistent authentication, TLS handling, and error management.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Atlas_Helper SHALL send all requests to the Atlas_API base URL configured via the `ATLAS_API_URL` environment variable
|
||||
2. THE Atlas_Helper SHALL include a Basic Auth `Authorization` header computed by base64-encoding the `ATLAS_API_USER` and `ATLAS_API_PASS` environment variable values at runtime
|
||||
3. WHEN the `ATLAS_SKIP_TLS` environment variable is set to `true`, THE Atlas_Helper SHALL disable TLS certificate verification for Atlas_API requests
|
||||
4. WHEN the `ATLAS_SKIP_TLS` environment variable is not set or set to `false`, THE Atlas_Helper SHALL enforce TLS certificate verification for Atlas_API requests
|
||||
5. THE Atlas_Helper SHALL support GET, PUT, PATCH, and POST HTTP methods for communicating with the Atlas_API
|
||||
6. THE Atlas_Helper SHALL set a request timeout of 15 seconds for single-host endpoints and 60 seconds for bulk endpoints
|
||||
7. WHEN the Atlas_API returns a non-2xx status code, THE Atlas_Helper SHALL resolve the promise with the status code and response body without throwing an exception
|
||||
8. WHEN a network error or timeout occurs, THE Atlas_Helper SHALL reject the promise with a descriptive error message including the HTTP method and URL path
|
||||
|
||||
### Requirement 2: Atlas Cache Table and Migration
|
||||
|
||||
**User Story:** As a system administrator, I want Atlas action plan status cached locally in SQLite, so that the ReportingPage can render badges without calling the Atlas_API on every page load.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Backend SHALL provide a migration script (`backend/migrations/add_atlas_action_plans_cache.js`) that creates the Atlas_Cache table
|
||||
2. THE Atlas_Cache table SHALL store one row per Host_ID with columns for: `host_id` (integer, unique), `has_action_plan` (integer, 0 or 1), `plan_count` (integer), `plans_json` (text, JSON array of plan summaries), and `synced_at` (datetime)
|
||||
3. THE migration script SHALL create an index on the `host_id` column of the Atlas_Cache table
|
||||
4. THE migration script SHALL follow the existing migration pattern: open the database at `backend/cve_database.db`, use `db.serialize()`, log progress to the console, and close the database on completion
|
||||
5. WHEN the migration script is run multiple times, THE migration script SHALL complete without errors by using `CREATE TABLE IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS`
|
||||
|
||||
### Requirement 3: Atlas Sync Route
|
||||
|
||||
**User Story:** As a dashboard user, I want to trigger a manual sync of Atlas action plan data, so that the badge indicators on the ReportingPage reflect the current state of action plans in Atlas.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Atlas_Router SHALL expose a `POST /api/atlas/sync` endpoint that requires authentication and membership in the Admin or Standard_User group
|
||||
2. WHEN the sync endpoint is called, THE Atlas_Router SHALL extract unique Host_ID values from the Ivanti_Cache findings
|
||||
3. WHEN unique Host_ID values are extracted, THE Atlas_Router SHALL call the Atlas_API `GET /hosts/{host_id}/action-plans` endpoint for each Host_ID to retrieve action plan data
|
||||
4. WHEN action plan data is retrieved for a Host_ID, THE Atlas_Router SHALL upsert the Atlas_Cache row for that Host_ID with the plan count, plan summary JSON, and current timestamp
|
||||
5. WHEN the Atlas_API returns a non-2xx response for a specific Host_ID, THE Atlas_Router SHALL skip that host and continue processing remaining hosts
|
||||
6. WHEN the sync completes, THE Atlas_Router SHALL return a JSON response containing the count of hosts synced, the count of hosts with action plans, and the count of hosts that failed
|
||||
7. THE Atlas_Router SHALL log an audit entry for each sync operation with the initiating user and result summary
|
||||
|
||||
### Requirement 4: Atlas Status Route
|
||||
|
||||
**User Story:** As a frontend developer, I want a single endpoint that returns cached Atlas status for all hosts, so that the ReportingPage can render badges without individual API calls per row.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Atlas_Router SHALL expose a `GET /api/atlas/status` endpoint that requires authentication
|
||||
2. WHEN the status endpoint is called, THE Atlas_Router SHALL return all rows from the Atlas_Cache table as a JSON array
|
||||
3. THE status response SHALL include for each host: `host_id`, `has_action_plan`, `plan_count`, and `synced_at`
|
||||
|
||||
### Requirement 5: Atlas Action Plan Proxy Routes
|
||||
|
||||
**User Story:** As a dashboard user, I want to create, view, and update Atlas action plans from the STEAM Dashboard, so that I do not need to switch to the Atlas InfoSec web tool.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Atlas_Router SHALL expose a `GET /api/atlas/hosts/:hostId/action-plans` endpoint that requires authentication and proxies to the Atlas_API `GET /hosts/{host_id}/action-plans` endpoint
|
||||
2. THE Atlas_Router SHALL expose a `PUT /api/atlas/hosts/:hostId/action-plans` endpoint that requires authentication and membership in the Admin or Standard_User group
|
||||
3. WHEN the PUT endpoint receives a request body, THE Atlas_Router SHALL validate that `plan_type` is one of: decommission, remediation, false_positive, risk_acceptance, scan_exclusion
|
||||
4. WHEN the PUT endpoint receives a request body, THE Atlas_Router SHALL validate that `commit_date` is present and is a valid date string in YYYY-MM-DD format
|
||||
5. WHEN validation passes, THE Atlas_Router SHALL proxy the request body to the Atlas_API `PUT /hosts/{host_id}/action-plans` endpoint and return the Atlas_API response
|
||||
6. THE Atlas_Router SHALL expose a `PATCH /api/atlas/hosts/:hostId/action-plans` endpoint that requires authentication and membership in the Admin or Standard_User group
|
||||
7. WHEN the PATCH endpoint receives a request body, THE Atlas_Router SHALL validate that `action_plan_id` (string) and `updates` (object) are present
|
||||
8. WHEN validation passes, THE Atlas_Router SHALL proxy the request body to the Atlas_API `PATCH /hosts/{host_id}/action-plans` endpoint and return the Atlas_API response
|
||||
9. THE Atlas_Router SHALL expose a `POST /api/atlas/hosts/bulk-action-plans` endpoint that requires authentication and membership in the Admin or Standard_User group
|
||||
10. WHEN the bulk endpoint receives a request body, THE Atlas_Router SHALL validate that `host_ids` is a non-empty array of integers, `plan_type` is valid, and `commit_date` is a valid YYYY-MM-DD date string
|
||||
11. WHEN validation passes, THE Atlas_Router SHALL proxy the request body to the Atlas_API `POST /hosts/create-bulk-action-plans` endpoint and return the Atlas_API response
|
||||
12. WHEN any proxy endpoint receives a non-2xx response from the Atlas_API, THE Atlas_Router SHALL return the Atlas_API status code and error body to the frontend
|
||||
13. THE Atlas_Router SHALL log an audit entry for each create (PUT) and update (PATCH) action plan operation with the user, Host_ID, and plan type
|
||||
|
||||
### Requirement 6: Atlas Badge on ReportingPage
|
||||
|
||||
**User Story:** As a dashboard user, I want to see at a glance which hosts in the findings table have Atlas action plans, so that I can prioritize hosts that still need compliance attention.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the ReportingPage loads, THE Dashboard SHALL fetch cached Atlas status from `GET /api/atlas/status` and store the result in component state
|
||||
2. WHEN a finding row's Host_ID matches an entry in the Atlas status data, THE Dashboard SHALL display an Atlas_Badge in the Host column next to the hostname
|
||||
3. WHEN a host exists in Atlas but has zero action plans, THE Atlas_Badge SHALL display with a warning style indicating the host needs attention
|
||||
4. WHEN a host exists in Atlas and has one or more active action plans, THE Atlas_Badge SHALL display with a success style indicating the host is covered
|
||||
5. WHEN a finding row's Host_ID does not match any entry in the Atlas status data, THE Dashboard SHALL display no Atlas_Badge for that row
|
||||
6. THE Atlas_Badge SHALL display the action plan count as text within the badge when the host has one or more plans
|
||||
|
||||
### Requirement 7: Atlas Slide-Out Panel
|
||||
|
||||
**User Story:** As a dashboard user, I want to click an Atlas badge to see full action plan details and create or update plans, so that I can manage compliance without leaving the ReportingPage.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a user clicks an Atlas_Badge, THE Dashboard SHALL open the Slide_Out_Panel on the right side of the ReportingPage
|
||||
2. WHEN the Slide_Out_Panel opens, THE Dashboard SHALL fetch full action plan details from `GET /api/atlas/hosts/:hostId/action-plans` and display them in the panel
|
||||
3. THE Slide_Out_Panel SHALL display each existing action plan with: plan type, commit date, status, and any associated VNR or EXC reference numbers
|
||||
4. WHEN the user is in the Admin or Standard_User group, THE Slide_Out_Panel SHALL display a form to create a new action plan with fields for: plan type (dropdown selector), commit date (date picker), qualys_id (optional text input), active_host_findings_id (optional numeric input), jira_vnr (optional text input), and archer_exc (optional text input)
|
||||
5. WHEN the user submits the create form with valid data, THE Dashboard SHALL send a PUT request to `/api/atlas/hosts/:hostId/action-plans` and refresh the plan list on success
|
||||
6. WHEN the user is in the Admin or Standard_User group, THE Slide_Out_Panel SHALL provide an edit capability for existing action plans
|
||||
7. WHEN the user submits an update with valid data, THE Dashboard SHALL send a PATCH request to `/api/atlas/hosts/:hostId/action-plans` and refresh the plan list on success
|
||||
8. WHEN the Atlas_API returns an error for a create or update operation, THE Slide_Out_Panel SHALL display the error message to the user
|
||||
9. WHEN the user clicks outside the Slide_Out_Panel or clicks a close button, THE Dashboard SHALL close the panel
|
||||
10. WHEN the user is in the Viewer group, THE Slide_Out_Panel SHALL display existing plans in read-only mode without the create or edit forms
|
||||
|
||||
### Requirement 8: Atlas Sync Button on ReportingPage
|
||||
|
||||
**User Story:** As a dashboard user, I want a manual sync button for Atlas data on the ReportingPage, so that I can refresh action plan status on demand.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL display an Atlas sync button on the ReportingPage near the existing Ivanti sync button
|
||||
2. WHEN the user is in the Admin or Standard_User group, THE Atlas sync button SHALL be enabled
|
||||
3. WHEN the user is in the Viewer group, THE Atlas sync button SHALL be disabled with a tooltip indicating insufficient permissions
|
||||
4. WHEN the user clicks the Atlas sync button, THE Dashboard SHALL send a POST request to `/api/atlas/sync`
|
||||
5. WHILE the Atlas sync is in progress, THE Atlas sync button SHALL display a loading indicator and be disabled to prevent duplicate requests
|
||||
6. WHEN the Atlas sync completes successfully, THE Dashboard SHALL refresh the Atlas status data and update all Atlas_Badge indicators on the page
|
||||
7. WHEN the Atlas sync fails, THE Dashboard SHALL display an error notification with the failure reason
|
||||
|
||||
### Requirement 9: Environment Configuration
|
||||
|
||||
**User Story:** As a system administrator, I want Atlas API credentials and configuration documented alongside existing environment variables, so that deployment setup is straightforward.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Backend SHALL read the Atlas_API base URL from the `ATLAS_API_URL` environment variable
|
||||
2. THE Backend SHALL read the Atlas service account username from the `ATLAS_API_USER` environment variable
|
||||
3. THE Backend SHALL read the Atlas service account password from the `ATLAS_API_PASS` environment variable
|
||||
4. THE Backend SHALL read the TLS verification skip flag from the `ATLAS_SKIP_TLS` environment variable
|
||||
5. THE Backend SHALL document all four Atlas environment variables in `backend/.env.example` with descriptive comments
|
||||
|
||||
### Requirement 10: Access Control
|
||||
|
||||
**User Story:** As a security administrator, I want Atlas operations restricted by user group, so that only authorized users can modify action plans or trigger syncs.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Atlas_Router SHALL allow all authenticated users to access the `GET /api/atlas/status` endpoint
|
||||
2. THE Atlas_Router SHALL allow all authenticated users to access the `GET /api/atlas/hosts/:hostId/action-plans` endpoint
|
||||
3. THE Atlas_Router SHALL restrict the `POST /api/atlas/sync` endpoint to users in the Admin or Standard_User group
|
||||
4. THE Atlas_Router SHALL restrict the `PUT /api/atlas/hosts/:hostId/action-plans` endpoint to users in the Admin or Standard_User group
|
||||
5. THE Atlas_Router SHALL restrict the `PATCH /api/atlas/hosts/:hostId/action-plans` endpoint to users in the Admin or Standard_User group
|
||||
6. THE Atlas_Router SHALL restrict the `POST /api/atlas/hosts/bulk-action-plans` endpoint to users in the Admin or Standard_User group
|
||||
7. WHEN an unauthorized user attempts a restricted operation, THE Atlas_Router SHALL return HTTP 403 with an error message indicating insufficient permissions
|
||||
262
.kiro/specs/atlas-action-plans/tasks.md
Normal file
262
.kiro/specs/atlas-action-plans/tasks.md
Normal file
@@ -0,0 +1,262 @@
|
||||
# Implementation Plan: Atlas Action Plans Integration
|
||||
|
||||
## Overview
|
||||
|
||||
Integrate the Atlas InfoSec action plans API into the STEAM Security Dashboard. The implementation follows the existing proxy-and-cache pattern — backend helper for HTTP communication, SQLite cache for fast page loads, Express routes for proxied CRUD, and React frontend components for badge display and plan management. Tasks are ordered for incremental progress: environment config, backend helper, migration, routes, server wiring, then frontend components.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Add Atlas environment variables to `.env.example`
|
||||
- Append `ATLAS_API_URL`, `ATLAS_API_USER`, `ATLAS_API_PASS`, and `ATLAS_SKIP_TLS` to `backend/.env.example` with descriptive comments, following the existing Ivanti variable block pattern
|
||||
- _Requirements: 9.1, 9.2, 9.3, 9.4, 9.5_
|
||||
|
||||
- [ ] 2. Implement Atlas API helper module
|
||||
- [x] 2.1 Create `backend/helpers/atlasApi.js` with `atlasRequest`, `atlasGet`, `atlasPut`, `atlasPatch`, `atlasPost` functions
|
||||
- Read `ATLAS_API_URL`, `ATLAS_API_USER`, `ATLAS_API_PASS`, `ATLAS_SKIP_TLS` from `process.env` at module load
|
||||
- Compute `Authorization: Basic <base64(user:pass)>` header at request time
|
||||
- Use Node.js `https` module following the `ivantiApi.js` pattern
|
||||
- Support GET, PUT, PATCH, POST methods with `rejectUnauthorized` controlled by `ATLAS_SKIP_TLS`
|
||||
- Default timeout 15s for single-host endpoints, 60s via `options.timeout` for bulk
|
||||
- Resolve non-2xx responses with `{ status, body }` without throwing
|
||||
- Reject on network errors/timeouts with a message containing the HTTP method and URL path
|
||||
- Log a warning at module load if required env vars are missing
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8_
|
||||
|
||||
- [ ] 2.2 Write property test: Basic Auth header round-trip
|
||||
- **Property 1: Basic Auth header round-trip**
|
||||
- Generate random (username, password) string pairs, verify base64 decode yields `username:password`
|
||||
- **Validates: Requirements 1.2**
|
||||
|
||||
- [ ] 2.3 Write property test: Non-2xx responses resolve with status and body
|
||||
- **Property 2: Non-2xx responses resolve with status and body**
|
||||
- Generate integers 400–599 and random body strings, verify promise resolves with `{ status, body }`
|
||||
- **Validates: Requirements 1.7**
|
||||
|
||||
- [ ] 2.4 Write property test: Error messages contain method and path
|
||||
- **Property 3: Error messages contain method and path**
|
||||
- Generate random method names and URL path strings, verify rejection message includes both
|
||||
- **Validates: Requirements 1.8**
|
||||
|
||||
- [x] 3. Checkpoint — Verify Atlas helper module
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [ ] 4. Create Atlas cache migration
|
||||
- [x] 4.1 Create `backend/migrations/add_atlas_action_plans_cache.js`
|
||||
- Follow the existing migration pattern from `add_ivanti_findings_tables.js`: open `backend/cve_database.db`, use `db.serialize()`, log progress, close on completion
|
||||
- Create `atlas_action_plans_cache` table with columns: `id` (INTEGER PRIMARY KEY AUTOINCREMENT), `host_id` (INTEGER NOT NULL UNIQUE), `has_action_plan` (INTEGER NOT NULL DEFAULT 0), `plan_count` (INTEGER NOT NULL DEFAULT 0), `plans_json` (TEXT NOT NULL DEFAULT '[]'), `synced_at` (DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)
|
||||
- Create index `idx_atlas_cache_host_id` on `host_id`
|
||||
- Use `CREATE TABLE IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS` for idempotency
|
||||
- _Requirements: 2.1, 2.2, 2.3, 2.4, 2.5_
|
||||
|
||||
- [ ]* 4.2 Write unit tests for migration idempotency
|
||||
- Verify migration runs twice without errors
|
||||
- Verify table and index exist after migration
|
||||
- _Requirements: 2.5_
|
||||
|
||||
- [ ] 5. Implement Atlas router with all endpoints
|
||||
- [x] 5.1 Create `backend/routes/atlas.js` with `createAtlasRouter(db, requireAuth)` factory function
|
||||
- Import `requireGroup` from `../middleware/auth`, `logAudit` from `../helpers/auditLog`, and Atlas helper functions from `../helpers/atlasApi`
|
||||
- Check Atlas helper availability; return 503 if Atlas is not configured
|
||||
- _Requirements: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7_
|
||||
|
||||
- [x] 5.2 Implement `GET /status` endpoint
|
||||
- Require authentication (any group)
|
||||
- Return all rows from `atlas_action_plans_cache` as JSON array with `host_id`, `has_action_plan`, `plan_count`, `synced_at`
|
||||
- _Requirements: 4.1, 4.2, 4.3, 10.1_
|
||||
|
||||
- [x] 5.3 Implement `POST /sync` endpoint
|
||||
- Require authentication and Admin or Standard_User group
|
||||
- Extract unique non-null `hostId` values from `ivanti_findings_cache.findings_json`
|
||||
- Call `atlasGet('/hosts/' + hostId + '/action-plans')` for each host with concurrency limit of 5 using `Promise.allSettled`
|
||||
- On 2xx: upsert cache row with `plan_count`, `has_action_plan`, `plans_json`, and current timestamp
|
||||
- On non-2xx: increment failure counter, log warning, continue
|
||||
- Return `{ synced, withPlans, failed }` summary
|
||||
- Log audit entry with initiating user and result summary
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 10.3_
|
||||
|
||||
- [x] 5.4 Implement `GET /hosts/:hostId/action-plans` proxy endpoint
|
||||
- Require authentication (any group)
|
||||
- Validate `hostId` is a positive integer
|
||||
- Proxy to Atlas API `GET /hosts/{host_id}/action-plans` and return the response
|
||||
- Forward non-2xx Atlas responses to the client
|
||||
- _Requirements: 5.1, 5.12, 10.2_
|
||||
|
||||
- [x] 5.5 Implement `PUT /hosts/:hostId/action-plans` proxy endpoint
|
||||
- Require authentication and Admin or Standard_User group
|
||||
- Validate `hostId` is a positive integer
|
||||
- Validate `plan_type` is one of: decommission, remediation, false_positive, risk_acceptance, scan_exclusion
|
||||
- Validate `commit_date` is present and matches `YYYY-MM-DD` format
|
||||
- Proxy validated body to Atlas API `PUT /hosts/{host_id}/action-plans`
|
||||
- Log audit entry with user, hostId, and plan type
|
||||
- _Requirements: 5.2, 5.3, 5.4, 5.5, 5.12, 5.13, 10.4_
|
||||
|
||||
- [x] 5.6 Implement `PATCH /hosts/:hostId/action-plans` proxy endpoint
|
||||
- Require authentication and Admin or Standard_User group
|
||||
- Validate `action_plan_id` is a non-empty string and `updates` is a non-null object
|
||||
- Proxy validated body to Atlas API `PATCH /hosts/{host_id}/action-plans`
|
||||
- Log audit entry with user, hostId, and plan type
|
||||
- _Requirements: 5.6, 5.7, 5.8, 5.12, 5.13, 10.5_
|
||||
|
||||
- [x] 5.7 Implement `POST /hosts/bulk-action-plans` proxy endpoint
|
||||
- Require authentication and Admin or Standard_User group
|
||||
- Validate `host_ids` is a non-empty array of positive integers, `plan_type` is valid, `commit_date` matches `YYYY-MM-DD`
|
||||
- Proxy validated body to Atlas API `POST /hosts/create-bulk-action-plans`
|
||||
- _Requirements: 5.9, 5.10, 5.11, 5.12, 10.6_
|
||||
|
||||
- [ ] 5.8 Write property test: Unique host ID extraction
|
||||
- **Property 4: Unique host ID extraction**
|
||||
- Generate arrays of finding objects with optional numeric `hostId` fields, verify extracted set has no duplicates and no nulls
|
||||
- **Validates: Requirements 3.2**
|
||||
|
||||
- [ ] 5.9 Write property test: Cache upsert derives correct plan_count and has_action_plan
|
||||
- **Property 5: Cache upsert derives correct plan_count and has_action_plan**
|
||||
- Generate (hostId, planArray) pairs, verify `plan_count` equals array length and `has_action_plan` equals 1 if non-empty, 0 otherwise
|
||||
- **Validates: Requirements 3.4**
|
||||
|
||||
- [ ] 5.10 Write property test: Sync response count invariant
|
||||
- **Property 6: Sync response count invariant**
|
||||
- Generate (totalHosts, failureCount) pairs, verify `synced + failed = totalHosts` and `withPlans <= synced`
|
||||
- **Validates: Requirements 3.6**
|
||||
|
||||
- [ ] 5.11 Write property test: Status endpoint returns all cached rows with required fields
|
||||
- **Property 7: Status endpoint returns all cached rows with required fields**
|
||||
- Generate N cache rows, insert into DB, verify response count and field presence
|
||||
- **Validates: Requirements 4.2, 4.3**
|
||||
|
||||
- [ ] 5.12 Write property test: plan_type validation
|
||||
- **Property 8: plan_type validation**
|
||||
- Generate random strings, verify acceptance if and only if string is one of the five valid types
|
||||
- **Validates: Requirements 5.3**
|
||||
|
||||
- [ ] 5.13 Write property test: commit_date validation
|
||||
- **Property 9: commit_date validation**
|
||||
- Generate random strings, verify acceptance if and only if string matches `YYYY-MM-DD` pattern
|
||||
- **Validates: Requirements 5.4**
|
||||
|
||||
- [ ] 5.14 Write property test: PATCH body validation
|
||||
- **Property 10: PATCH body validation**
|
||||
- Generate random objects with varying field presence, verify acceptance if and only if `action_plan_id` is a non-empty string and `updates` is a non-null object
|
||||
- **Validates: Requirements 5.7**
|
||||
|
||||
- [ ] 5.15 Write property test: Bulk request validation
|
||||
- **Property 11: Bulk request validation**
|
||||
- Generate objects with varying `host_ids`, `plan_type`, `commit_date`, verify acceptance matches combined validation rules
|
||||
- **Validates: Requirements 5.10**
|
||||
|
||||
- [ ]* 5.16 Write property test: Non-2xx Atlas response passthrough
|
||||
- **Property 12: Non-2xx Atlas response passthrough**
|
||||
- Generate non-2xx status codes and body strings, verify proxy route returns same status and body
|
||||
- **Validates: Requirements 5.12**
|
||||
|
||||
- [x] 6. Checkpoint — Verify backend routes and properties
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 7. Mount Atlas router in server.js
|
||||
- Add `const createAtlasRouter = require('./routes/atlas');` import alongside existing route imports
|
||||
- Add `app.use('/api/atlas', createAtlasRouter(db, requireAuth));` mount alongside existing route mounts
|
||||
- _Requirements: 3.1, 4.1, 5.1, 5.2, 5.6, 5.9_
|
||||
|
||||
- [ ] 8. Implement frontend Atlas components
|
||||
- [x] 8.1 Create AtlasBadge component in `frontend/src/components/AtlasBadge.js`
|
||||
- Accept props: `{ hostId, atlasStatus, onClick }`
|
||||
- Render nothing if `atlasStatus` is undefined (host not in cache)
|
||||
- Render warning badge (amber border, "0" text) if `has_action_plan === 0`
|
||||
- Render success badge (emerald border, plan count text) if `plan_count > 0`
|
||||
- Use design system badge pattern: monospace font, 0.58rem, inline-flex, pill shape
|
||||
- _Requirements: 6.2, 6.3, 6.4, 6.5, 6.6_
|
||||
|
||||
- [ ]* 8.2 Write property test: Badge visibility and content
|
||||
- **Property 13: Badge visibility and content**
|
||||
- Generate findings with `hostId` and atlas status maps, verify badge renders if and only if `hostId` exists in map, and badge text contains plan count when `plan_count > 0`
|
||||
- **Validates: Requirements 6.2, 6.5, 6.6**
|
||||
|
||||
- [x] 8.3 Create AtlasSlideOutPanel component in `frontend/src/components/AtlasSlideOutPanel.js`
|
||||
- Accept props: `{ hostId, hostName, onClose, canWrite }`
|
||||
- Fetch action plans from `GET /api/atlas/hosts/:hostId/action-plans` on open
|
||||
- Display header with hostname, host ID, and close button
|
||||
- Display each plan with: plan type, commit date, status, VNR/EXC references
|
||||
- Show create form (plan type dropdown, commit date picker, optional fields: qualys_id, active_host_findings_id, jira_vnr, archer_exc) when `canWrite` is true
|
||||
- Submit create via `PUT /api/atlas/hosts/:hostId/action-plans`, refresh plan list on success
|
||||
- Show inline edit capability for existing plans when `canWrite` is true
|
||||
- Submit updates via `PATCH /api/atlas/hosts/:hostId/action-plans`, refresh plan list on success
|
||||
- Display error messages from Atlas API inline in the panel
|
||||
- Close on backdrop click or close button
|
||||
- Hide create/edit forms for Viewer group (read-only mode)
|
||||
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, 7.10_
|
||||
|
||||
- [ ]* 8.4 Write property test: Panel displays all plan fields
|
||||
- **Property 14: Panel displays all plan fields**
|
||||
- Generate plan objects with `plan_type`, `commit_date`, `status`, and optional reference fields, verify all non-null field values appear in rendered output
|
||||
- **Validates: Requirements 7.3**
|
||||
|
||||
- [ ] 8.5 Write unit tests for AtlasBadge and AtlasSlideOutPanel
|
||||
- Test AtlasBadge renders nothing when host not in status map
|
||||
- Test AtlasBadge renders warning style when `plan_count` is 0
|
||||
- Test AtlasBadge renders success style when `plan_count > 0`
|
||||
- Test AtlasSlideOutPanel shows create form for Admin/Standard_User
|
||||
- Test AtlasSlideOutPanel hides create form for Viewer
|
||||
- _Requirements: 6.2, 6.3, 6.4, 6.5, 7.4, 7.10_
|
||||
|
||||
- [ ] 9. Integrate Atlas badge and sync button into ReportingPage
|
||||
- [x] 9.1 Add Atlas status state and fetch to ReportingPage
|
||||
- Add `atlasStatus` state (Map keyed by hostId), `atlasSyncing` boolean, `atlasError` string
|
||||
- Fetch `GET /api/atlas/status` on mount and build the status map
|
||||
- _Requirements: 6.1_
|
||||
|
||||
- [x] 9.2 Render AtlasBadge in Host column cells
|
||||
- In the Host column cell renderer, check `atlasStatus` map for the finding's `hostId`
|
||||
- Render AtlasBadge inline after the hostname text when a match exists
|
||||
- Wire badge `onClick` to open the AtlasSlideOutPanel with the host's ID and name
|
||||
- _Requirements: 6.2, 6.3, 6.4, 6.5, 6.6, 7.1_
|
||||
|
||||
- [x] 9.3 Add Atlas sync button to ReportingPage toolbar
|
||||
- Place adjacent to existing Ivanti sync button, using same styling pattern (RefreshCw icon, monospace uppercase text, sky blue accent)
|
||||
- Differentiate with Database icon prefix and "Atlas" label
|
||||
- Enable for Admin and Standard_User groups, disable for Viewer with tooltip
|
||||
- On click: send `POST /api/atlas/sync`, show loading indicator, disable button
|
||||
- On success: re-fetch `GET /api/atlas/status` and update all badges
|
||||
- On failure: display error notification
|
||||
- _Requirements: 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7_
|
||||
|
||||
- [x] 9.4 Wire AtlasSlideOutPanel into ReportingPage
|
||||
- Add state for selected host (`atlasSelectedHostId`, `atlasSelectedHostName`, `atlasPanelOpen`)
|
||||
- Render AtlasSlideOutPanel conditionally when `atlasPanelOpen` is true
|
||||
- Pass `canWrite` based on user group (Admin or Standard_User)
|
||||
- On panel close: clear selected host state
|
||||
- On plan create/update success: re-fetch atlas status to update badges
|
||||
- _Requirements: 7.1, 7.2, 7.9, 7.10_
|
||||
|
||||
- [x] 10. Checkpoint — Verify full integration
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [ ] 11. Write integration tests
|
||||
- [ ]* 11.1 Write integration tests for Atlas sync flow
|
||||
- Populate Ivanti cache with test findings, trigger sync with mocked Atlas API, verify Atlas cache populated correctly
|
||||
- Test error resilience: mix of successful and failing hosts during sync
|
||||
- _Requirements: 3.2, 3.3, 3.4, 3.5, 3.6_
|
||||
|
||||
- [ ]* 11.2 Write integration tests for Atlas proxy routes
|
||||
- Test create plan flow: send PUT, verify Atlas API called, verify audit logged
|
||||
- Test update plan flow: send PATCH, verify Atlas API called, verify audit logged
|
||||
- Test bulk create flow: send POST, verify Atlas API called with correct body
|
||||
- _Requirements: 5.1, 5.2, 5.5, 5.6, 5.8, 5.11, 5.13_
|
||||
|
||||
- [ ] 11.3 Write integration tests for access control
|
||||
- Verify 401 for unauthenticated requests on all endpoints
|
||||
- Verify 403 for Viewer group on restricted endpoints (sync, PUT, PATCH, bulk POST)
|
||||
- Verify 200 for Viewer group on read endpoints (status, GET plans)
|
||||
- _Requirements: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7_
|
||||
|
||||
- [x] 12. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests validate universal correctness properties from the design document using fast-check
|
||||
- Unit tests validate specific examples and edge cases
|
||||
- The backend follows the existing factory function pattern (`createAtlasRouter(db, requireAuth)`)
|
||||
- The Atlas helper follows the existing `ivantiApi.js` pattern (promise-based HTTP with Node.js `https` module)
|
||||
- The migration follows the existing pattern from `add_ivanti_findings_tables.js`
|
||||
1
.kiro/specs/atlas-metrics-report/.config.kiro
Normal file
1
.kiro/specs/atlas-metrics-report/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "a3e7c1d2-8f4b-4a91-b6e3-9d2f5c8a1b74", "workflowType": "requirements-first", "specType": "feature"}
|
||||
362
.kiro/specs/atlas-metrics-report/design.md
Normal file
362
.kiro/specs/atlas-metrics-report/design.md
Normal file
@@ -0,0 +1,362 @@
|
||||
# Design Document: Atlas Metrics Report
|
||||
|
||||
## Overview
|
||||
|
||||
This feature adds a tab system to the existing Metric Graphs panel on the ReportingPage, separating Ivanti donut charts from new Atlas coverage charts. A new `GET /api/atlas/metrics` endpoint aggregates cached Atlas action plan data into chart-ready metrics. The frontend renders three new donut charts — coverage, plan type distribution, and plan status distribution — under an "Atlas Coverage" tab, while the existing four Ivanti donuts move under an "Ivanti Findings" tab.
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
- **Server-side aggregation**: The metrics endpoint computes counts and distributions on the backend rather than shipping raw `plans_json` to the client. This keeps the frontend simple and avoids parsing potentially large JSON arrays in the browser.
|
||||
- **Reuse existing donut helpers**: The new Atlas donut charts reuse the `polarToCartesian` and `donutArcPath` SVG helper functions already defined in ReportingPage.js, along with the same dimensions (180px size, 72px outer radius, 48px inner radius). This keeps the visual language consistent.
|
||||
- **Fetch once, refresh on sync**: Atlas metrics are fetched once on page mount and re-fetched only after a successful Atlas sync. Tab switches do not trigger new API calls.
|
||||
- **No server.js changes**: The new endpoint is added inside the existing `createAtlasRouter(db, requireAuth)` factory function in `backend/routes/atlas.js`. The router is already mounted at `/api/atlas` in server.js.
|
||||
- **Tab state is local**: The active tab is stored in React component state — no URL params, no localStorage. The default is "Ivanti Findings" to preserve the existing experience.
|
||||
- **IvantiCountsChart conditional visibility**: The trend chart below the Metric Graphs panel is only shown when the Ivanti tab is active, since it has no relevance to Atlas data.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph Frontend - ReportingPage
|
||||
TS[Tab System<br/>Ivanti Findings | Atlas Coverage]
|
||||
ID[Ivanti Donuts<br/>StatusDonut, ActionCoverageDonut,<br/>FPWorkflowDonut x2]
|
||||
AD[Atlas Donuts<br/>CoverageDonut, PlanTypeDonut,<br/>PlanStatusDonut]
|
||||
IC[IvantiCountsChart]
|
||||
end
|
||||
|
||||
subgraph Backend - Atlas Router
|
||||
ME[GET /api/atlas/metrics]
|
||||
AC[(atlas_action_plans_cache<br/>SQLite)]
|
||||
end
|
||||
|
||||
TS -->|tab = ivanti| ID
|
||||
TS -->|tab = ivanti| IC
|
||||
TS -->|tab = atlas| AD
|
||||
AD -->|fetch on mount + after sync| ME
|
||||
ME -->|SELECT + aggregate| AC
|
||||
```
|
||||
|
||||
### Data Flow: Metrics Fetch
|
||||
|
||||
1. ReportingPage mounts → calls `GET /api/atlas/metrics`
|
||||
2. Backend queries all rows from `atlas_action_plans_cache`, including `plans_json`
|
||||
3. Backend iterates rows, parses each `plans_json`, counts plans by type and status
|
||||
4. Backend returns aggregated JSON: `{ totalHosts, hostsWithPlans, hostsWithoutPlans, plansByType, plansByStatus, totalPlans }`
|
||||
5. Frontend stores result in `atlasMetrics` state
|
||||
6. When "Atlas Coverage" tab is active, three donut components render from this state
|
||||
|
||||
### Data Flow: Refresh After Sync
|
||||
|
||||
1. User clicks Atlas sync button → `POST /api/atlas/sync` (existing)
|
||||
2. On success, frontend calls `GET /api/atlas/metrics` again
|
||||
3. Atlas donut charts re-render with updated data
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend: GET /api/atlas/metrics Endpoint
|
||||
|
||||
Added inside the existing `createAtlasRouter(db, requireAuth)` factory function in `backend/routes/atlas.js`.
|
||||
|
||||
| Method | Path | Auth | Group | Description |
|
||||
|--------|------|------|-------|-------------|
|
||||
| `GET` | `/metrics` | requireAuth | any | Return aggregated Atlas metrics for chart rendering |
|
||||
|
||||
**Response shape**:
|
||||
|
||||
```json
|
||||
{
|
||||
"totalHosts": 42,
|
||||
"hostsWithPlans": 28,
|
||||
"hostsWithoutPlans": 14,
|
||||
"plansByType": {
|
||||
"decommission": 5,
|
||||
"remediation": 18,
|
||||
"false_positive": 3,
|
||||
"risk_acceptance": 8,
|
||||
"scan_exclusion": 2
|
||||
},
|
||||
"plansByStatus": {
|
||||
"active": 25,
|
||||
"expired": 7,
|
||||
"completed": 4
|
||||
},
|
||||
"totalPlans": 36
|
||||
}
|
||||
```
|
||||
|
||||
**Implementation approach**:
|
||||
|
||||
1. Query all rows: `SELECT has_action_plan, plans_json FROM atlas_action_plans_cache`
|
||||
2. Initialize counters: `totalHosts = rows.length`, `hostsWithPlans = 0`, `hostsWithoutPlans = 0`, `plansByType = {}`, `plansByStatus = {}`, `totalPlans = 0`
|
||||
3. For each row:
|
||||
- If `has_action_plan === 1`, increment `hostsWithPlans`; else increment `hostsWithoutPlans`
|
||||
- Try to parse `plans_json`; on failure, skip plan details for that row
|
||||
- For each plan in the parsed array, increment the corresponding `plansByType[plan.plan_type]` and `plansByStatus[plan.status]` counters, and increment `totalPlans`
|
||||
4. Return the aggregated object
|
||||
|
||||
Uses the existing `dbAll` promise wrapper already defined in `atlas.js`.
|
||||
|
||||
### Frontend: Tab System
|
||||
|
||||
A horizontal tab bar rendered inside the Metric Graphs panel header, to the right of the "Metric Graphs" title and `PieChart` icon.
|
||||
|
||||
**State**: `metricsTab` — `'ivanti'` (default) or `'atlas'`
|
||||
|
||||
**Tab bar structure**:
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ [PieChart icon] METRIC GRAPHS [Ivanti Findings] [Atlas Coverage] │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Styling**:
|
||||
- Tabs use `role="tab"` and `aria-selected`; the content area uses `role="tabpanel"`
|
||||
- Active tab: `color: #F59E0B`, `borderBottom: 2px solid #F59E0B`
|
||||
- Inactive tab: `color: #64748B`, no bottom border
|
||||
- Hover on inactive: `background: rgba(245, 158, 11, 0.06)`
|
||||
- Font: `'JetBrains Mono', monospace`, `0.7rem`, `uppercase`, `letterSpacing: 0.08em`
|
||||
- Tabs are keyboard navigable via Tab and Enter keys
|
||||
|
||||
### Frontend: Atlas Metrics State
|
||||
|
||||
New state variables in the ReportingPage component:
|
||||
|
||||
```javascript
|
||||
const [metricsTab, setMetricsTab] = useState('ivanti');
|
||||
const [atlasMetrics, setAtlasMetrics] = useState(null);
|
||||
const [atlasMetricsLoading, setAtlasMetricsLoading] = useState(false);
|
||||
const [atlasMetricsError, setAtlasMetricsError] = useState(null);
|
||||
```
|
||||
|
||||
New fetch function:
|
||||
|
||||
```javascript
|
||||
const fetchAtlasMetrics = useCallback(async () => {
|
||||
setAtlasMetricsLoading(true);
|
||||
setAtlasMetricsError(null);
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/atlas/metrics`, { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setAtlasMetrics(data);
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
setAtlasMetricsError(err.error || 'Failed to fetch Atlas metrics');
|
||||
}
|
||||
} catch (err) {
|
||||
setAtlasMetricsError(err.message);
|
||||
} finally {
|
||||
setAtlasMetricsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
```
|
||||
|
||||
Called on mount (in the existing `useEffect`) and after a successful Atlas sync.
|
||||
|
||||
### Frontend: Atlas Donut Charts
|
||||
|
||||
Three new inline components defined in ReportingPage.js, following the same pattern as `StatusDonut`, `ActionCoverageDonut`, and `FPWorkflowDonut`. All reuse the existing `polarToCartesian` and `donutArcPath` helper functions.
|
||||
|
||||
**AtlasCoverageDonut**
|
||||
- Props: `{ hostsWithPlans, hostsWithoutPlans, totalHosts }`
|
||||
- Segments: emerald (`#10B981`) for with plans, amber (`#F59E0B`) for without plans
|
||||
- Center text: `totalHosts` count, "HOSTS" label
|
||||
- Empty state: "No data — run Atlas Sync"
|
||||
|
||||
**AtlasPlanTypeDonut**
|
||||
- Props: `{ plansByType, totalPlans }`
|
||||
- Color map: `decommission: #EF4444`, `remediation: #0EA5E9`, `false_positive: #A855F7`, `risk_acceptance: #F59E0B`, `scan_exclusion: #64748B`
|
||||
- Center text: `totalPlans` count, "PLANS" label
|
||||
- Legend: only shows types with count > 0
|
||||
- Empty state: "No plans — run Atlas Sync"
|
||||
|
||||
**AtlasPlanStatusDonut**
|
||||
- Props: `{ plansByStatus, totalPlans }`
|
||||
- Color map: `active: #10B981`, `expired: #EF4444`, `completed: #0EA5E9`, fallback: `#64748B`
|
||||
- Center text: `totalPlans` count, "STATUS" label
|
||||
- Legend: only shows statuses with count > 0
|
||||
- Empty state: "No plans — run Atlas Sync"
|
||||
|
||||
All three follow the same SVG dimensions: 180px size, 72px outer radius, 48px inner radius.
|
||||
|
||||
### Frontend: Metric Graphs Panel Layout
|
||||
|
||||
When "Ivanti Findings" tab is active:
|
||||
- Existing four donuts in horizontal flex row with dividers (unchanged)
|
||||
- IvantiCountsChart rendered below the panel (unchanged)
|
||||
|
||||
When "Atlas Coverage" tab is active:
|
||||
- Three Atlas donuts in horizontal flex row with dividers (same layout pattern)
|
||||
- IvantiCountsChart hidden
|
||||
|
||||
## Data Models
|
||||
|
||||
### Metrics Endpoint Response
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `totalHosts` | integer | Count of all rows in `atlas_action_plans_cache` |
|
||||
| `hostsWithPlans` | integer | Count of rows where `has_action_plan = 1` |
|
||||
| `hostsWithoutPlans` | integer | Count of rows where `has_action_plan = 0` |
|
||||
| `plansByType` | object | Map of plan type string → integer count |
|
||||
| `plansByStatus` | object | Map of plan status string → integer count |
|
||||
| `totalPlans` | integer | Sum of all plans across all hosts |
|
||||
|
||||
### Existing Atlas Cache Table (no changes)
|
||||
|
||||
The `atlas_action_plans_cache` table is unchanged. The metrics endpoint reads from it:
|
||||
|
||||
| Column | Type | Used by metrics endpoint |
|
||||
|--------|------|--------------------------|
|
||||
| `has_action_plan` | INTEGER | Counting hosts with/without plans |
|
||||
| `plans_json` | TEXT | Parsed to count plans by type and status |
|
||||
|
||||
### Plan Object Shape (within `plans_json`)
|
||||
|
||||
The metrics endpoint reads `plan_type` and `status` from each plan object in the JSON array. The Atlas API returns these fields as strings. Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"action_plan_id": "ap-123",
|
||||
"plan_type": "remediation",
|
||||
"status": "active",
|
||||
"commit_date": "2026-07-01"
|
||||
}
|
||||
```
|
||||
|
||||
Known `plan_type` values: `decommission`, `remediation`, `false_positive`, `risk_acceptance`, `scan_exclusion`
|
||||
|
||||
Known `status` values: `active`, `expired`, `completed` (the frontend handles unknown values with a neutral color)
|
||||
|
||||
|
||||
## 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: Metrics aggregation correctness
|
||||
|
||||
*For any* array of cache rows — each with a `has_action_plan` flag (0 or 1) and a `plans_json` string that is either valid JSON containing an array of plan objects (each with `plan_type` and `status` fields) or invalid JSON — the metrics aggregation function SHALL produce:
|
||||
- `totalHosts` equal to the number of rows
|
||||
- `hostsWithPlans + hostsWithoutPlans` equal to `totalHosts`
|
||||
- `hostsWithPlans` equal to the count of rows where `has_action_plan === 1`
|
||||
- `totalPlans` equal to the sum of plan array lengths across all rows with valid JSON
|
||||
- Each key in `plansByType` maps to the count of plans with that `plan_type` across all valid rows
|
||||
- Each key in `plansByStatus` maps to the count of plans with that `status` across all valid rows
|
||||
- Rows with invalid `plans_json` are counted in `totalHosts` and `hostsWithPlans`/`hostsWithoutPlans` but their plans are excluded from `plansByType`, `plansByStatus`, and `totalPlans`
|
||||
|
||||
**Validates: Requirements 1.3, 1.4, 1.5**
|
||||
|
||||
### Property 2: Coverage donut data correctness
|
||||
|
||||
*For any* non-negative integer pair `(hostsWithPlans, hostsWithoutPlans)` where `totalHosts = hostsWithPlans + hostsWithoutPlans > 0`, the Coverage Donut SHALL display `totalHosts` as center text, and the legend SHALL show counts matching the input values with percentages that equal `(count / totalHosts) * 100` for each segment.
|
||||
|
||||
**Validates: Requirements 3.3, 3.4**
|
||||
|
||||
### Property 3: Plan type donut data correctness
|
||||
|
||||
*For any* `plansByType` object mapping plan type strings to positive integer counts, and `totalPlans` equal to the sum of those counts, the Plan Type Donut SHALL display `totalPlans` as center text, the legend SHALL include only types with count greater than zero, and each legend entry's percentage SHALL equal `(count / totalPlans) * 100`.
|
||||
|
||||
**Validates: Requirements 4.3, 4.4**
|
||||
|
||||
### Property 4: Plan status donut data correctness
|
||||
|
||||
*For any* `plansByStatus` object mapping status strings to positive integer counts, and `totalPlans` equal to the sum of those counts, the Plan Status Donut SHALL display `totalPlans` as center text, the legend SHALL include only statuses with count greater than zero, and each legend entry's percentage SHALL equal `(count / totalPlans) * 100`.
|
||||
|
||||
**Validates: Requirements 5.3, 5.4**
|
||||
|
||||
### Property 5: Plan status color assignment
|
||||
|
||||
*For any* status string, the Plan Status Donut color assignment function SHALL return `#10B981` if the status is `"active"`, `#EF4444` if `"expired"`, `#0EA5E9` if `"completed"`, and `#64748B` for any other string value.
|
||||
|
||||
**Validates: Requirements 5.2**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Backend Errors
|
||||
|
||||
| Error Scenario | Handling | HTTP Status | Response |
|
||||
|----------------|----------|-------------|----------|
|
||||
| Atlas not configured (missing env vars) | Return 503 with descriptive message | 503 | `{ error: 'Atlas API is not configured...' }` |
|
||||
| Database query failure | Catch error, log, return 500 | 500 | `{ error: 'Failed to fetch Atlas metrics.' }` |
|
||||
| Invalid JSON in `plans_json` column | Skip that row's plan details, continue processing | N/A (handled internally) | Metrics still returned with correct counts for valid rows |
|
||||
| Empty cache table | Return metrics object with all zeros | 200 | `{ totalHosts: 0, hostsWithPlans: 0, hostsWithoutPlans: 0, plansByType: {}, plansByStatus: {}, totalPlans: 0 }` |
|
||||
| Unauthenticated request | Auth middleware rejects | 401 | `{ error: 'Authentication required' }` |
|
||||
|
||||
### Frontend Errors
|
||||
|
||||
| Error Scenario | Handling | User Impact |
|
||||
|----------------|----------|-------------|
|
||||
| Metrics fetch returns non-200 | Store error message in `atlasMetricsError` state | Error message displayed in Atlas Coverage tab content area |
|
||||
| Metrics fetch network failure | Catch error, store message | Error message displayed with failure reason |
|
||||
| Metrics fetch in progress | `atlasMetricsLoading = true` | Loading spinner shown in Atlas Coverage tab content area |
|
||||
| Atlas metrics data is null (not yet fetched) | Donut components check for null/undefined | Loading state or empty state shown |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
|
||||
Unit tests cover specific examples, edge cases, and integration points:
|
||||
|
||||
**Backend — Metrics Aggregation (`GET /api/atlas/metrics`)**:
|
||||
- Returns all-zero metrics when cache table is empty
|
||||
- Correctly counts hosts with and without plans from seeded data
|
||||
- Correctly aggregates plansByType from multiple hosts
|
||||
- Correctly aggregates plansByStatus from multiple hosts
|
||||
- Skips plan details for rows with invalid JSON but still counts the host
|
||||
- Returns 503 when Atlas is not configured
|
||||
- Requires authentication (returns 401 without session)
|
||||
|
||||
**Frontend — Tab System**:
|
||||
- Renders two tabs with correct labels
|
||||
- Defaults to "Ivanti Findings" tab on mount
|
||||
- Switches content when tab is clicked
|
||||
- Active tab has correct ARIA attributes (`aria-selected="true"`)
|
||||
- Tab panel has `role="tabpanel"` attribute
|
||||
- Keyboard navigation works (Tab + Enter)
|
||||
|
||||
**Frontend — Atlas Donut Charts**:
|
||||
- Coverage donut shows "No data — run Atlas Sync" when totalHosts is 0
|
||||
- Plan type donut shows "No plans — run Atlas Sync" when totalPlans is 0
|
||||
- Plan status donut shows "No plans — run Atlas Sync" when totalPlans is 0
|
||||
- SVG dimensions are 180px with 72px outer and 48px inner radius
|
||||
- Color assignments match specification for each plan type
|
||||
- Color assignments match specification for known statuses
|
||||
|
||||
**Frontend — Data Fetching**:
|
||||
- Fetches metrics on mount
|
||||
- Re-fetches metrics after successful Atlas sync
|
||||
- Does not re-fetch on tab switch
|
||||
- Shows loading indicator while fetch is in progress
|
||||
- Shows error message when fetch fails
|
||||
|
||||
**Frontend — IvantiCountsChart Visibility**:
|
||||
- Rendered when Ivanti tab is active
|
||||
- Not rendered when Atlas tab is active
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based tests verify universal properties across generated inputs. Each test runs a minimum of 100 iterations.
|
||||
|
||||
**Library**: [fast-check](https://github.com/dubzzz/fast-check) — the standard PBT library for JavaScript/Node.js.
|
||||
|
||||
**Configuration**: Each property test runs with `{ numRuns: 100 }` minimum.
|
||||
|
||||
**Tag format**: Each test includes a comment referencing its design property:
|
||||
```javascript
|
||||
// Feature: atlas-metrics-report, Property 1: Metrics aggregation correctness
|
||||
```
|
||||
|
||||
| Property | Test Description | Generator Strategy |
|
||||
|----------|-----------------|-------------------|
|
||||
| Property 1 | Metrics aggregation correctness | Generate arrays of objects with `has_action_plan` (0 or 1) and `plans_json` (either valid JSON array of `{plan_type, status}` objects or random invalid strings). Extract the aggregation logic into a pure function, call it with generated input, verify all invariants. |
|
||||
| Property 2 | Coverage donut data correctness | Generate random `(hostsWithPlans, hostsWithoutPlans)` pairs of non-negative integers (at least one > 0). Render `AtlasCoverageDonut`, verify center text equals sum and legend percentages are mathematically correct. |
|
||||
| Property 3 | Plan type donut data correctness | Generate random `plansByType` objects with 1–5 plan type keys mapped to positive integers. Render `AtlasPlanTypeDonut`, verify center text equals sum and legend entries match input. |
|
||||
| Property 4 | Plan status donut data correctness | Generate random `plansByStatus` objects with 1–4 status keys mapped to positive integers. Render `AtlasPlanStatusDonut`, verify center text equals sum and legend entries match input. |
|
||||
| Property 5 | Plan status color assignment | Generate random strings (mix of known statuses and arbitrary strings). Verify the color function returns the correct color for known statuses and the fallback for unknowns. |
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- Full metrics flow: seed `atlas_action_plans_cache` with varied data → call `GET /api/atlas/metrics` → verify response matches expected aggregation
|
||||
- Empty cache flow: ensure empty cache returns all-zero metrics
|
||||
- Corrupt data flow: seed cache with mix of valid and invalid `plans_json` → verify metrics are correct for valid rows
|
||||
124
.kiro/specs/atlas-metrics-report/requirements.md
Normal file
124
.kiro/specs/atlas-metrics-report/requirements.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
Add a tab system to the existing Metric Graphs panel on the ReportingPage so that Atlas-specific coverage metrics live alongside the existing Ivanti donut charts without cluttering the current layout. The existing four donut charts (Open vs Closed, Action Coverage, FP Finding Status, FP Workflow Status) move under an "Ivanti Findings" tab. A new "Atlas Coverage" tab displays donut charts derived from the cached Atlas action plan data — plan coverage, plan type breakdown, and plan status distribution. A new backend endpoint on the existing Atlas router aggregates the cached data into chart-ready metrics, keeping server.js untouched.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Dashboard**: The STEAM Security Dashboard frontend React application
|
||||
- **ReportingPage**: The existing frontend page (`frontend/src/components/pages/ReportingPage.js`) displaying Ivanti host findings, metric charts, and the findings table
|
||||
- **Metric_Graphs_Panel**: The existing panel on the ReportingPage containing four SVG donut charts and the IvantiCountsChart trend line
|
||||
- **Tab_System**: A horizontal tab bar added to the Metric_Graphs_Panel header that switches between Ivanti and Atlas chart views
|
||||
- **Atlas_Cache**: The existing `atlas_action_plans_cache` SQLite table storing per-host action plan status, including `plans_json`
|
||||
- **Atlas_Router**: The existing Express route module (`backend/routes/atlas.js`) mounted at `/api/atlas`
|
||||
- **Atlas_Metrics_Endpoint**: A new `GET /api/atlas/metrics` endpoint on the Atlas_Router that returns aggregated chart data
|
||||
- **Coverage_Donut**: A donut chart showing hosts with action plans vs hosts without action plans
|
||||
- **Plan_Type_Donut**: A donut chart showing the distribution of action plans across the five plan types (decommission, remediation, false_positive, risk_acceptance, scan_exclusion)
|
||||
- **Plan_Status_Donut**: A donut chart showing the distribution of action plans across their status values (e.g. active, expired, completed)
|
||||
- **Action_Plan**: A compliance plan in Atlas with a type, commit date, and status — stored in the `plans_json` column of the Atlas_Cache
|
||||
- **Host_ID**: The shared numeric identifier linking an Ivanti host finding to an Atlas host
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Atlas Metrics Aggregation Endpoint
|
||||
|
||||
**User Story:** As a frontend developer, I want a single endpoint that returns pre-aggregated Atlas metrics, so that the frontend can render donut charts without parsing raw plan JSON on the client.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Atlas_Router SHALL expose a `GET /api/atlas/metrics` endpoint that requires authentication
|
||||
2. WHEN the metrics endpoint is called, THE Atlas_Router SHALL query all rows from the Atlas_Cache table including the `plans_json` column
|
||||
3. WHEN rows are retrieved, THE Atlas_Router SHALL compute and return a JSON object containing: `totalHosts` (integer count of all cached hosts), `hostsWithPlans` (integer count of hosts where `has_action_plan` equals 1), `hostsWithoutPlans` (integer count of hosts where `has_action_plan` equals 0), `plansByType` (object mapping each plan type string to its integer count across all hosts), `plansByStatus` (object mapping each plan status string to its integer count across all hosts), and `totalPlans` (integer sum of all plans across all hosts)
|
||||
4. WHEN the Atlas_Cache table is empty, THE Atlas_Router SHALL return the metrics object with all counts set to zero and `plansByType` and `plansByStatus` as empty objects
|
||||
5. IF a row's `plans_json` column contains invalid JSON, THEN THE Atlas_Router SHALL skip that row's plan details and continue processing remaining rows
|
||||
6. THE Atlas_Metrics_Endpoint SHALL NOT modify server.js — the endpoint SHALL be added to the existing Atlas_Router module only
|
||||
|
||||
### Requirement 2: Tab System in Metric Graphs Panel
|
||||
|
||||
**User Story:** As a dashboard user, I want the Metric Graphs panel to have tabs, so that I can switch between Ivanti findings metrics and Atlas coverage metrics without the panel becoming overcrowded.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL display a horizontal tab bar in the Metric_Graphs_Panel header area, to the right of the "Metric Graphs" title
|
||||
2. THE Tab_System SHALL contain exactly two tabs labeled "Ivanti Findings" and "Atlas Coverage"
|
||||
3. WHEN the ReportingPage loads, THE Tab_System SHALL default to the "Ivanti Findings" tab as the active tab
|
||||
4. WHEN the "Ivanti Findings" tab is active, THE Metric_Graphs_Panel SHALL display the existing four donut charts (Open vs Closed, Action Coverage, FP Finding Status, FP Workflow Status) in their current layout
|
||||
5. WHEN the "Atlas Coverage" tab is active, THE Metric_Graphs_Panel SHALL display the Atlas-specific donut charts (Coverage_Donut, Plan_Type_Donut, Plan_Status_Donut) in a horizontal flex row matching the existing chart layout pattern
|
||||
6. THE Tab_System SHALL visually indicate the active tab using the design system accent color and a bottom border highlight
|
||||
7. THE Tab_System SHALL use monospace font, uppercase text, and letter spacing consistent with the existing Metric_Graphs_Panel header style
|
||||
8. WHEN the user switches tabs, THE Metric_Graphs_Panel content SHALL update immediately without a full page reload
|
||||
|
||||
### Requirement 3: Atlas Coverage Donut Chart
|
||||
|
||||
**User Story:** As a dashboard user, I want to see what percentage of cached hosts have Atlas action plans, so that I can gauge overall compliance coverage at a glance.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the "Atlas Coverage" tab is active, THE Dashboard SHALL display a Coverage_Donut chart showing hosts with plans vs hosts without plans
|
||||
2. THE Coverage_Donut SHALL use emerald (`#10B981`) for hosts with plans and amber (`#F59E0B`) for hosts without plans
|
||||
3. THE Coverage_Donut SHALL display the total host count as center text with a "HOSTS" label below it
|
||||
4. THE Coverage_Donut SHALL include a legend showing the count and percentage for each segment
|
||||
5. WHEN the Atlas_Cache contains no data, THE Coverage_Donut SHALL display a "No data — run Atlas Sync" message instead of an empty chart
|
||||
6. THE Coverage_Donut SHALL follow the same SVG donut dimensions and styling as the existing StatusDonut component (180px size, 72px outer radius, 48px inner radius)
|
||||
|
||||
### Requirement 4: Plan Type Distribution Donut Chart
|
||||
|
||||
**User Story:** As a dashboard user, I want to see how action plans are distributed across plan types, so that I can understand the remediation strategy mix.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the "Atlas Coverage" tab is active, THE Dashboard SHALL display a Plan_Type_Donut chart showing the count of plans per type
|
||||
2. THE Plan_Type_Donut SHALL assign a distinct color to each plan type: decommission (`#EF4444`), remediation (`#0EA5E9`), false_positive (`#A855F7`), risk_acceptance (`#F59E0B`), scan_exclusion (`#64748B`)
|
||||
3. THE Plan_Type_Donut SHALL display the total plan count as center text with a "PLANS" label below it
|
||||
4. THE Plan_Type_Donut SHALL include a legend showing the label, count, and percentage for each plan type that has a count greater than zero
|
||||
5. WHEN no plans exist in the Atlas_Cache, THE Plan_Type_Donut SHALL display a "No plans — run Atlas Sync" message instead of an empty chart
|
||||
6. THE Plan_Type_Donut SHALL follow the same SVG donut dimensions and styling as the existing donut chart components
|
||||
|
||||
### Requirement 5: Plan Status Distribution Donut Chart
|
||||
|
||||
**User Story:** As a dashboard user, I want to see how action plans are distributed across statuses, so that I can identify how many plans are active vs expired or completed.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the "Atlas Coverage" tab is active, THE Dashboard SHALL display a Plan_Status_Donut chart showing the count of plans per status value
|
||||
2. THE Plan_Status_Donut SHALL assign colors to known statuses: active (`#10B981`), expired (`#EF4444`), completed (`#0EA5E9`), and use a neutral color (`#64748B`) for any unrecognized status values
|
||||
3. THE Plan_Status_Donut SHALL display the total plan count as center text with a "STATUS" label below it
|
||||
4. THE Plan_Status_Donut SHALL include a legend showing the label, count, and percentage for each status that has a count greater than zero
|
||||
5. WHEN no plans exist in the Atlas_Cache, THE Plan_Status_Donut SHALL display a "No plans — run Atlas Sync" message instead of an empty chart
|
||||
6. THE Plan_Status_Donut SHALL follow the same SVG donut dimensions and styling as the existing donut chart components
|
||||
|
||||
### Requirement 6: Atlas Metrics Data Fetching
|
||||
|
||||
**User Story:** As a frontend developer, I want the Atlas metrics fetched efficiently and kept in sync with the Atlas cache, so that the charts reflect the latest synced data without unnecessary API calls.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the ReportingPage mounts, THE Dashboard SHALL fetch Atlas metrics from `GET /api/atlas/metrics` and store the result in component state
|
||||
2. WHEN an Atlas sync completes successfully (via the existing Atlas sync button), THE Dashboard SHALL re-fetch Atlas metrics from `GET /api/atlas/metrics` to update the charts
|
||||
3. WHILE the Atlas metrics fetch is in progress, THE Dashboard SHALL display a loading indicator in the Atlas Coverage tab content area
|
||||
4. IF the Atlas metrics fetch fails, THEN THE Dashboard SHALL display an error message in the Atlas Coverage tab content area with the failure reason
|
||||
5. THE Dashboard SHALL NOT fetch Atlas metrics on every tab switch — the data SHALL be fetched once on mount and refreshed only after a sync operation
|
||||
|
||||
### Requirement 7: IvantiCountsChart Visibility with Tabs
|
||||
|
||||
**User Story:** As a dashboard user, I want the IvantiCountsChart trend line to remain visible when the Ivanti Findings tab is active, so that the existing reporting experience is preserved.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the "Ivanti Findings" tab is active, THE Dashboard SHALL display the IvantiCountsChart trend line below the Metric_Graphs_Panel, matching its current position
|
||||
2. WHEN the "Atlas Coverage" tab is active, THE Dashboard SHALL hide the IvantiCountsChart trend line since it is not relevant to Atlas metrics
|
||||
3. THE IvantiCountsChart component SHALL continue to function identically to its current behavior when visible
|
||||
|
||||
### Requirement 8: Tab System Styling and Accessibility
|
||||
|
||||
**User Story:** As a dashboard user, I want the tab system to be visually consistent with the existing design system and keyboard accessible, so that the interface feels cohesive and usable.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Tab_System tabs SHALL use inline styles consistent with the design system: dark background, monospace font at 0.7rem, uppercase text, 0.08em letter spacing
|
||||
2. THE active tab SHALL have a bottom border of 2px solid using the panel accent color (`#F59E0B`) and brighter text color (`#F59E0B`)
|
||||
3. THE inactive tab SHALL have muted text color (`#64748B`) and no bottom border highlight
|
||||
4. WHEN the user hovers over an inactive tab, THE tab SHALL display a subtle background color change to indicate interactivity
|
||||
5. THE Tab_System tabs SHALL use `role="tab"`, `aria-selected`, and `role="tabpanel"` attributes for screen reader accessibility
|
||||
6. THE Tab_System tabs SHALL be keyboard navigable using Tab and Enter keys
|
||||
163
.kiro/specs/atlas-metrics-report/tasks.md
Normal file
163
.kiro/specs/atlas-metrics-report/tasks.md
Normal file
@@ -0,0 +1,163 @@
|
||||
# Implementation Plan: Atlas Metrics Report
|
||||
|
||||
## Overview
|
||||
|
||||
Add a tab system to the Metric Graphs panel on the ReportingPage, with an "Ivanti Findings" tab (existing donuts) and an "Atlas Coverage" tab (three new donut charts). A new `GET /api/atlas/metrics` endpoint aggregates cached Atlas action plan data into chart-ready metrics. All backend changes stay within `backend/routes/atlas.js`. Frontend changes are in `frontend/src/components/pages/ReportingPage.js`.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Implement the Atlas metrics aggregation endpoint
|
||||
- [x] 1.1 Add `GET /metrics` route inside the existing `createAtlasRouter` factory function in `backend/routes/atlas.js`
|
||||
- Query all rows from `atlas_action_plans_cache` using the existing `dbAll` helper: `SELECT has_action_plan, plans_json FROM atlas_action_plans_cache`
|
||||
- Extract the aggregation logic into a pure function `aggregateAtlasMetrics(rows)` that takes an array of `{ has_action_plan, plans_json }` objects and returns `{ totalHosts, hostsWithPlans, hostsWithoutPlans, plansByType, plansByStatus, totalPlans }`
|
||||
- For each row: count hosts with/without plans based on `has_action_plan`; parse `plans_json` and count plans by `plan_type` and `status`; skip plan details for rows with invalid JSON
|
||||
- Return 503 if Atlas is not configured; return 500 on DB errors; require authentication via `requireAuth(db)`
|
||||
- Return all-zero metrics with empty objects when the cache table is empty
|
||||
- Do NOT modify `server.js` — the route is added inside the existing router factory
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6_
|
||||
|
||||
- [x] 1.2 Write property test for metrics aggregation (Property 1)
|
||||
- **Property 1: Metrics aggregation correctness**
|
||||
- Extract `aggregateAtlasMetrics` as a pure exported function for testability
|
||||
- Use fast-check to generate arrays of objects with `has_action_plan` (0 or 1) and `plans_json` (valid JSON arrays of `{ plan_type, status }` objects or invalid strings)
|
||||
- Verify: `totalHosts === rows.length`, `hostsWithPlans + hostsWithoutPlans === totalHosts`, `hostsWithPlans` equals count of rows where `has_action_plan === 1`, `totalPlans` equals sum of valid plan array lengths, `plansByType` and `plansByStatus` counts match individual plan fields, rows with invalid JSON are counted in host totals but excluded from plan counts
|
||||
- **Validates: Requirements 1.3, 1.4, 1.5**
|
||||
|
||||
- [ ]* 1.3 Write unit tests for the metrics endpoint
|
||||
- Test empty cache returns all-zero metrics
|
||||
- Test correct host counting with seeded data
|
||||
- Test correct plansByType and plansByStatus aggregation
|
||||
- Test rows with invalid `plans_json` are handled gracefully
|
||||
- Test 503 response when Atlas is not configured
|
||||
- Test 401 response for unauthenticated requests
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5_
|
||||
|
||||
- [x] 2. Checkpoint — Verify backend endpoint
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 3. Add tab system to the Metric Graphs panel
|
||||
- [x] 3.1 Add tab state and tab bar UI to the Metric Graphs panel header in `ReportingPage.js`
|
||||
- Add `metricsTab` state initialized to `'ivanti'`
|
||||
- Render a horizontal tab bar to the right of the "Metric Graphs" title with two tabs: "Ivanti Findings" and "Atlas Coverage"
|
||||
- Active tab styling: `color: #F59E0B`, `borderBottom: 2px solid #F59E0B`
|
||||
- Inactive tab styling: `color: #64748B`, no bottom border
|
||||
- Hover on inactive: `background: rgba(245, 158, 11, 0.06)`
|
||||
- Font: `'JetBrains Mono', monospace`, `0.7rem`, `uppercase`, `letterSpacing: 0.08em`
|
||||
- Add `role="tab"`, `aria-selected` attributes on tabs; `role="tabpanel"` on content area
|
||||
- Tabs navigable via Tab and Enter keys
|
||||
- _Requirements: 2.1, 2.2, 2.3, 2.6, 2.7, 2.8, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6_
|
||||
|
||||
- [x] 3.2 Conditionally render Ivanti donuts vs Atlas content based on active tab
|
||||
- When `metricsTab === 'ivanti'`: show existing four donut charts in their current layout (unchanged)
|
||||
- When `metricsTab === 'atlas'`: show placeholder for Atlas donut charts (to be implemented in task 5)
|
||||
- _Requirements: 2.4, 2.5_
|
||||
|
||||
- [x] 3.3 Conditionally render IvantiCountsChart based on active tab
|
||||
- Show `IvantiCountsChart` only when `metricsTab === 'ivanti'`
|
||||
- Hide it when `metricsTab === 'atlas'`
|
||||
- _Requirements: 7.1, 7.2, 7.3_
|
||||
|
||||
- [x] 4. Add Atlas metrics data fetching
|
||||
- [x] 4.1 Add Atlas metrics state and fetch function to `ReportingPage.js`
|
||||
- Add state: `atlasMetrics` (null), `atlasMetricsLoading` (false), `atlasMetricsError` (null)
|
||||
- Add `fetchAtlasMetrics` callback that calls `GET /api/atlas/metrics` with `credentials: 'include'`
|
||||
- On success: store data in `atlasMetrics`; on error: store message in `atlasMetricsError`
|
||||
- Set loading state during fetch
|
||||
- _Requirements: 6.1, 6.3, 6.4_
|
||||
|
||||
- [x] 4.2 Call `fetchAtlasMetrics` on mount and after successful Atlas sync
|
||||
- Add `fetchAtlasMetrics()` call in the existing mount `useEffect`
|
||||
- After a successful Atlas sync (existing sync handler), call `fetchAtlasMetrics()` to refresh
|
||||
- Do NOT re-fetch on tab switch
|
||||
- _Requirements: 6.1, 6.2, 6.5_
|
||||
|
||||
- [x] 5. Implement Atlas donut chart components
|
||||
- [x] 5.1 Implement `AtlasCoverageDonut` component in `ReportingPage.js`
|
||||
- Props: `{ hostsWithPlans, hostsWithoutPlans, totalHosts }`
|
||||
- Segments: emerald (`#10B981`) for with plans, amber (`#F59E0B`) for without plans
|
||||
- Center text: `totalHosts` count, "HOSTS" label
|
||||
- Legend: count and percentage for each segment
|
||||
- Empty state: "No data — run Atlas Sync" when `totalHosts === 0`
|
||||
- Reuse existing `polarToCartesian` and `donutArcPath` helpers; same dimensions (180px, 72px outer, 48px inner)
|
||||
- Follow the same SVG and styling pattern as `StatusDonut`
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.4, 3.5, 3.6_
|
||||
|
||||
- [x] 5.2 Implement `AtlasPlanTypeDonut` component in `ReportingPage.js`
|
||||
- Props: `{ plansByType, totalPlans }`
|
||||
- Color map: `decommission: #EF4444`, `remediation: #0EA5E9`, `false_positive: #A855F7`, `risk_acceptance: #F59E0B`, `scan_exclusion: #64748B`
|
||||
- Center text: `totalPlans` count, "PLANS" label
|
||||
- Legend: only show types with count > 0, with label, count, and percentage
|
||||
- Empty state: "No plans — run Atlas Sync" when `totalPlans === 0`
|
||||
- Same SVG dimensions and styling pattern
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5, 4.6_
|
||||
|
||||
- [x] 5.3 Implement `AtlasPlanStatusDonut` component in `ReportingPage.js`
|
||||
- Props: `{ plansByStatus, totalPlans }`
|
||||
- Color map: `active: #10B981`, `expired: #EF4444`, `completed: #0EA5E9`, fallback: `#64748B`
|
||||
- Extract a `getStatusColor(status)` helper function for color assignment
|
||||
- Center text: `totalPlans` count, "STATUS" label
|
||||
- Legend: only show statuses with count > 0, with label, count, and percentage
|
||||
- Empty state: "No plans — run Atlas Sync" when `totalPlans === 0`
|
||||
- Same SVG dimensions and styling pattern
|
||||
- _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5, 5.6_
|
||||
|
||||
- [x] 5.4 Write property test for Coverage donut data correctness (Property 2)
|
||||
- **Property 2: Coverage donut data correctness**
|
||||
- Use fast-check to generate random `(hostsWithPlans, hostsWithoutPlans)` pairs of non-negative integers where at least one > 0
|
||||
- Render `AtlasCoverageDonut`, verify center text equals `totalHosts`, legend percentages equal `(count / totalHosts) * 100`
|
||||
- **Validates: Requirements 3.3, 3.4**
|
||||
|
||||
- [x] 5.5 Write property test for Plan type donut data correctness (Property 3)
|
||||
- **Property 3: Plan type donut data correctness**
|
||||
- Use fast-check to generate random `plansByType` objects with 1–5 plan type keys mapped to positive integers
|
||||
- Render `AtlasPlanTypeDonut`, verify center text equals sum of counts, legend entries match input, percentages are correct
|
||||
- **Validates: Requirements 4.3, 4.4**
|
||||
|
||||
- [x] 5.6 Write property test for Plan status donut data correctness (Property 4)
|
||||
- **Property 4: Plan status donut data correctness**
|
||||
- Use fast-check to generate random `plansByStatus` objects with 1–4 status keys mapped to positive integers
|
||||
- Render `AtlasPlanStatusDonut`, verify center text equals sum of counts, legend entries match input, percentages are correct
|
||||
- **Validates: Requirements 5.3, 5.4**
|
||||
|
||||
- [x] 5.7 Write property test for Plan status color assignment (Property 5)
|
||||
- **Property 5: Plan status color assignment**
|
||||
- Use fast-check to generate random strings (mix of known statuses and arbitrary strings)
|
||||
- Verify `getStatusColor` returns `#10B981` for "active", `#EF4444` for "expired", `#0EA5E9` for "completed", `#64748B` for any other string
|
||||
- **Validates: Requirements 5.2**
|
||||
|
||||
- [ ]* 5.8 Write unit tests for Atlas donut components
|
||||
- Test Coverage donut empty state message when totalHosts is 0
|
||||
- Test Plan type donut empty state message when totalPlans is 0
|
||||
- Test Plan status donut empty state message when totalPlans is 0
|
||||
- Test SVG dimensions are 180px with correct outer/inner radius
|
||||
- Test color assignments for each plan type and status
|
||||
- _Requirements: 3.5, 4.5, 5.5, 3.6, 4.6, 5.6_
|
||||
|
||||
- [x] 6. Wire Atlas donuts into the Atlas Coverage tab
|
||||
- [x] 6.1 Render Atlas donut charts in the Atlas Coverage tab content area
|
||||
- When `metricsTab === 'atlas'`: render `AtlasCoverageDonut`, `AtlasPlanTypeDonut`, `AtlasPlanStatusDonut` in a horizontal flex row with dividers (same layout pattern as Ivanti donuts)
|
||||
- Pass data from `atlasMetrics` state to each donut component
|
||||
- Show loading indicator while `atlasMetricsLoading` is true
|
||||
- Show error message when `atlasMetricsError` is set
|
||||
- Add chart labels above each donut: "Host Coverage", "Plan Types", "Plan Status" — matching existing label style
|
||||
- _Requirements: 2.5, 3.1, 4.1, 5.1, 6.3, 6.4_
|
||||
|
||||
- [ ]* 6.2 Write integration tests for the full metrics flow
|
||||
- Test: fetch metrics on mount populates Atlas donut charts
|
||||
- Test: tab switch does not trigger re-fetch
|
||||
- Test: loading state shown during fetch
|
||||
- Test: error state shown on fetch failure
|
||||
- _Requirements: 6.1, 6.2, 6.3, 6.4, 6.5_
|
||||
|
||||
- [x] 7. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- All backend changes are confined to `backend/routes/atlas.js` — server.js is NOT modified
|
||||
- The `aggregateAtlasMetrics` function is extracted as a pure function for testability and property-based testing
|
||||
- Property tests use fast-check with `{ numRuns: 100 }` minimum
|
||||
- Checkpoints ensure incremental validation after backend and full integration
|
||||
- The existing donut chart pattern (StatusDonut, ActionCoverageDonut, FPWorkflowDonut) serves as the template for all three Atlas donut components
|
||||
1
.kiro/specs/batch-finding-disposition/.config.kiro
Normal file
1
.kiro/specs/batch-finding-disposition/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "9f5c16d4-43ea-4d7a-beb1-9329d79a5acc", "workflowType": "requirements-first", "specType": "feature"}
|
||||
331
.kiro/specs/batch-finding-disposition/design.md
Normal file
331
.kiro/specs/batch-finding-disposition/design.md
Normal file
@@ -0,0 +1,331 @@
|
||||
# Design Document: Batch Finding Disposition
|
||||
|
||||
## Overview
|
||||
|
||||
This feature adds multi-select capability to the Vulnerability Triage page's findings table, enabling engineers to select multiple findings and add them all to the Ivanti Queue in a single operation. The current flow requires clicking each finding individually, configuring a popover, and submitting one at a time — this design replaces that with a batch selection toolbar and a bulk-add API endpoint while preserving the existing single-select popover for one-off additions.
|
||||
|
||||
The design touches three layers:
|
||||
1. A new `POST /api/ivanti/todo-queue/batch` backend endpoint that accepts an array of findings in a single transactional insert
|
||||
2. Frontend multi-select state management (selection set, shift-click range select, select-all)
|
||||
3. A sticky Selection Toolbar component with workflow type toggles, vendor input, and batch submit
|
||||
|
||||
## Architecture
|
||||
|
||||
The feature extends the existing Ivanti Queue subsystem without introducing new services or tables. The `ivanti_todo_queue` table schema is unchanged — batch add simply inserts multiple rows in a single SQLite transaction.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Frontend ["Frontend (ReportingPage.js)"]
|
||||
CB[Row Checkboxes] --> SS[Selection State<br/>Set of finding IDs]
|
||||
SS --> ST[Selection Toolbar]
|
||||
ST -->|"Add to Queue"| BA[Batch API Call]
|
||||
CB -->|"No selection + click"| PO[AddToQueuePopover<br/>existing single-add]
|
||||
end
|
||||
|
||||
subgraph Backend ["Backend (ivantiTodoQueue.js)"]
|
||||
BA -->|"POST /batch"| BH[Batch Handler]
|
||||
BH -->|"BEGIN TRANSACTION"| DB[(ivanti_todo_queue)]
|
||||
BH -->|"logAudit()"| AL[(audit_logs)]
|
||||
PO -->|"POST /"| SH[Single Handler<br/>existing]
|
||||
SH --> DB
|
||||
end
|
||||
```
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
1. **No new database table or migration** — batch insert reuses the existing `ivanti_todo_queue` schema. Each finding becomes its own row, identical to what the single-add endpoint creates.
|
||||
|
||||
2. **SQLite transaction for atomicity** — all findings in a batch are inserted inside `db.serialize()` with `BEGIN TRANSACTION` / `COMMIT`. If any insert fails, the entire batch is rolled back. This satisfies the all-or-nothing requirement (Req 3.7, 3.8, 3.11).
|
||||
|
||||
3. **Selection state lives in the VulnerabilityTriagePage component** — a `Set<string>` of finding IDs managed via `useState`. This keeps the selection co-located with the existing `findings`, `sorted`, `filtered`, and `queueItems` state. No new context or global store needed.
|
||||
|
||||
4. **Dual-mode checkbox behavior** — when no findings are selected, clicking a checkbox opens the existing `AddToQueuePopover` (preserving the single-select flow per Req 5). Once one or more findings are selected, subsequent checkbox clicks toggle selection instead. This is the simplest UX that satisfies both Req 1 and Req 5.
|
||||
|
||||
5. **Selection Toolbar as inline sticky bar** — rendered between the table header controls and the `<table>` element, using `position: sticky` to stay visible during scroll. This avoids portal complexity and keeps the toolbar visually anchored to the table.
|
||||
|
||||
6. **200-item batch limit** — prevents oversized payloads and keeps SQLite transaction time reasonable. The findings table typically has 200-800 rows, so this covers most realistic batch sizes.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend
|
||||
|
||||
#### `POST /api/ivanti/todo-queue/batch`
|
||||
|
||||
Added to the existing `createIvantiTodoQueueRouter` factory in `backend/routes/ivantiTodoQueue.js`.
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{
|
||||
"findings": [
|
||||
{
|
||||
"finding_id": "FID-12345",
|
||||
"finding_title": "OpenSSL vulnerability",
|
||||
"cves": ["CVE-2024-0001"],
|
||||
"ip_address": "10.0.1.50"
|
||||
}
|
||||
],
|
||||
"workflow_type": "FP",
|
||||
"vendor": "Juniper"
|
||||
}
|
||||
```
|
||||
|
||||
**Validation rules:**
|
||||
- `findings` — array, 1–200 items
|
||||
- Each item: `finding_id` required, non-empty string; `finding_title`, `cves`, `ip_address` optional
|
||||
- `workflow_type` — must be `FP`, `Archer`, or `CARD`
|
||||
- `vendor` — required non-empty string (≤200 chars) for FP/Archer; ignored for CARD
|
||||
- If any finding fails validation, reject entire batch with 400
|
||||
|
||||
**Auth:** `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
|
||||
**Response (201):**
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": 42,
|
||||
"user_id": 1,
|
||||
"finding_id": "FID-12345",
|
||||
"finding_title": "OpenSSL vulnerability",
|
||||
"cves_json": "[\"CVE-2024-0001\"]",
|
||||
"ip_address": "10.0.1.50",
|
||||
"vendor": "Juniper",
|
||||
"workflow_type": "FP",
|
||||
"status": "pending",
|
||||
"created_at": "2025-01-15 12:00:00",
|
||||
"updated_at": "2025-01-15 12:00:00",
|
||||
"cves": ["CVE-2024-0001"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Error responses:**
|
||||
- `400` — validation failure (descriptive message)
|
||||
- `401` — not authenticated
|
||||
- `403` — insufficient permissions
|
||||
- `500` — database transaction failure (all inserts rolled back)
|
||||
|
||||
### Frontend
|
||||
|
||||
#### Selection State (in VulnerabilityTriagePage)
|
||||
|
||||
New state variables added to the main component:
|
||||
|
||||
```javascript
|
||||
const [selectedIds, setSelectedIds] = useState(new Set()); // Set<string> of finding IDs
|
||||
const [lastClickedId, setLastClickedId] = useState(null); // for shift-click range select
|
||||
const [batchSubmitting, setBatchSubmitting] = useState(false); // loading state
|
||||
const [batchError, setBatchError] = useState(null); // error message from failed batch
|
||||
const [batchWorkflowType, setBatchWorkflowType] = useState('FP');
|
||||
const [batchVendor, setBatchVendor] = useState('');
|
||||
```
|
||||
|
||||
#### Checkbox Click Logic
|
||||
|
||||
```
|
||||
onClick(finding, event):
|
||||
if finding is already queued → return (no-op)
|
||||
if selectedIds.size === 0 AND not shift-click:
|
||||
→ open AddToQueuePopover (existing single-select flow)
|
||||
else:
|
||||
if shift-click AND lastClickedId exists:
|
||||
→ range-select all visible findings between lastClickedId and finding.id
|
||||
else:
|
||||
→ toggle finding.id in selectedIds
|
||||
set lastClickedId = finding.id
|
||||
```
|
||||
|
||||
#### SelectionToolbar Component
|
||||
|
||||
Rendered inline above the table when `selectedIds.size > 0`. Contains:
|
||||
- Selected count badge
|
||||
- "Clear Selection" button
|
||||
- Workflow type toggle buttons (FP / Archer / CARD) with existing color scheme
|
||||
- Vendor text input (hidden when CARD selected)
|
||||
- "Add to Queue" submit button (disabled until valid)
|
||||
- Error message display area
|
||||
|
||||
#### Selection Persistence Across Filters
|
||||
|
||||
When `columnFilters`, `actionFilter`, or `excFilter` change, the selection set is pruned to only include IDs that remain in the `filtered` array. This is done via a `useEffect` that intersects `selectedIds` with the current filtered finding IDs.
|
||||
|
||||
#### Select All / Deselect All
|
||||
|
||||
The checkbox column header renders a "Select All" control when `selectedIds.size > 0` or as a standard header otherwise. Clicking it:
|
||||
- If not all visible non-queued findings are selected → selects all visible non-queued findings
|
||||
- If all are already selected → deselects all
|
||||
|
||||
## Data Models
|
||||
|
||||
### Database Schema (unchanged)
|
||||
|
||||
The `ivanti_todo_queue` table is reused as-is:
|
||||
|
||||
```sql
|
||||
CREATE TABLE ivanti_todo_queue (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
finding_id TEXT NOT NULL,
|
||||
finding_title TEXT,
|
||||
cves_json TEXT,
|
||||
ip_address TEXT,
|
||||
vendor TEXT NOT NULL,
|
||||
workflow_type TEXT NOT NULL CHECK(workflow_type IN ('FP', 'Archer', 'CARD')),
|
||||
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'complete')),
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
```
|
||||
|
||||
Each batch-added finding creates one row, identical to single-add. The `vendor` and `workflow_type` are shared across all findings in a batch (set once in the toolbar).
|
||||
|
||||
### API Request Schema
|
||||
|
||||
```
|
||||
BatchAddRequest {
|
||||
findings: Array<{
|
||||
finding_id: string (required, non-empty, trimmed)
|
||||
finding_title: string | null (max 500 chars)
|
||||
cves: string[] | null
|
||||
ip_address: string | null (max 64 chars)
|
||||
}> (1–200 items)
|
||||
workflow_type: "FP" | "Archer" | "CARD"
|
||||
vendor: string (required for FP/Archer, ≤200 chars; empty/absent for CARD)
|
||||
}
|
||||
```
|
||||
|
||||
### Frontend State Shape
|
||||
|
||||
```
|
||||
Selection State:
|
||||
selectedIds: Set<string> — finding IDs currently selected
|
||||
lastClickedId: string | null — last checkbox clicked (for shift-range)
|
||||
batchSubmitting: boolean — true while POST /batch in flight
|
||||
batchError: string | null — error message from last failed batch
|
||||
batchWorkflowType: "FP" | "Archer" | "CARD"
|
||||
batchVendor: string
|
||||
```
|
||||
|
||||
|
||||
## 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: Selection pruning preserves only visible findings
|
||||
|
||||
*For any* set of selected finding IDs and any set of currently visible (filtered) finding IDs, pruning the selection after a filter change should produce exactly the intersection of the two sets — every ID in the result is both selected and visible, and no visible selected ID is lost.
|
||||
|
||||
**Validates: Requirements 1.4**
|
||||
|
||||
### Property 2: Select-all produces the complete visible non-queued set
|
||||
|
||||
*For any* list of visible findings and any set of queued finding IDs, the select-all operation should produce a set containing exactly the IDs of visible findings that are not in the queued set — no queued findings included, no non-queued visible findings omitted.
|
||||
|
||||
**Validates: Requirements 1.6**
|
||||
|
||||
### Property 3: Submit button enabled state matches validation rule
|
||||
|
||||
*For any* workflow type (FP, Archer, CARD) and any vendor string, the "Add to Queue" button should be enabled if and only if the workflow type is CARD, or the vendor string trimmed is non-empty. No other combination should enable the button.
|
||||
|
||||
**Validates: Requirements 2.7**
|
||||
|
||||
### Property 4: Batch size validation accepts only 1–200 items
|
||||
|
||||
*For any* integer N representing the number of findings in a batch request, the endpoint should accept the request (assuming all other fields are valid) if and only if 1 ≤ N ≤ 200. Arrays of size 0 or greater than 200 should be rejected with a 400 response.
|
||||
|
||||
**Validates: Requirements 3.2**
|
||||
|
||||
### Property 5: Vendor validation is conditional on workflow type
|
||||
|
||||
*For any* workflow type and any vendor string, the batch endpoint should require a non-empty vendor of 200 characters or fewer when workflow_type is FP or Archer, and should accept any vendor value (including empty or absent) when workflow_type is CARD.
|
||||
|
||||
**Validates: Requirements 3.5, 3.6**
|
||||
|
||||
### Property 6: One invalid finding rejects the entire batch
|
||||
|
||||
*For any* valid batch of findings, if exactly one finding is replaced with an invalid finding (empty finding_id, missing finding_id, or non-string finding_id) at any position in the array, the entire batch should be rejected with a 400 response and zero rows should be inserted.
|
||||
|
||||
**Validates: Requirements 3.3, 3.8**
|
||||
|
||||
### Property 7: Successful batch response matches request
|
||||
|
||||
*For any* valid batch request of N findings, the 201 response should contain exactly N items, each with a unique numeric `id`, and the set of `finding_id` values in the response should equal the set of `finding_id` values in the request.
|
||||
|
||||
**Validates: Requirements 3.9**
|
||||
|
||||
### Property 8: Shift-click range select covers exactly the between range
|
||||
|
||||
*For any* sorted list of visible findings, any last-clicked index, and any current-click index, the shift-click range select should produce a set containing exactly the non-queued findings between those two indices (inclusive), regardless of which index is larger.
|
||||
|
||||
**Validates: Requirements 6.1**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Backend Errors
|
||||
|
||||
| Scenario | Response | Behavior |
|
||||
|----------|----------|----------|
|
||||
| Empty findings array or > 200 items | 400 | `{ error: "findings array must contain 1-200 items." }` |
|
||||
| Any finding missing/empty finding_id | 400 | `{ error: "Each finding must have a non-empty finding_id string." }` |
|
||||
| Invalid workflow_type | 400 | `{ error: "workflow_type must be FP, Archer, or CARD." }` |
|
||||
| Missing vendor for FP/Archer | 400 | `{ error: "vendor is required for FP and Archer workflows." }` |
|
||||
| Vendor exceeds 200 chars | 400 | `{ error: "vendor must be under 200 chars." }` |
|
||||
| Not authenticated | 401 | Standard auth middleware response |
|
||||
| Insufficient permissions (Read_Only) | 403 | Standard group middleware response |
|
||||
| SQLite transaction failure | 500 | Transaction rolled back, `{ error: "Internal server error." }` |
|
||||
|
||||
### Frontend Errors
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| Batch POST returns 4xx/5xx | Display error message in Selection Toolbar, keep selection intact |
|
||||
| Network failure during batch POST | Display "Network error — please try again" in toolbar, keep selection |
|
||||
| Batch POST timeout | Same as network failure handling |
|
||||
|
||||
### Edge Cases
|
||||
|
||||
- **Duplicate finding_ids in batch**: Allowed — the same finding could appear on multiple hosts. The backend does not enforce uniqueness on finding_id within a batch.
|
||||
- **Finding already in queue**: The frontend prevents selecting already-queued findings (checkbox is disabled), so duplicates should not reach the API. No server-side duplicate check is added to keep the endpoint simple.
|
||||
- **Concurrent batch submissions**: The SQLite transaction serializes writes. If two users submit overlapping batches, both succeed independently (each user has their own queue scoped by user_id).
|
||||
- **Selection of 0 findings**: The "Add to Queue" button is only rendered when selectedIds.size > 0, so this state cannot be reached through the UI. The backend still validates for it.
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
|
||||
Focus on specific examples and edge cases:
|
||||
|
||||
- **Backend validation**: Test each validation rule with concrete valid/invalid inputs (empty array, 201 items, missing finding_id, invalid workflow_type, vendor edge cases)
|
||||
- **Transaction rollback**: Mock a database error mid-insert, verify no rows are committed
|
||||
- **Frontend checkbox dual-mode**: Test that clicking with empty selection opens popover, clicking with existing selection toggles selection
|
||||
- **Toolbar visibility**: Test toolbar appears/disappears based on selection state
|
||||
- **Clear selection**: Test that clear button empties selection
|
||||
- **Escape key**: Test that Escape clears selection
|
||||
- **Select-all toggle**: Test select-all and deselect-all behavior
|
||||
- **Queue panel update**: Test that successful batch updates queueItems state
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Using [fast-check](https://github.com/dubzzz/fast-check) for JavaScript property-based testing.
|
||||
|
||||
Each property test runs a minimum of 100 iterations with randomly generated inputs. Tests are tagged with their corresponding design property.
|
||||
|
||||
| Property | What's Generated | What's Verified |
|
||||
|----------|-----------------|-----------------|
|
||||
| Property 1: Selection pruning | Random sets of selected IDs and filtered IDs | Result = intersection of both sets |
|
||||
| Property 2: Select-all | Random finding lists and queued ID sets | Result = visible IDs minus queued IDs |
|
||||
| Property 3: Submit enabled | Random workflow types and vendor strings | Enabled iff CARD or non-empty vendor |
|
||||
| Property 4: Batch size | Random integers 0–300 | Accepted iff 1 ≤ N ≤ 200 |
|
||||
| Property 5: Vendor validation | Random workflow types and vendor strings (0–300 chars) | Conditional acceptance rule |
|
||||
| Property 6: Invalid finding rejection | Valid batches with one injected invalid item | Entire batch rejected, 0 rows inserted |
|
||||
| Property 7: Response shape | Valid batches of 1–50 findings | Response count matches, IDs match |
|
||||
| Property 8: Range select | Random sorted lists and two index positions | Correct range of non-queued findings |
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- End-to-end batch submission: POST valid batch, verify rows in database, verify response shape
|
||||
- Auth enforcement: Verify 401 for unauthenticated, 403 for Read_Only users
|
||||
- Transaction atomicity: Verify rollback on database error
|
||||
- Frontend → Backend: Mock API, verify correct request payload from toolbar submit
|
||||
97
.kiro/specs/batch-finding-disposition/requirements.md
Normal file
97
.kiro/specs/batch-finding-disposition/requirements.md
Normal file
@@ -0,0 +1,97 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The Batch Finding Disposition feature adds multi-select capability to the Vulnerability Triage page's findings table, allowing engineers to select multiple findings at once and add them all to the Ivanti Queue with a shared workflow type and vendor in a single operation. Currently, each finding must be individually clicked, configured via a popover, and submitted — a repetitive process that slows down triage when working through many findings. This feature replaces that one-at-a-time flow with a batch selection toolbar and a bulk-add API endpoint.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Findings_Table**: The sortable, filterable table of Ivanti host findings rendered in the VulnerabilityTriagePage component (`ReportingPage.js`), where each row represents one finding.
|
||||
- **Selection_Toolbar**: A floating toolbar that appears above the Findings_Table when one or more findings are selected via their row checkboxes, displaying the count of selected findings and batch action controls.
|
||||
- **Batch_Add_Panel**: The inline panel within the Selection_Toolbar that provides workflow type selection (FP, Archer, CARD), an optional vendor input, and a submit button for adding all selected findings to the queue in one operation.
|
||||
- **Todo_Queue_API**: The backend Express router at `/api/ivanti/todo-queue` that manages CRUD operations on the `ivanti_todo_queue` table.
|
||||
- **Queue_Panel**: The existing right-side slide-out panel (`QueuePanel` component) that displays the user's current queue items grouped by vendor.
|
||||
- **Workflow_Type**: One of three disposition categories: FP (false positive), Archer (risk acceptance), or CARD (remediation card). Each finding added to the queue is assigned exactly one Workflow_Type.
|
||||
- **Finding**: A single Ivanti host vulnerability record containing an ID, title, CVEs, IP address, severity, and other metadata.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Multi-Select Findings via Row Checkboxes
|
||||
|
||||
**User Story:** As an engineer, I want to select multiple findings using checkboxes so that I can batch-process them instead of handling each one individually.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Findings_Table SHALL render a checkbox in the first column of each finding row that is not already in the queue.
|
||||
2. WHEN a user clicks a finding row's checkbox, THE Findings_Table SHALL toggle that Finding's selected state without opening the AddToQueuePopover.
|
||||
3. WHEN one or more findings are selected, THE Findings_Table SHALL visually distinguish selected rows from unselected rows using a highlighted background.
|
||||
4. THE Findings_Table SHALL maintain the selected findings set across sort and filter changes, removing only findings that are no longer visible after filtering.
|
||||
5. WHEN a finding is already in the queue, THE Findings_Table SHALL display that row's checkbox as checked and disabled, preventing re-selection.
|
||||
6. WHILE findings are selected, THE Findings_Table SHALL display a "Select All (visible)" control in the checkbox column header that selects all visible, non-queued findings.
|
||||
7. WHEN the "Select All" control is clicked while all visible non-queued findings are already selected, THE Findings_Table SHALL deselect all findings.
|
||||
|
||||
### Requirement 2: Selection Toolbar with Batch Actions
|
||||
|
||||
**User Story:** As an engineer, I want a toolbar that appears when I have findings selected so that I can see how many are selected and take batch actions on them.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN one or more findings are selected, THE Selection_Toolbar SHALL appear as a sticky bar above the Findings_Table header row.
|
||||
2. THE Selection_Toolbar SHALL display the count of currently selected findings.
|
||||
3. THE Selection_Toolbar SHALL provide a "Clear Selection" button that deselects all findings and hides the Selection_Toolbar.
|
||||
4. THE Selection_Toolbar SHALL provide workflow type toggle buttons for FP, Archer, and CARD, matching the existing color scheme (FP: amber, Archer: blue, CARD: green).
|
||||
5. WHEN the selected Workflow_Type is FP or Archer, THE Selection_Toolbar SHALL display a vendor text input field.
|
||||
6. WHEN the selected Workflow_Type is CARD, THE Selection_Toolbar SHALL hide the vendor input field and display a "No vendor required" indicator.
|
||||
7. THE Selection_Toolbar SHALL provide an "Add to Queue" submit button that is enabled only when a Workflow_Type is selected and vendor is provided (for FP/Archer) or Workflow_Type is CARD.
|
||||
8. THE Selection_Toolbar SHALL follow the existing dark theme design system (monospace fonts, dark gradient backgrounds, accent-colored borders).
|
||||
|
||||
### Requirement 3: Bulk Add to Queue API Endpoint
|
||||
|
||||
**User Story:** As an engineer, I want the backend to accept multiple findings in a single request so that batch additions are processed efficiently.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Todo_Queue_API SHALL expose a `POST /api/ivanti/todo-queue/batch` endpoint that accepts an array of finding objects with a shared workflow_type and vendor.
|
||||
2. THE Todo_Queue_API SHALL validate that the findings array contains between 1 and 200 items.
|
||||
3. THE Todo_Queue_API SHALL validate that each finding object contains a non-empty finding_id string.
|
||||
4. THE Todo_Queue_API SHALL validate that workflow_type is one of FP, Archer, or CARD.
|
||||
5. WHEN workflow_type is FP or Archer, THE Todo_Queue_API SHALL validate that vendor is a non-empty string of 200 characters or fewer.
|
||||
6. WHEN workflow_type is CARD, THE Todo_Queue_API SHALL accept an empty or absent vendor field.
|
||||
7. THE Todo_Queue_API SHALL insert all valid findings into the `ivanti_todo_queue` table within a single database transaction.
|
||||
8. IF any finding in the batch fails validation, THEN THE Todo_Queue_API SHALL reject the entire batch and return a 400 response with a descriptive error message.
|
||||
9. THE Todo_Queue_API SHALL return a 201 response containing the array of newly created queue items with their assigned IDs.
|
||||
10. THE Todo_Queue_API SHALL require authentication and the Admin or Standard_User group.
|
||||
11. IF a database error occurs during the transaction, THEN THE Todo_Queue_API SHALL roll back all inserts and return a 500 response.
|
||||
|
||||
### Requirement 4: Frontend Batch Submission Flow
|
||||
|
||||
**User Story:** As an engineer, I want clicking "Add to Queue" on the toolbar to submit all selected findings at once so that I save time during triage.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the user clicks "Add to Queue" on the Selection_Toolbar, THE Findings_Table SHALL send a single POST request to `POST /api/ivanti/todo-queue/batch` containing all selected findings with the chosen workflow_type and vendor.
|
||||
2. WHILE the batch request is in progress, THE Selection_Toolbar SHALL disable the "Add to Queue" button and display a loading indicator.
|
||||
3. WHEN the batch request succeeds, THE Findings_Table SHALL add all returned queue items to the local queue state, clear the selection, and hide the Selection_Toolbar.
|
||||
4. WHEN the batch request succeeds, THE Findings_Table SHALL update each newly queued finding's row checkbox to show the checked-and-disabled (already queued) state.
|
||||
5. IF the batch request fails, THEN THE Selection_Toolbar SHALL display the error message returned by the API and keep the current selection intact.
|
||||
6. WHEN the batch request succeeds and the Queue_Panel is open, THE Queue_Panel SHALL reflect the newly added items immediately without requiring a manual refresh.
|
||||
|
||||
### Requirement 5: Preserve Single-Select Popover Flow
|
||||
|
||||
**User Story:** As an engineer, I want to still be able to add a single finding to the queue quickly without going through the batch flow, so that simple one-off additions remain fast.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN no findings are currently selected and a user clicks a finding row's checkbox, THE Findings_Table SHALL open the existing AddToQueuePopover for that single finding.
|
||||
2. WHEN one or more findings are already selected and a user clicks another finding row's checkbox, THE Findings_Table SHALL add that finding to the selection set instead of opening the AddToQueuePopover.
|
||||
3. THE AddToQueuePopover SHALL continue to use the existing single-item `POST /api/ivanti/todo-queue` endpoint for individual additions.
|
||||
|
||||
### Requirement 6: Keyboard Accessibility for Multi-Select
|
||||
|
||||
**User Story:** As an engineer, I want to use keyboard shortcuts to speed up multi-select so that I can triage even faster.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a user holds Shift and clicks a finding row's checkbox, THE Findings_Table SHALL select all visible findings between the last clicked checkbox and the current checkbox (range select).
|
||||
2. THE Selection_Toolbar SHALL be navigable via keyboard Tab order, with all interactive elements (workflow buttons, vendor input, submit button) reachable by Tab key.
|
||||
3. WHEN the Escape key is pressed while the Selection_Toolbar is visible, THE Findings_Table SHALL clear the selection and hide the Selection_Toolbar.
|
||||
116
.kiro/specs/batch-finding-disposition/tasks.md
Normal file
116
.kiro/specs/batch-finding-disposition/tasks.md
Normal file
@@ -0,0 +1,116 @@
|
||||
# Implementation Plan: Batch Finding Disposition
|
||||
|
||||
## Overview
|
||||
|
||||
Add multi-select capability to the Vulnerability Triage findings table with a batch-add-to-queue API endpoint. The backend gets a new `POST /api/ivanti/todo-queue/batch` route in `ivantiTodoQueue.js`. The frontend gets selection state, checkbox dual-mode logic, a SelectionToolbar component, shift-click range select, select-all, and Escape-to-clear — all within `ReportingPage.js`.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Add `POST /api/ivanti/todo-queue/batch` endpoint
|
||||
- [x] 1.1 Add batch route handler to `backend/routes/ivantiTodoQueue.js`
|
||||
- Add `POST /batch` route inside `createIvantiTodoQueueRouter`, before the `POST /` route
|
||||
- Apply `requireAuth(db)` and `requireGroup('Admin', 'Standard_User')` middleware
|
||||
- Validate request body: `findings` array (1–200 items), each with non-empty `finding_id` string
|
||||
- Validate `workflow_type` is one of `FP`, `Archer`, `CARD`
|
||||
- Validate `vendor`: required non-empty string ≤200 chars for FP/Archer; ignored for CARD
|
||||
- If any validation fails, return 400 with descriptive error message and reject entire batch
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.8, 3.10_
|
||||
- [x] 1.2 Implement transactional batch insert with SQLite
|
||||
- Use `db.serialize()` with `BEGIN TRANSACTION` / `COMMIT` to insert all findings atomically
|
||||
- For each finding: insert row into `ivanti_todo_queue` with `user_id`, `finding_id`, `finding_title`, `cves_json`, `ip_address`, `vendor`, `workflow_type`
|
||||
- On success: fetch all inserted rows, parse `cves_json` back to arrays, return 201 with `{ items: [...] }`
|
||||
- On any DB error: `ROLLBACK` the transaction and return 500
|
||||
- _Requirements: 3.7, 3.8, 3.9, 3.11_
|
||||
- [x] 1.3 Add audit logging for batch additions
|
||||
- After successful commit, call `logAudit(db, { ... })` with action `'batch_add_to_queue'`, entityType `'ivanti_todo_queue'`, and details including the count and workflow_type
|
||||
- Import `logAudit` from `../helpers/auditLog`
|
||||
- _Requirements: 3.7_
|
||||
|
||||
- [x] 2. Checkpoint — Verify backend endpoint
|
||||
- Ensure the batch endpoint is syntactically correct and the route file has no errors. Ask the user if questions arise.
|
||||
|
||||
- [x] 3. Add multi-select state and checkbox dual-mode logic to `ReportingPage.js`
|
||||
- [x] 3.1 Add selection state variables to `VulnerabilityTriagePage`
|
||||
- Add `selectedIds` (`new Set()`), `lastClickedId` (null), `batchSubmitting` (false), `batchError` (null), `batchWorkflowType` ('FP'), `batchVendor` ('') as new `useState` hooks
|
||||
- _Requirements: 1.1, 2.1_
|
||||
- [x] 3.2 Implement checkbox dual-mode click handler
|
||||
- Replace the existing `<td>` onClick in the checkbox cell with new logic:
|
||||
- If finding is already queued → no-op (existing behavior)
|
||||
- If `selectedIds.size === 0` AND not shift-click → open `AddToQueuePopover` (preserves single-select flow)
|
||||
- If shift-click AND `lastClickedId` exists → range-select all visible non-queued findings between `lastClickedId` and current finding in the `sorted` array
|
||||
- Otherwise → toggle finding.id in `selectedIds`
|
||||
- Always update `lastClickedId` when toggling selection
|
||||
- _Requirements: 1.1, 1.2, 5.1, 5.2, 6.1_
|
||||
- [x] 3.3 Add visual highlighting for selected rows
|
||||
- When a finding's ID is in `selectedIds`, apply a highlighted background (e.g. `rgba(14,165,233,0.12)`) to the row
|
||||
- Override the existing alternating row background and hover for selected rows
|
||||
- _Requirements: 1.3_
|
||||
- [x] 3.4 Disable checkbox for already-queued findings
|
||||
- Keep existing behavior: queued findings show checked + disabled checkbox, preventing re-selection
|
||||
- Ensure queued findings are excluded from shift-click range select and select-all
|
||||
- _Requirements: 1.5_
|
||||
|
||||
- [x] 4. Implement Select All / Deselect All in column header
|
||||
- Modify the checkbox column `<th>` to render a clickable "Select All" checkbox when `selectedIds.size > 0` or when the user interacts with it
|
||||
- Click behavior: if not all visible non-queued findings are selected → select all visible non-queued; if all are selected → deselect all
|
||||
- _Requirements: 1.6, 1.7_
|
||||
|
||||
- [x] 5. Add selection pruning on filter changes
|
||||
- Add a `useEffect` that watches `filtered` (the filtered findings array) and prunes `selectedIds` to only include IDs still present in the filtered set
|
||||
- This ensures selection stays consistent when `columnFilters`, `actionFilter`, or `excFilter` change
|
||||
- _Requirements: 1.4_
|
||||
|
||||
- [x] 6. Implement SelectionToolbar component
|
||||
- [x] 6.1 Create the `SelectionToolbar` inline component in `ReportingPage.js`
|
||||
- Render between the panel header controls and the `<table>` element, only when `selectedIds.size > 0`
|
||||
- Use `position: sticky` with appropriate `top` value to stay visible during scroll
|
||||
- Follow the dark theme design system: monospace fonts, dark gradient background, accent-colored borders
|
||||
- _Requirements: 2.1, 2.8_
|
||||
- [x] 6.2 Add toolbar controls: count badge, Clear Selection, workflow toggles, vendor input, submit button
|
||||
- Display selected count badge (e.g. "12 selected")
|
||||
- "Clear Selection" button that empties `selectedIds` and hides toolbar
|
||||
- Workflow type toggle buttons (FP / Archer / CARD) using existing color scheme: FP = amber (`#F59E0B`), Archer = blue (`#0EA5E9`), CARD = green (`#10B981`)
|
||||
- Vendor text input (hidden when CARD is selected, show "No vendor required" indicator for CARD)
|
||||
- "Add to Queue" submit button — enabled only when workflow_type is CARD, or vendor is non-empty
|
||||
- _Requirements: 2.2, 2.3, 2.4, 2.5, 2.6, 2.7_
|
||||
|
||||
- [x] 7. Implement batch submission flow
|
||||
- [x] 7.1 Add `submitBatch` async function to `VulnerabilityTriagePage`
|
||||
- Build request payload from `selectedIds` (map each ID to its finding object from `sorted`/`filtered` for `finding_id`, `finding_title`, `cves`, `ip_address`), plus `batchWorkflowType` and `batchVendor`
|
||||
- POST to `${API_BASE}/ivanti/todo-queue/batch` with `credentials: 'include'`
|
||||
- Set `batchSubmitting = true` before request, `false` after
|
||||
- _Requirements: 4.1, 4.2_
|
||||
- [x] 7.2 Handle batch success response
|
||||
- On 201: merge returned items into `queueItems` state (sorted by vendor then id, matching existing pattern)
|
||||
- Clear `selectedIds`, reset `batchWorkflowType` to 'FP', reset `batchVendor` to '', clear `batchError`
|
||||
- The newly queued findings will automatically show as checked+disabled via the existing `isQueued()` helper
|
||||
- _Requirements: 4.3, 4.4, 4.6_
|
||||
- [x] 7.3 Handle batch error response
|
||||
- On 4xx/5xx: parse error message from response JSON, set `batchError` to display in toolbar
|
||||
- On network failure: set `batchError` to "Network error — please try again"
|
||||
- Keep selection intact on error so user can retry
|
||||
- _Requirements: 4.5_
|
||||
|
||||
- [x] 8. Add Escape key handler to clear selection
|
||||
- Add a `useEffect` with a `keydown` listener for Escape that clears `selectedIds` when the SelectionToolbar is visible (i.e. `selectedIds.size > 0`)
|
||||
- Ensure it doesn't conflict with the existing Escape handler on `AddToQueuePopover`
|
||||
- _Requirements: 6.3_
|
||||
|
||||
- [x] 9. Ensure keyboard Tab accessibility for SelectionToolbar
|
||||
- Verify all interactive elements in the toolbar (workflow buttons, vendor input, submit button, clear button) are focusable via Tab key
|
||||
- Use native `<button>` and `<input>` elements (which are inherently tabbable) rather than `<div>` with onClick
|
||||
- _Requirements: 6.2_
|
||||
|
||||
- [x] 10. Final checkpoint — Full integration verification
|
||||
- Ensure all files have no syntax errors or diagnostic issues
|
||||
- Verify the checkbox dual-mode logic: no selection → popover, existing selection → toggle
|
||||
- Verify the SelectionToolbar renders/hides correctly based on selection state
|
||||
- Verify batch submit wires through to the backend endpoint and updates queue state
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- No new database migration needed — batch insert reuses the existing `ivanti_todo_queue` schema
|
||||
- The batch endpoint must be registered before `POST /` in the router to avoid Express route conflicts
|
||||
- All testing is done on the dev server after push — no local test tasks included
|
||||
- Each task references specific acceptance criteria from the requirements document for traceability
|
||||
1
.kiro/specs/card-api-integration/.config.kiro
Normal file
1
.kiro/specs/card-api-integration/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "0334e0b6-7ae7-4284-95a0-caed55c59af1", "workflowType": "requirements-first", "specType": "feature"}
|
||||
163
.kiro/specs/card-api-integration/requirements.md
Normal file
163
.kiro/specs/card-api-integration/requirements.md
Normal 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.
|
||||
1
.kiro/specs/compliance-metric-grouping/.config.kiro
Normal file
1
.kiro/specs/compliance-metric-grouping/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "9ecf72f0-b470-4877-b244-899e583007f7", "workflowType": "requirements-first", "specType": "feature"}
|
||||
516
.kiro/specs/compliance-metric-grouping/design.md
Normal file
516
.kiro/specs/compliance-metric-grouping/design.md
Normal file
@@ -0,0 +1,516 @@
|
||||
# Design Document: Compliance Metric Grouping
|
||||
|
||||
## Overview
|
||||
|
||||
The Compliance Metric Grouping feature consolidates the AEO Compliance page's metric health cards from one-per-summary-entry to one-per-metric-family. A metric family is the set of summary entries that share the same base `metric_id` (e.g., `5.2.5`). The same base ID can appear multiple times in the summary data because the backend parser produces one entry per team/variant row in the xlsx Summary sheet.
|
||||
|
||||
The feature adds three new capabilities on top of the grouping:
|
||||
|
||||
1. **Variant pills** inside each grouped card showing per-variant compliance percentages and status indicators
|
||||
2. **Hover tooltip** (300ms delay) displaying metric title, business justification, and data sources from a static definitions file
|
||||
3. **Info panel** opened via an info icon on each card, showing the full metric definition (scope, filters, exclusions, notes)
|
||||
|
||||
A static JSON file (`metricDefinitions.json`) ships with the frontend containing structured metric definition data for all tracked metrics. No new backend endpoints are needed.
|
||||
|
||||
### Design Decisions
|
||||
|
||||
- **Grouping is frontend-only.** The backend summary endpoint returns flat entries. The frontend groups them by `metric_id` at render time. This avoids backend changes and keeps the grouping logic testable as a pure function.
|
||||
- **`metricFilter` changes from a single string to an array.** Currently `metricFilter` is a single `metric_id` string or `null`. With grouping, clicking a card sets the filter to the array of all `metric_id` values in that family. For single-entry families this is a one-element array. The device table filter checks `metricFilter.includes(m.metric_id)` instead of `m.metric_id === metricFilter`.
|
||||
- **Worst-status drives card color.** Each grouped card computes the most severe status across its variants using a defined severity ordering. This gives engineers an at-a-glance signal when any variant is failing.
|
||||
- **Definitions file is static, not an API.** The metric definitions table has ~130 rows that change infrequently. A static JSON import avoids API round-trips and keeps the tooltip/panel responsive. The file can be regenerated from the source xlsx definitions table when metrics change.
|
||||
- **MetricInfoPanel is a new component.** The detail panel is complex enough (12+ fields, dark-themed sections) to warrant its own component file rather than inlining it in CompliancePage.js. The hover tooltip, being lightweight, stays inline.
|
||||
- **Info icon click uses `stopPropagation`.** The info icon sits inside the card button. Clicking it opens the detail panel without triggering the card's metric filter toggle.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[CompliancePage.js] -->|imports| B[metricDefinitions.json]
|
||||
A -->|renders| C[MetricHealthCard - grouped]
|
||||
A -->|renders| D[MetricInfoPanel]
|
||||
A -->|renders| E[HoverTooltip - inline]
|
||||
A -->|fetches| F[GET /api/compliance/summary?team=X]
|
||||
A -->|fetches| G[GET /api/compliance/items?team=X&status=Y]
|
||||
|
||||
F -->|returns| H[summary.entries array]
|
||||
H -->|groupByMetricFamily| I[Map of metricId → entries array]
|
||||
I -->|one card per group| C
|
||||
|
||||
C -->|click outside info icon| J[setMetricFilter - array of IDs]
|
||||
C -->|click info icon| K[setInfoMetric - opens MetricInfoPanel]
|
||||
C -->|hover 300ms| E
|
||||
|
||||
J -->|filters| G2[filteredDevices]
|
||||
B -->|lookup by metric_id| E
|
||||
B -->|lookup by metric_id| D
|
||||
```
|
||||
|
||||
### Component Hierarchy
|
||||
|
||||
```
|
||||
CompliancePage
|
||||
├── PageHeader (unchanged)
|
||||
├── TeamTabs (unchanged)
|
||||
├── MetricHealthSection
|
||||
│ ├── SectionHeader ("Metric Health — click to filter" + clear button)
|
||||
│ └── MetricHealthCard (one per metric family)
|
||||
│ ├── CardTitle (base metric_id + category)
|
||||
│ ├── VariantPill[] (one per summary entry in family)
|
||||
│ ├── WorstStatusPill (computed from all variants)
|
||||
│ ├── TargetDisplay (shared target %)
|
||||
│ ├── InfoIcon (lucide-react Info, top-right)
|
||||
│ └── HoverTooltip (inline, 300ms delay)
|
||||
├── MetricInfoPanel (slide-out/overlay, opened by info icon click)
|
||||
├── ComplianceChartsPanel (unchanged)
|
||||
├── DeviceTable (unchanged, filter logic updated)
|
||||
├── ComplianceDetailPanel (unchanged)
|
||||
├── ComplianceUploadModal (unchanged)
|
||||
└── RollbackModal (unchanged)
|
||||
```
|
||||
|
||||
### Data Flow
|
||||
|
||||
1. `CompliancePage` fetches summary entries from `/api/compliance/summary?team=X` on mount and team change.
|
||||
2. The `groupByMetricFamily(entries)` helper groups the flat entries array into a `Map<string, SummaryEntry[]>` keyed by base `metric_id`.
|
||||
3. One `MetricHealthCard` renders per map entry. Each card receives the full array of entries for that family.
|
||||
4. The card computes `worstStatus` from the entries' status fields and uses it for border/pill coloring.
|
||||
5. On card click (outside info icon), `metricFilter` is set to the array of `metric_id` values in that family (or cleared if already active).
|
||||
6. The device table filter changes from `d.failing_metrics.some(m => m.metric_id === metricFilter)` to `d.failing_metrics.some(m => metricFilter.includes(m.metric_id))`.
|
||||
7. On hover (300ms), a tooltip renders using data from the `metricDefinitions.json` lookup map, falling back to the summary entry description.
|
||||
8. On info icon click, `infoMetric` state is set, opening `MetricInfoPanel` with the full definition.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### groupByMetricFamily (pure helper function)
|
||||
|
||||
```javascript
|
||||
// In CompliancePage.js — replaces the current teamMetrics() helper
|
||||
// Input: entries (array of SummaryEntry from the summary endpoint), team (string)
|
||||
// Output: array of { metricId, entries, category, target, worstStatus }
|
||||
|
||||
function groupByMetricFamily(allEntries, team) {
|
||||
const teamEntries = allEntries.filter(e => e.team === team);
|
||||
const familyMap = {};
|
||||
|
||||
for (const entry of teamEntries) {
|
||||
const baseId = entry.metric_id; // already the base ID from the parser
|
||||
if (!familyMap[baseId]) {
|
||||
familyMap[baseId] = [];
|
||||
}
|
||||
familyMap[baseId].push(entry);
|
||||
}
|
||||
|
||||
return Object.entries(familyMap).map(([metricId, entries]) => ({
|
||||
metricId,
|
||||
entries,
|
||||
category: entries[0].category,
|
||||
target: entries[0].target,
|
||||
worstStatus: computeWorstStatus(entries.map(e => e.status)),
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
### computeWorstStatus (pure helper function)
|
||||
|
||||
```javascript
|
||||
// Input: array of status strings
|
||||
// Output: the most severe status string
|
||||
// Severity order: "Below 15% of Target" > "Within 15% of Target" > "Meets/Exceeds Target"
|
||||
|
||||
const STATUS_SEVERITY = {
|
||||
'Below 15% of Target': 0,
|
||||
'Within 15% of Target': 1,
|
||||
'Meets/Exceeds Target': 2,
|
||||
};
|
||||
|
||||
function computeWorstStatus(statuses) {
|
||||
let worst = 'Meets/Exceeds Target';
|
||||
let worstSev = 2;
|
||||
for (const s of statuses) {
|
||||
const sev = STATUS_SEVERITY[s] ?? 0;
|
||||
if (sev < worstSev) {
|
||||
worstSev = sev;
|
||||
worst = s;
|
||||
}
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
```
|
||||
|
||||
### MetricHealthCard (redesigned)
|
||||
|
||||
```javascript
|
||||
// Props:
|
||||
// family: { metricId, entries, category, target, worstStatus }
|
||||
// active: boolean (is this family's filter currently active)
|
||||
// onClick: () => void (toggle metric filter)
|
||||
// onInfoClick: (metricId) => void (open detail panel)
|
||||
// definitionLookup: Map<string, MetricDefinition> (for tooltip)
|
||||
//
|
||||
// Renders:
|
||||
// - Base metric ID as title
|
||||
// - Category label
|
||||
// - One VariantPill per entry in family.entries
|
||||
// - Shared target percentage
|
||||
// - Worst-status pill with border color
|
||||
// - Info icon (top-right, stopPropagation on click)
|
||||
// - HoverTooltip (300ms delay, positioned near card)
|
||||
```
|
||||
|
||||
### VariantPill (new inline sub-component)
|
||||
|
||||
```javascript
|
||||
// Props:
|
||||
// entry: SummaryEntry (single variant)
|
||||
//
|
||||
// Renders:
|
||||
// - Label: entry.team or entry.description (distinguishing text)
|
||||
// - Compliance percentage in monospace
|
||||
// - Background tint from entry's status color at ~12% opacity
|
||||
// - Glow dot if status !== "Meets/Exceeds Target"
|
||||
//
|
||||
// Layout: inline-flex, wraps via parent flexWrap
|
||||
```
|
||||
|
||||
### HoverTooltip (inline in CompliancePage.js)
|
||||
|
||||
```javascript
|
||||
// State managed in CompliancePage:
|
||||
// hoveredMetric: string | null
|
||||
// hoverTimeout: ref (setTimeout ID)
|
||||
// tooltipPosition: { top, left } (computed from card bounding rect)
|
||||
//
|
||||
// On mouseEnter on MetricHealthCard:
|
||||
// Set timeout for 300ms → set hoveredMetric to family.metricId
|
||||
// On mouseLeave:
|
||||
// Clear timeout, set hoveredMetric to null
|
||||
//
|
||||
// Renders (when hoveredMetric matches):
|
||||
// - Fixed-position div near the card
|
||||
// - Metric title (from definitionLookup or entry.description)
|
||||
// - Business justification (from definitionLookup)
|
||||
// - Data sources required (from definitionLookup)
|
||||
// - Dark card background, subtle border, shadow per DESIGN_SYSTEM.md
|
||||
// - Falls back to summary entry description if no definition found
|
||||
```
|
||||
|
||||
### MetricInfoPanel (new component file)
|
||||
|
||||
```javascript
|
||||
// frontend/src/components/pages/MetricInfoPanel.js
|
||||
// Props:
|
||||
// metricId: string (base metric ID)
|
||||
// definition: MetricDefinition | null (from lookup)
|
||||
// summaryEntries: SummaryEntry[] (the family's entries, for fallback)
|
||||
// onClose: () => void
|
||||
//
|
||||
// Renders:
|
||||
// - Overlay/slide-out panel with dark theme
|
||||
// - Close button (X icon, top-right)
|
||||
// - Metric title (h3, monospace)
|
||||
// - Sections with monospace uppercase labels:
|
||||
// - Asset Types / Asset Types In Scope
|
||||
// - Application Types In Scope
|
||||
// - Environment In Scope
|
||||
// - Status In Scope
|
||||
// - Instance Types In Scope
|
||||
// - Criticality Levels In Scope
|
||||
// - Exclusions
|
||||
// - Special Conditions
|
||||
// - Data Sources Required
|
||||
// - Business Justification
|
||||
// - Notes
|
||||
// - If definition is null: "No detailed definition available" + summary description fallback
|
||||
// - Click outside or close button → onClose()
|
||||
```
|
||||
|
||||
### Integration with CompliancePage.js
|
||||
|
||||
```javascript
|
||||
// New imports:
|
||||
import { Info } from 'lucide-react';
|
||||
import MetricInfoPanel from './MetricInfoPanel';
|
||||
import metricDefinitionsRaw from '../../data/metricDefinitions.json';
|
||||
|
||||
// Build lookup map once at module level:
|
||||
const METRIC_DEFINITIONS = {};
|
||||
for (const def of metricDefinitionsRaw) {
|
||||
METRIC_DEFINITIONS[def.metric_id] = def;
|
||||
}
|
||||
|
||||
// State changes in CompliancePage:
|
||||
// - metricFilter: null → null | string[] (array of metric IDs)
|
||||
// - New state: infoMetric (string | null) — which metric's info panel is open
|
||||
// - New state: hoveredMetric (string | null) — which metric is being hovered
|
||||
// - New ref: hoverTimeoutRef — for 300ms delay
|
||||
|
||||
// Filter logic change:
|
||||
// Old: .filter(d => !metricFilter || d.failing_metrics.some(m => m.metric_id === metricFilter))
|
||||
// New: .filter(d => !metricFilter || d.failing_metrics.some(m => metricFilter.includes(m.metric_id)))
|
||||
|
||||
// Card rendering change:
|
||||
// Old: metrics.map(entry => <MetricHealthCard entry={entry} ... />)
|
||||
// New: families.map(family => <MetricHealthCard family={family} ... />)
|
||||
```
|
||||
|
||||
## Data Models
|
||||
|
||||
### SummaryEntry (from backend, unchanged)
|
||||
|
||||
```javascript
|
||||
{
|
||||
metric_id: string, // e.g. "5.2.5" — base ID, no suffix
|
||||
team: string, // e.g. "STEAM", "ACCESS-ENG"
|
||||
priority: string,
|
||||
non_compliant: number,
|
||||
compliant: number,
|
||||
total: number,
|
||||
compliance_pct: number, // 0.0–1.0
|
||||
target: number, // 0.0–1.0
|
||||
status: string, // "Meets/Exceeds Target" | "Within 15% of Target" | "Below 15% of Target"
|
||||
description: string,
|
||||
category: string // from compliance_config.json metric_categories
|
||||
}
|
||||
```
|
||||
|
||||
### MetricFamily (computed client-side)
|
||||
|
||||
```javascript
|
||||
{
|
||||
metricId: string, // base metric ID (e.g. "5.2.5")
|
||||
entries: SummaryEntry[], // all summary entries for this base ID
|
||||
category: string, // from first entry
|
||||
target: number, // from first entry (shared across variants)
|
||||
worstStatus: string // computed worst status across all entries
|
||||
}
|
||||
```
|
||||
|
||||
### MetricDefinition (from metricDefinitions.json)
|
||||
|
||||
```javascript
|
||||
{
|
||||
metric_id: string, // e.g. "5.2.5"
|
||||
metric_title: string, // e.g. "MFA for Privileged Access"
|
||||
asset_types: string, // e.g. "Servers, Network Devices"
|
||||
asset_types_in_scope: string,
|
||||
application_types_in_scope: string,
|
||||
environment_in_scope: string,
|
||||
status_in_scope: string,
|
||||
instance_types_in_scope: string,
|
||||
criticality_levels_in_scope: string,
|
||||
exclusions: string, // empty string if none
|
||||
special_conditions: string, // empty string if none
|
||||
data_sources_required: string,
|
||||
business_justification: string,
|
||||
notes: string // empty string if none
|
||||
}
|
||||
```
|
||||
|
||||
### metricDefinitions.json (file structure)
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"metric_id": "1.1.1",
|
||||
"metric_title": "...",
|
||||
"asset_types": "...",
|
||||
"asset_types_in_scope": "...",
|
||||
"application_types_in_scope": "...",
|
||||
"environment_in_scope": "...",
|
||||
"status_in_scope": "...",
|
||||
"instance_types_in_scope": "...",
|
||||
"criticality_levels_in_scope": "...",
|
||||
"exclusions": "",
|
||||
"special_conditions": "",
|
||||
"data_sources_required": "...",
|
||||
"business_justification": "...",
|
||||
"notes": ""
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
All entries use the same set of keys. Optional fields with no value use empty strings, never `null` or omitted keys.
|
||||
|
||||
### Status Severity Map
|
||||
|
||||
```javascript
|
||||
const STATUS_SEVERITY = {
|
||||
'Below 15% of Target': 0, // worst
|
||||
'Within 15% of Target': 1,
|
||||
'Meets/Exceeds Target': 2, // best
|
||||
};
|
||||
```
|
||||
|
||||
### Updated metricFilter State
|
||||
|
||||
```javascript
|
||||
// Old: metricFilter: string | null
|
||||
// New: metricFilter: string[] | null
|
||||
//
|
||||
// null = no filter (show all devices)
|
||||
// string[] = show devices with failing_metrics matching any ID in the array
|
||||
```
|
||||
|
||||
## 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: Grouping invariant — no entries lost or misplaced
|
||||
|
||||
*For any* array of summary entries and any team string, grouping by metric family SHALL produce groups where (a) every entry appears in exactly one group, (b) all entries within a group share the same `metric_id`, and (c) the total number of entries across all groups equals the number of entries for that team in the input.
|
||||
|
||||
**Validates: Requirements 1.1, 1.2**
|
||||
|
||||
### Property 2: Worst-status computation follows severity ordering
|
||||
|
||||
*For any* non-empty array of status strings drawn from `{"Below 15% of Target", "Within 15% of Target", "Meets/Exceeds Target"}`, the computed worst status SHALL be the status with the lowest severity rank present in the array. If the array contains "Below 15% of Target", the result SHALL be "Below 15% of Target" regardless of other values.
|
||||
|
||||
**Validates: Requirements 1.6, 3.1**
|
||||
|
||||
### Property 3: Device filtering with metric family includes all matching devices
|
||||
|
||||
*For any* array of device objects (each with a `failing_metrics` array of `{metric_id}` objects) and *for any* non-empty array of filter metric IDs, the filtered result SHALL contain exactly those devices that have at least one `failing_metrics` entry whose `metric_id` is included in the filter array. No matching device is excluded and no non-matching device is included.
|
||||
|
||||
**Validates: Requirements 1.8, 7.1, 7.2**
|
||||
|
||||
### Property 4: Definition lookup returns correct entry or null
|
||||
|
||||
*For any* array of metric definition objects with unique `metric_id` values, building a lookup map and querying it with a `metric_id` that exists in the array SHALL return the corresponding definition object. Querying with a `metric_id` not in the array SHALL return `undefined`.
|
||||
|
||||
**Validates: Requirements 4.2, 4.6**
|
||||
|
||||
### Property 5: Detail panel renders all required definition fields
|
||||
|
||||
*For any* valid metric definition object (with all 14 fields present), the set of field keys rendered by the detail panel SHALL include: `metric_title`, `asset_types`, `asset_types_in_scope`, `application_types_in_scope`, `environment_in_scope`, `status_in_scope`, `instance_types_in_scope`, `criticality_levels_in_scope`, `exclusions`, `special_conditions`, `data_sources_required`, `business_justification`, and `notes`.
|
||||
|
||||
**Validates: Requirements 5.3**
|
||||
|
||||
### Property 6: Definitions schema validation — all entries have required fields
|
||||
|
||||
*For any* entry in the metric definitions array, the entry SHALL have all 14 required keys present, and the `metric_id` field SHALL be a non-empty string. Optional fields (`exclusions`, `special_conditions`, `notes`) SHALL be present as strings (empty string if no value), never omitted or null.
|
||||
|
||||
**Validates: Requirements 6.2, 8.3, 8.4**
|
||||
|
||||
### Property 7: Lookup map construction preserves all definitions
|
||||
|
||||
*For any* array of metric definition objects with unique `metric_id` values, building a lookup map keyed by `metric_id` SHALL produce a map with exactly as many entries as the input array, and every input definition SHALL be retrievable by its `metric_id`.
|
||||
|
||||
**Validates: Requirements 6.4**
|
||||
|
||||
### Property 8: JSON round-trip preserves metric definition data
|
||||
|
||||
*For any* valid metric definition object, `JSON.parse(JSON.stringify(definition))` SHALL produce an object deeply equal to the original.
|
||||
|
||||
**Validates: Requirements 8.1, 8.2**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Metric Definitions File
|
||||
|
||||
| Error Scenario | Handling |
|
||||
|---|---|
|
||||
| `metricDefinitions.json` fails to import (malformed JSON) | Build-time error caught by Create React App. The file is validated at development time. |
|
||||
| Metric ID not found in definitions lookup | Tooltip falls back to `entry.description` from summary data. Info panel shows "No detailed definition available" with summary description. |
|
||||
| Definition entry has empty optional fields | Rendered sections show "—" placeholder for empty strings. No error thrown. |
|
||||
|
||||
### Grouping Logic
|
||||
|
||||
| Error Scenario | Handling |
|
||||
|---|---|
|
||||
| Summary entries array is empty | `groupByMetricFamily` returns empty array. No cards rendered. Existing "No compliance data" empty state shown. |
|
||||
| Summary entry has missing or empty `metric_id` | Entry is skipped during grouping (filtered out). |
|
||||
| All entries for a team have the same `metric_id` | Single family group with multiple variant pills. Works correctly. |
|
||||
|
||||
### Hover Tooltip
|
||||
|
||||
| Error Scenario | Handling |
|
||||
|---|---|
|
||||
| User moves mouse away before 300ms | Timeout cleared, tooltip never shown. No side effects. |
|
||||
| Tooltip would render off-screen | Position clamped to viewport bounds using `getBoundingClientRect()`. |
|
||||
| Rapid hover/unhover across multiple cards | Previous timeout cleared on each `mouseLeave`. Only the currently hovered card's tooltip can appear. |
|
||||
|
||||
### Info Panel
|
||||
|
||||
| Error Scenario | Handling |
|
||||
|---|---|
|
||||
| Info icon click while tooltip is visible | Tooltip dismissed (mouseLeave fires). Panel opens. No conflict. |
|
||||
| Multiple rapid info icon clicks | `infoMetric` state is set to the latest clicked metric. Only one panel open at a time. |
|
||||
| Click outside panel while scrolled | Overlay backdrop captures click, closes panel. Scroll position preserved. |
|
||||
|
||||
### Device Table Filtering
|
||||
|
||||
| Error Scenario | Handling |
|
||||
|---|---|
|
||||
| `metricFilter` is set to an array but no devices match | Empty state message shown: "No non-compliant devices". |
|
||||
| Device has `failing_metrics` with IDs not in any family | Device only shown when no filter is active or when its metric IDs match the active filter. |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (Example-Based)
|
||||
|
||||
Unit tests cover specific rendering, interaction, and integration scenarios:
|
||||
|
||||
**Grouping and display:**
|
||||
- Groups entries with the same `metric_id` into one card
|
||||
- Single-entry families render one variant pill
|
||||
- Multi-entry families render one pill per entry
|
||||
- Card title shows base metric ID and category from first entry
|
||||
- Card shows shared target percentage
|
||||
|
||||
**Worst-status computation:**
|
||||
- All "Meets/Exceeds Target" → card shows "OK" with success color
|
||||
- Mix of statuses → card uses the worst status color
|
||||
- Single "Below 15% of Target" among passing variants → card shows danger color
|
||||
|
||||
**Variant pills:**
|
||||
- Each pill shows the entry's team label and compliance percentage
|
||||
- Pill background tint matches the entry's individual status color
|
||||
- Non-passing variants show a glow dot
|
||||
|
||||
**Hover tooltip:**
|
||||
- Tooltip appears after 300ms hover delay
|
||||
- Tooltip shows metric title, business justification, data sources from definitions
|
||||
- Tooltip disappears on mouse leave
|
||||
- Tooltip falls back to summary description when no definition exists
|
||||
- Tooltip does not interfere with card click
|
||||
|
||||
**Info panel:**
|
||||
- Info icon click opens MetricInfoPanel with correct metric definition
|
||||
- Info icon click does not trigger card's metric filter toggle (stopPropagation)
|
||||
- Panel displays all 12+ definition fields with section labels
|
||||
- Panel shows fallback message when no definition exists
|
||||
- Panel closes on outside click or close button
|
||||
|
||||
**Device table filtering:**
|
||||
- Clicking a grouped card sets filter to all metric IDs in that family
|
||||
- Filtered device table shows devices matching any ID in the family
|
||||
- Clicking the same card again clears the filter
|
||||
- Clear filter button resets to show all devices
|
||||
- Active card shows highlighted styling
|
||||
|
||||
**Definitions file:**
|
||||
- File imports without error
|
||||
- Lookup map contains all metric IDs from the file
|
||||
- All entries have the required 14 fields
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based tests use [fast-check](https://github.com/dubzzz/fast-check) to verify universal properties across generated inputs. Each test runs a minimum of 100 iterations.
|
||||
|
||||
| Property | Test Description | Tag |
|
||||
|---|---|---|
|
||||
| Property 1 | Generate random arrays of summary entries with varying metric_id values and team strings. Group them and verify: all entries accounted for, entries within each group share the same metric_id, group count equals unique metric_id count. | Feature: compliance-metric-grouping, Property 1: Grouping invariant — no entries lost or misplaced |
|
||||
| Property 2 | Generate random non-empty arrays of status strings from the valid set. Compute worst status and verify it matches the minimum severity rank in the array. | Feature: compliance-metric-grouping, Property 2: Worst-status computation follows severity ordering |
|
||||
| Property 3 | Generate random device arrays (each with random failing_metrics) and random filter ID arrays. Filter and verify the result contains exactly the devices with at least one matching metric. | Feature: compliance-metric-grouping, Property 3: Device filtering with metric family includes all matching devices |
|
||||
| Property 4 | Generate random arrays of metric definitions with unique IDs. Build lookup map, query with IDs from the array (expect hit) and IDs not in the array (expect miss). | Feature: compliance-metric-grouping, Property 4: Definition lookup returns correct entry or null |
|
||||
| Property 5 | Generate random metric definition objects with all 14 fields. Extract the rendered field keys and verify all required keys are present. | Feature: compliance-metric-grouping, Property 5: Detail panel renders all required definition fields |
|
||||
| Property 6 | Generate random arrays of metric definition objects. Verify every entry has all 14 keys present, metric_id is a non-empty string, and optional fields are strings (not null/undefined). | Feature: compliance-metric-grouping, Property 6: Definitions schema validation — all entries have required fields |
|
||||
| Property 7 | Generate random definition arrays with unique IDs. Build lookup map and verify map size equals array length, and every definition is retrievable by its metric_id. | Feature: compliance-metric-grouping, Property 7: Lookup map construction preserves all definitions |
|
||||
| Property 8 | Generate random metric definition objects with string values. Round-trip through JSON.stringify then JSON.parse and verify deep equality. | Feature: compliance-metric-grouping, Property 8: JSON round-trip preserves metric definition data |
|
||||
|
||||
### Test Configuration
|
||||
|
||||
- **Library:** fast-check (JavaScript property-based testing)
|
||||
- **Runner:** Jest (via react-scripts test)
|
||||
- **Iterations:** Minimum 100 per property test (`fc.assert(property, { numRuns: 100 })`)
|
||||
- **Tag format:** Comment at top of each property test referencing the design property
|
||||
121
.kiro/specs/compliance-metric-grouping/requirements.md
Normal file
121
.kiro/specs/compliance-metric-grouping/requirements.md
Normal file
@@ -0,0 +1,121 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The AEO Compliance page currently renders one metric health card per `metric_id` returned from the summary endpoint. Many metrics share the same base ID but differ by network variant suffix (e.g., `-Corp`, `-Cust`, `-SpecBus`) in the definitions reference table. This feature groups those variant entries into a single card per metric family, adds hover tooltips with metric descriptions for quick context, provides an info panel for full metric definitions, and ships a static JSON reference file containing the complete metric definitions data. The goal is to reduce card clutter, surface metric context to engineers unfamiliar with the metrics, and preserve the existing card-click filtering behavior.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Compliance_Page**: The `CompliancePage.js` React component that renders metric health cards, team tabs, and the device violation table
|
||||
- **Metric_Family**: A group of summary entries that share the same base metric ID (e.g., `5.2.5`), regardless of network variant suffix
|
||||
- **Network_Variant**: A suffix classification from the metric definitions table indicating which network a metric applies to — Corp, Cust, or SpecBus
|
||||
- **Variant_Pill**: A small inline badge within a grouped metric card that displays a single network variant's suffix label and its compliance percentage
|
||||
- **Metric_Health_Card**: The existing `MetricHealthCard` button component that displays a metric's compliance status, now extended to support grouped variants
|
||||
- **Worst_Status**: The most severe compliance status among all variants in a Metric_Family, used to determine the card's overall border and status color
|
||||
- **Hover_Tooltip**: A floating overlay that appears on mouse hover over a Metric_Health_Card, showing the metric title, business justification, and data sources
|
||||
- **Info_Icon**: A small `Info` icon from lucide-react placed in the corner of each Metric_Health_Card that opens the Detail_Panel on click
|
||||
- **Detail_Panel**: A slide-out or inline expandable section that displays the full metric definition including scope, filters, exclusions, and per-variant notes
|
||||
- **Metric_Definitions_File**: A static JSON file shipped with the frontend containing structured metric definition data for all tracked metrics
|
||||
- **Design_System**: The color palette, typography, component specs, and interaction patterns defined in `DESIGN_SYSTEM.md`
|
||||
- **Summary_Entry**: A single row from the backend's `/api/compliance/summary` response, containing `metric_id`, `team`, `compliance_pct`, `target`, `status`, `description`, and `category`
|
||||
- **Device_Table**: The lower section of the Compliance_Page that lists non-compliant devices, filterable by metric
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Metric Family Grouping
|
||||
|
||||
**User Story:** As an engineer, I want metrics that share the same base ID to be consolidated into a single card, so that the compliance page is less cluttered and I can see the full picture for each metric family at a glance.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Compliance_Page receives Summary_Entry data, THE Compliance_Page SHALL group entries by their base metric ID to form Metric_Family groups
|
||||
2. THE Compliance_Page SHALL render one Metric_Health_Card per Metric_Family instead of one card per Summary_Entry
|
||||
3. THE Metric_Health_Card SHALL display the base metric ID (e.g., `5.2.5`) as the card title and the category name from the first entry in the group
|
||||
4. THE Metric_Health_Card SHALL display one Variant_Pill for each Summary_Entry in the Metric_Family, showing the variant's team label and compliance percentage
|
||||
5. WHEN a Metric_Family contains only one Summary_Entry, THE Metric_Health_Card SHALL display a single Variant_Pill — the layout scales naturally without special-casing
|
||||
6. THE Metric_Health_Card SHALL determine its overall border color and status indicator using the Worst_Status among all variants in the Metric_Family
|
||||
7. THE Metric_Health_Card SHALL display the shared target percentage from the Metric_Family entries
|
||||
8. WHEN a user clicks a grouped Metric_Health_Card, THE Compliance_Page SHALL filter the Device_Table to show violations across all metric IDs belonging to that Metric_Family
|
||||
|
||||
### Requirement 2: Variant Pill Display
|
||||
|
||||
**User Story:** As an engineer, I want to see each network variant's compliance percentage inside the grouped card, so that I can quickly identify which variant is underperforming.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Variant_Pill SHALL display the variant's distinguishing label (team name or suffix) and its compliance percentage in monospace font
|
||||
2. THE Variant_Pill SHALL use a background tint derived from the variant's individual status color at low opacity, consistent with the Design_System badge pattern
|
||||
3. WHEN a variant's status is not "Meets/Exceeds Target", THE Variant_Pill SHALL display a subtle glow dot matching the variant's status color to draw attention
|
||||
4. THE Variant_Pill layout SHALL wrap to multiple rows when the Metric_Family contains more variants than fit on a single line
|
||||
|
||||
### Requirement 3: Worst-Status Card Coloring
|
||||
|
||||
**User Story:** As an engineer, I want the grouped card to immediately show me if any variant is failing, so that I do not have to inspect each variant individually to find problems.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Metric_Health_Card SHALL compute the Worst_Status by selecting the most severe status from all Summary_Entry items in the Metric_Family, using the severity order: "Below 15% of Target" (worst) > "Within 15% of Target" > "Meets/Exceeds Target" (best)
|
||||
2. THE Metric_Health_Card SHALL apply the Worst_Status color to its border, status pill text, and status dot
|
||||
3. WHEN all variants in a Metric_Family meet or exceed the target, THE Metric_Health_Card SHALL display the "OK" status indicator with the success color
|
||||
|
||||
### Requirement 4: Hover Tooltip for Quick Context
|
||||
|
||||
**User Story:** As an engineer unfamiliar with the metrics, I want to hover over a metric card and see a brief description, so that I can understand what the metric measures without disrupting my workflow.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a user hovers over a Metric_Health_Card for more than 300 milliseconds, THE Compliance_Page SHALL display a Hover_Tooltip positioned near the card
|
||||
2. THE Hover_Tooltip SHALL display the metric title, a one-liner business justification, and the data sources required, sourced from the Metric_Definitions_File
|
||||
3. THE Hover_Tooltip SHALL use the Design_System dark card background with a subtle border and shadow for readability
|
||||
4. WHEN the user moves the cursor away from the Metric_Health_Card, THE Hover_Tooltip SHALL disappear
|
||||
5. THE Hover_Tooltip SHALL NOT interfere with the card's click behavior for filtering the Device_Table
|
||||
6. IF no definition exists in the Metric_Definitions_File for a given metric, THEN THE Hover_Tooltip SHALL display the metric description from the Summary_Entry data as a fallback
|
||||
|
||||
### Requirement 5: Info Icon and Detail Panel
|
||||
|
||||
**User Story:** As an engineer, I want to click an info icon on a metric card to see the full metric definition, so that I can understand the exact scope, filters, and exclusions without leaving the compliance page.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Metric_Health_Card SHALL display an Info_Icon (lucide-react `Info`) in the top-right corner of the card
|
||||
2. WHEN a user clicks the Info_Icon, THE Compliance_Page SHALL open a Detail_Panel displaying the full metric definition from the Metric_Definitions_File
|
||||
3. THE Detail_Panel SHALL display: metric title, asset types in scope, application types in scope, environment in scope, status in scope, instance types in scope, criticality levels in scope, exclusions, special conditions, data sources required, business justification, and per-variant notes
|
||||
4. THE Detail_Panel SHALL use the Design_System dark theme with section labels in monospace uppercase and content in the standard text colors
|
||||
5. WHEN a user clicks the Info_Icon, THE click event SHALL NOT propagate to the Metric_Health_Card's onClick handler that filters the Device_Table
|
||||
6. WHEN a user clicks outside the Detail_Panel or clicks a close button, THE Detail_Panel SHALL close
|
||||
7. IF no definition exists in the Metric_Definitions_File for a given metric, THEN THE Detail_Panel SHALL display a "No detailed definition available" message with the Summary_Entry description as fallback content
|
||||
|
||||
### Requirement 6: Metric Definitions Data File
|
||||
|
||||
**User Story:** As a developer, I want metric definitions stored as a static JSON file in the frontend, so that the tooltip and detail panel can render metric context without additional API calls.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Metric_Definitions_File SHALL be a JSON file located in the frontend source directory (e.g., `frontend/src/data/metricDefinitions.json`)
|
||||
2. THE Metric_Definitions_File SHALL contain an entry for each metric ID with the following fields: metric_id, metric_title, asset_types, asset_types_in_scope, application_types_in_scope, environment_in_scope, status_in_scope, instance_types_in_scope, criticality_levels_in_scope, exclusions, special_conditions, data_sources_required, business_justification, and notes
|
||||
3. THE Metric_Definitions_File SHALL be importable as a standard JavaScript module using a static import statement
|
||||
4. WHEN the Metric_Definitions_File is loaded, THE Compliance_Page SHALL build a lookup map keyed by metric_id for efficient access
|
||||
5. THE Metric_Definitions_File SHALL use a flat array structure where each entry represents one metric row from the definitions table
|
||||
|
||||
### Requirement 7: Preserved Card-Click Filtering Behavior
|
||||
|
||||
**User Story:** As an engineer, I want clicking a grouped metric card to still filter the device table, so that the existing workflow for investigating violations is not disrupted.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a user clicks a grouped Metric_Health_Card (outside the Info_Icon), THE Compliance_Page SHALL set the metric filter to include all metric IDs in that Metric_Family
|
||||
2. WHEN a metric filter is active for a Metric_Family, THE Device_Table SHALL display devices that have violations for any metric ID within that family
|
||||
3. WHEN a user clicks the same grouped Metric_Health_Card again, THE Compliance_Page SHALL clear the metric filter
|
||||
4. THE "clear filter" button in the metric health section header SHALL continue to reset the filter to show all devices
|
||||
5. THE Metric_Health_Card SHALL visually indicate the active/selected state using the existing highlight pattern (tinted background with the status color)
|
||||
|
||||
### Requirement 8: Metric Definitions File Structure and Round-Trip Integrity
|
||||
|
||||
**User Story:** As a developer, I want the metric definitions JSON to be parseable and printable without data loss, so that the file can be maintained and validated reliably.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Metric_Definitions_File SHALL be valid JSON that parses without error using `JSON.parse()`
|
||||
2. FOR ALL entries in the Metric_Definitions_File, parsing the JSON then stringifying it then parsing it again SHALL produce an equivalent object (round-trip property)
|
||||
3. THE Metric_Definitions_File SHALL contain a `metric_id` field in every entry that is a non-empty string
|
||||
4. IF an optional field (exclusions, special_conditions, notes) has no value for a metric, THEN THE Metric_Definitions_File SHALL represent it as an empty string rather than omitting the key
|
||||
178
.kiro/specs/compliance-metric-grouping/tasks.md
Normal file
178
.kiro/specs/compliance-metric-grouping/tasks.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# Implementation Plan: Compliance Metric Grouping
|
||||
|
||||
## Overview
|
||||
|
||||
Consolidate the AEO Compliance page's metric health cards from one-per-summary-entry to one-per-metric-family. Add variant pills inside each grouped card, a hover tooltip with metric context (300ms delay), an info panel for full metric definitions, and a static `metricDefinitions.json` data file. All work is frontend-only — no backend changes needed. The `metricFilter` state changes from `string|null` to `string[]|null` to support filtering by all metric IDs in a family.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Create metric definitions data file and install test dependencies
|
||||
- [x] 1.1 Create `frontend/src/data/metricDefinitions.json`
|
||||
- Create the `frontend/src/data/` directory
|
||||
- Build the JSON array from the metric definitions table provided by the user (130+ rows, 14 fields each)
|
||||
- Each entry must have all 14 keys: `metric_id`, `metric_title`, `asset_types`, `asset_types_in_scope`, `application_types_in_scope`, `environment_in_scope`, `status_in_scope`, `instance_types_in_scope`, `criticality_levels_in_scope`, `exclusions`, `special_conditions`, `data_sources_required`, `business_justification`, `notes`
|
||||
- Use empty strings for optional fields with no value — never `null` or omitted keys
|
||||
- Verify the file imports without error via a quick `JSON.parse` check
|
||||
- _Requirements: 6.1, 6.2, 6.3, 6.5, 8.3, 8.4_
|
||||
|
||||
- [x] 1.2 Install `fast-check` as a dev dependency
|
||||
- Run `npm install --save-dev fast-check` in `frontend/`
|
||||
- Verify it appears in `package.json` devDependencies
|
||||
- _Requirements: (testing infrastructure)_
|
||||
|
||||
- [x] 2. Implement pure helper functions and their tests
|
||||
- [x] 2.1 Add `computeWorstStatus` and `groupByMetricFamily` helpers to CompliancePage.js
|
||||
- Add `STATUS_SEVERITY` map: `{ 'Below 15% of Target': 0, 'Within 15% of Target': 1, 'Meets/Exceeds Target': 2 }`
|
||||
- Implement `computeWorstStatus(statuses)` — returns the status with the lowest severity rank from a non-empty array
|
||||
- Implement `groupByMetricFamily(allEntries, team)` — filters entries by team, groups by `metric_id`, returns array of `{ metricId, entries, category, target, worstStatus }` objects
|
||||
- Export both functions for testing (named exports alongside the default CompliancePage export)
|
||||
- Remove the existing `teamMetrics()` helper (replaced by `groupByMetricFamily`)
|
||||
- _Requirements: 1.1, 1.2, 1.6, 3.1_
|
||||
|
||||
- [x] 2.2 Write property test: Grouping invariant — no entries lost or misplaced
|
||||
- **Property 1: Grouping invariant — no entries lost or misplaced**
|
||||
- Create test file `frontend/src/components/pages/__tests__/complianceGrouping.property.test.js`
|
||||
- Generate random arrays of summary entry objects with varying `metric_id` and `team` values
|
||||
- Verify: (a) every entry appears in exactly one group, (b) all entries within a group share the same `metric_id`, (c) total entries across groups equals team-filtered input count
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 1.1, 1.2**
|
||||
|
||||
- [x] 2.3 Write property test: Worst-status computation follows severity ordering
|
||||
- **Property 2: Worst-status computation follows severity ordering**
|
||||
- Generate random non-empty arrays of status strings from `{"Below 15% of Target", "Within 15% of Target", "Meets/Exceeds Target"}`
|
||||
- Verify the result is the status with the lowest severity rank present in the array
|
||||
- If the array contains "Below 15% of Target", the result must be "Below 15% of Target"
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 1.6, 3.1**
|
||||
|
||||
- [ ]* 2.4 Write property test: Device filtering with metric family includes all matching devices
|
||||
- **Property 3: Device filtering with metric family includes all matching devices**
|
||||
- Generate random device arrays (each with a `failing_metrics` array of `{ metric_id }` objects) and random filter ID arrays
|
||||
- Verify the filtered result contains exactly those devices with at least one matching `metric_id` in the filter array
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 1.8, 7.1, 7.2**
|
||||
|
||||
- [x] 3. Checkpoint — Verify helpers and property tests
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 4. Redesign MetricHealthCard with variant pills and worst-status coloring
|
||||
- [x] 4.1 Redesign `MetricHealthCard` to accept a family group
|
||||
- Change props from `{ entry, active, onClick }` to `{ family, active, onClick, onInfoClick, definitionLookup }`
|
||||
- `family` is `{ metricId, entries, category, target, worstStatus }`
|
||||
- Display base `metricId` as card title and `category` from the family
|
||||
- Display shared `target` percentage
|
||||
- Use `worstStatus` color for card border, status pill text, and status dot
|
||||
- When all variants meet/exceed target, show "OK" status indicator with success color
|
||||
- Add `Info` icon (lucide-react) in the top-right corner with `stopPropagation` on click to call `onInfoClick(family.metricId)`
|
||||
- _Requirements: 1.2, 1.3, 1.6, 1.7, 3.1, 3.2, 3.3, 5.1, 5.5_
|
||||
|
||||
- [x] 4.2 Implement `VariantPill` inline sub-component
|
||||
- Render one pill per `entry` in `family.entries`
|
||||
- Each pill shows the entry's `description` or `team` label and compliance percentage in monospace
|
||||
- Background tint from the entry's individual status color at ~12% opacity
|
||||
- Show a glow dot when the variant's status is not "Meets/Exceeds Target"
|
||||
- Layout: `inline-flex` with `flexWrap: 'wrap'` on the parent container
|
||||
- _Requirements: 1.4, 1.5, 2.1, 2.2, 2.3, 2.4_
|
||||
|
||||
- [x] 5. Update CompliancePage state and rendering to use grouped families
|
||||
- [x] 5.1 Add new imports and build the definitions lookup map
|
||||
- Import `{ Info }` from `lucide-react`
|
||||
- Import `MetricInfoPanel` from `./MetricInfoPanel` (created in task 6)
|
||||
- Import `metricDefinitionsRaw` from `../../data/metricDefinitions.json`
|
||||
- Build `METRIC_DEFINITIONS` lookup object at module level keyed by `metric_id`
|
||||
- _Requirements: 6.3, 6.4_
|
||||
|
||||
- [x] 5.2 Update state management and filter logic
|
||||
- Change `metricFilter` from `string|null` to `string[]|null`
|
||||
- Add new state: `infoMetric` (`string|null`) — which metric's info panel is open
|
||||
- Add new state: `hoveredMetric` (`string|null`) — which metric is being hovered
|
||||
- Add new ref: `hoverTimeoutRef` — for 300ms delay management
|
||||
- Update `filteredDevices` filter from `m.metric_id === metricFilter` to `metricFilter.includes(m.metric_id)`
|
||||
- _Requirements: 7.1, 7.2_
|
||||
|
||||
- [x] 5.3 Update card rendering to use `groupByMetricFamily`
|
||||
- Replace `const metrics = teamMetrics(summary.entries, activeTeam)` with `const families = groupByMetricFamily(summary.entries, activeTeam)`
|
||||
- Replace `metrics.map(entry => <MetricHealthCard entry={entry} ... />)` with `families.map(family => <MetricHealthCard family={family} ... />)`
|
||||
- On card click: set `metricFilter` to `family.entries.map(e => e.metric_id)` (array of all IDs in the family), or clear if already active
|
||||
- Active state check: compare `metricFilter` array contents against the family's metric IDs
|
||||
- Pass `onInfoClick` handler that sets `infoMetric` state
|
||||
- Pass `definitionLookup` as `METRIC_DEFINITIONS`
|
||||
- _Requirements: 1.2, 1.8, 7.1, 7.3, 7.4, 7.5_
|
||||
|
||||
- [x] 6. Implement MetricInfoPanel component
|
||||
- [x] 6.1 Create `frontend/src/components/pages/MetricInfoPanel.js`
|
||||
- Props: `metricId`, `definition` (from lookup or null), `summaryEntries` (family entries for fallback), `onClose`
|
||||
- Render overlay/slide-out panel with dark theme matching DESIGN_SYSTEM.md
|
||||
- Close button (X icon, top-right)
|
||||
- Metric title in h3 monospace
|
||||
- Sections with monospace uppercase labels: Asset Types, Asset Types In Scope, Application Types In Scope, Environment In Scope, Status In Scope, Instance Types In Scope, Criticality Levels In Scope, Exclusions, Special Conditions, Data Sources Required, Business Justification, Notes
|
||||
- Show "—" placeholder for empty string fields
|
||||
- If `definition` is null: show "No detailed definition available" with summary description fallback
|
||||
- Click outside or close button calls `onClose()`
|
||||
- _Requirements: 5.2, 5.3, 5.4, 5.6, 5.7_
|
||||
|
||||
- [x] 7. Implement HoverTooltip inline in CompliancePage
|
||||
- [x] 7.1 Add hover tooltip logic and rendering
|
||||
- On `mouseEnter` on MetricHealthCard: set 300ms timeout, then set `hoveredMetric` to `family.metricId`
|
||||
- On `mouseLeave`: clear timeout, set `hoveredMetric` to null
|
||||
- Render tooltip when `hoveredMetric` matches a family — positioned near the card using `getBoundingClientRect()`
|
||||
- Tooltip content: metric title, business justification, data sources required (from `METRIC_DEFINITIONS` lookup)
|
||||
- Fall back to summary entry `description` when no definition exists
|
||||
- Dark card background with subtle border and shadow per DESIGN_SYSTEM.md
|
||||
- Tooltip must not interfere with card click behavior
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5, 4.6_
|
||||
|
||||
- [x] 8. Checkpoint — Verify full UI integration
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 9. Property tests for definitions data and lookup
|
||||
- [x] 9.1 Write property test: Definition lookup returns correct entry or null
|
||||
- **Property 4: Definition lookup returns correct entry or null**
|
||||
- Create test file `frontend/src/components/pages/__tests__/metricDefinitions.property.test.js`
|
||||
- Generate random arrays of metric definition objects with unique `metric_id` values
|
||||
- Build lookup map, query with IDs from the array (expect hit) and IDs not in the array (expect miss)
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 4.2, 4.6**
|
||||
|
||||
- [x] 9.2 Write property test: Detail panel renders all required definition fields
|
||||
- **Property 5: Detail panel renders all required definition fields**
|
||||
- Generate random metric definition objects with all 14 fields
|
||||
- Extract the set of field keys that the MetricInfoPanel renders and verify all required keys are present
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 5.3**
|
||||
|
||||
- [x] 9.3 Write property test: Definitions schema validation — all entries have required fields
|
||||
- **Property 6: Definitions schema validation — all entries have required fields**
|
||||
- Generate random arrays of metric definition objects
|
||||
- Verify every entry has all 14 keys present, `metric_id` is a non-empty string, and optional fields (`exclusions`, `special_conditions`, `notes`) are strings (not null/undefined)
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 6.2, 8.3, 8.4**
|
||||
|
||||
- [x] 9.4 Write property test: Lookup map construction preserves all definitions
|
||||
- **Property 7: Lookup map construction preserves all definitions**
|
||||
- Generate random definition arrays with unique `metric_id` values
|
||||
- Build lookup map and verify map size equals array length, and every definition is retrievable by its `metric_id`
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 6.4**
|
||||
|
||||
- [x] 9.5 Write property test: JSON round-trip preserves metric definition data
|
||||
- **Property 8: JSON round-trip preserves metric definition data**
|
||||
- Generate random metric definition objects with string values for all fields
|
||||
- Round-trip through `JSON.stringify` then `JSON.parse` and verify deep equality
|
||||
- Use `fc.assert(property, { numRuns: 100 })`
|
||||
- **Validates: Requirements 8.1, 8.2**
|
||||
|
||||
- [x] 10. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests validate universal correctness properties from the design document using fast-check
|
||||
- Unit tests validate specific examples and edge cases
|
||||
- All styling follows the project convention of inline styles (no CSS modules or Tailwind)
|
||||
- The `fast-check` library must be installed as a dev dependency before running property tests
|
||||
- The `metricDefinitions.json` file contains 130+ rows — the user will provide the metric definitions table data for conversion
|
||||
- `computeWorstStatus` and `groupByMetricFamily` are exported as named exports from CompliancePage.js for testability
|
||||
1
.kiro/specs/compliance-multi-metric-notes/.config.kiro
Normal file
1
.kiro/specs/compliance-multi-metric-notes/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "8ec01dea-8d5c-40c1-8778-ec2992adb37f", "workflowType": "requirements-first", "specType": "feature"}
|
||||
290
.kiro/specs/compliance-multi-metric-notes/design.md
Normal file
290
.kiro/specs/compliance-multi-metric-notes/design.md
Normal file
@@ -0,0 +1,290 @@
|
||||
# Design Document: Multi-Metric Notes for Compliance Detail Panel
|
||||
|
||||
## Overview
|
||||
|
||||
This feature extends the compliance notes system so that a single note can be associated with multiple metrics in one action. Today, the `ComplianceDetailPanel` uses a single-select `<select>` dropdown to pick one metric before adding a note. When a remediation action covers several metrics on the same device, the analyst must repeat the note for each metric individually.
|
||||
|
||||
The change touches three layers:
|
||||
|
||||
1. **Database** — add a `group_id` column to `compliance_notes` so notes created together can be identified as a batch.
|
||||
2. **API** — extend `POST /api/compliance/notes` to accept `metric_ids` (array) alongside the existing `metric_id` (string), inserting one row per metric inside a transaction.
|
||||
3. **Frontend** — replace the single-select dropdown with a multi-select chip-based selector, add Select All / Deselect All, and group notes by `group_id` in the display.
|
||||
|
||||
Backward compatibility is preserved: the existing `metric_id` field continues to work, and notes created before this feature (which lack a `group_id`) render exactly as they do today.
|
||||
|
||||
## Architecture
|
||||
|
||||
The feature follows the existing compliance module architecture. No new files or route modules are introduced — changes are scoped to the existing `compliance.js` route file and `ComplianceDetailPanel.js` component.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant DetailPanel as ComplianceDetailPanel
|
||||
participant API as POST /api/compliance/notes
|
||||
participant DB as SQLite (compliance_notes)
|
||||
|
||||
User->>DetailPanel: Select multiple metrics via chip selector
|
||||
User->>DetailPanel: Type note text, click Send
|
||||
DetailPanel->>API: POST { hostname, metric_ids: [...], note }
|
||||
API->>API: Validate inputs (note text, metric IDs)
|
||||
API->>API: Generate group_id (UUID)
|
||||
API->>DB: BEGIN TRANSACTION
|
||||
loop For each metric_id in metric_ids
|
||||
API->>DB: INSERT INTO compliance_notes (hostname, metric_id, note, group_id, created_by, created_at)
|
||||
end
|
||||
API->>DB: COMMIT
|
||||
API->>DetailPanel: 201 { notes: [...created rows] }
|
||||
DetailPanel->>DetailPanel: Group notes by group_id, refresh display
|
||||
```
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend
|
||||
|
||||
**Modified: `POST /api/compliance/notes`**
|
||||
|
||||
Request body accepts either format:
|
||||
|
||||
```javascript
|
||||
// New multi-metric format
|
||||
{ hostname: "SERVER01", metric_ids: ["2.1.1", "2.3.2", "4.1.1"], note: "Vendor ticket VT-1234 opened" }
|
||||
|
||||
// Legacy single-metric format (still supported)
|
||||
{ hostname: "SERVER01", metric_id: "2.1.1", note: "Vendor ticket VT-1234 opened" }
|
||||
```
|
||||
|
||||
Precedence: if both `metric_id` and `metric_ids` are present, `metric_ids` wins.
|
||||
|
||||
Validation rules:
|
||||
- `hostname` — required, string, 1–300 chars, matches `/^[a-zA-Z0-9._-]+$/` (unchanged)
|
||||
- `metric_ids` — array of strings, each non-empty and ≤50 chars, at least one entry
|
||||
- `note` — required, non-empty after trimming, max 1000 chars (unchanged)
|
||||
|
||||
On success, the endpoint returns all created rows (with `username` joined from `users`) so the frontend can update without a separate fetch.
|
||||
|
||||
**New: Migration script `backend/migrations/add_compliance_notes_group_id.js`**
|
||||
|
||||
Adds the `group_id` column and backfills existing rows:
|
||||
|
||||
```sql
|
||||
ALTER TABLE compliance_notes ADD COLUMN group_id TEXT;
|
||||
CREATE INDEX idx_compliance_notes_group ON compliance_notes(group_id);
|
||||
-- Backfill: each existing row gets its own unique group_id
|
||||
UPDATE compliance_notes SET group_id = 'legacy-' || id WHERE group_id IS NULL;
|
||||
```
|
||||
|
||||
The backfill ensures every row has a `group_id`, so the frontend grouping logic works uniformly without null checks.
|
||||
|
||||
### Frontend
|
||||
|
||||
**Modified: `ComplianceDetailPanel.js`**
|
||||
|
||||
The notes section is updated with three changes:
|
||||
|
||||
1. **Multi-select metric selector** — replaces the `<select>` dropdown with a chip-based toggle list. Each active metric is rendered as a clickable `MetricChip`. Selected chips get a highlighted border/background. A "Select All" / "Deselect All" toggle appears when there are 2+ active metrics.
|
||||
|
||||
2. **Submission logic** — `handleAddNote` sends `metric_ids` (array of selected metric IDs) instead of `metric_id` (single string). The submit button is disabled when no metrics are selected or note text is empty.
|
||||
|
||||
3. **Note display grouping** — notes are grouped by `group_id` before rendering. Notes sharing a `group_id` are displayed as a single card with multiple `MetricChip` badges. Notes without a `group_id` (pre-migration legacy) render as individual entries, same as today.
|
||||
|
||||
**Component structure:**
|
||||
|
||||
```
|
||||
ComplianceDetailPanel
|
||||
├── Header (hostname, IP, device type, team)
|
||||
├── Section: Failing Metrics
|
||||
│ └── MetricRow (per active metric)
|
||||
├── Section: Resolved Metrics
|
||||
│ └── MetricRow (per resolved metric)
|
||||
├── Section: History
|
||||
│ └── MetricChip + seen count (per active metric)
|
||||
└── Section: Notes
|
||||
├── NoteCard (per group_id group, shows multiple MetricChips if multi-metric)
|
||||
└── Add Note Form
|
||||
├── MetricChipSelector (multi-select chip toggles)
|
||||
│ ├── MetricChip (per active metric, clickable)
|
||||
│ └── Select All / Deselect All toggle
|
||||
├── Textarea (note text)
|
||||
└── Send button (disabled when no metrics selected or text empty)
|
||||
```
|
||||
|
||||
**MetricChipSelector behavior:**
|
||||
|
||||
| State | Behavior |
|
||||
|---|---|
|
||||
| 1 active metric | Chip is pre-selected and non-removable. No Select All toggle. |
|
||||
| 2+ active metrics, panel just opened | First metric pre-selected. Select All toggle visible. |
|
||||
| User clicks unselected chip | Chip added to selection |
|
||||
| User clicks selected chip (2+ selected) | Chip removed from selection |
|
||||
| User clicks selected chip (only 1 selected, 2+ metrics exist) | No-op — at least one must remain selected |
|
||||
| Select All clicked | All active metrics selected, toggle label changes to "Deselect All" |
|
||||
| Deselect All clicked | All metrics deselected except the first (to maintain minimum selection) |
|
||||
|
||||
**Design rationale — minimum selection of 1:** The submit button is disabled when no metrics are selected (Requirement 3.4). Rather than allowing the user to reach an empty state and see a disabled button, "Deselect All" keeps the first metric selected. This matches the current UX where a metric is always selected.
|
||||
|
||||
## Data Models
|
||||
|
||||
### compliance_notes table (modified)
|
||||
|
||||
| Column | Type | Description |
|
||||
|---|---|---|
|
||||
| `id` | INTEGER PK | Auto-increment row ID |
|
||||
| `hostname` | TEXT NOT NULL | Device hostname |
|
||||
| `metric_id` | TEXT NOT NULL | Compliance metric ID |
|
||||
| `note` | TEXT NOT NULL | Note text (max 1000 chars) |
|
||||
| `group_id` | TEXT | Batch identifier — rows from the same submission share this value |
|
||||
| `created_by` | INTEGER FK | User ID of the note author |
|
||||
| `created_at` | DATETIME | Timestamp of creation |
|
||||
|
||||
The `group_id` is a UUID v4 string generated server-side via `crypto.randomUUID()`. Single-metric submissions also receive a `group_id` so the frontend grouping logic is uniform.
|
||||
|
||||
**Index:** `idx_compliance_notes_group ON compliance_notes(group_id)` — supports the frontend's grouping query.
|
||||
|
||||
### API Response Shape
|
||||
|
||||
`POST /api/compliance/notes` response (201):
|
||||
|
||||
```json
|
||||
{
|
||||
"notes": [
|
||||
{
|
||||
"id": 42,
|
||||
"hostname": "SERVER01",
|
||||
"metric_id": "2.1.1",
|
||||
"note": "Vendor ticket VT-1234 opened",
|
||||
"group_id": "a1b2c3d4-...",
|
||||
"created_at": "2025-01-15 14:30:00",
|
||||
"created_by": "jsmith"
|
||||
},
|
||||
{
|
||||
"id": 43,
|
||||
"hostname": "SERVER01",
|
||||
"metric_id": "2.3.2",
|
||||
"note": "Vendor ticket VT-1234 opened",
|
||||
"group_id": "a1b2c3d4-...",
|
||||
"created_at": "2025-01-15 14:30:00",
|
||||
"created_by": "jsmith"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`GET /api/compliance/items/:hostname` response — the existing `notes` array now includes `group_id`:
|
||||
|
||||
```json
|
||||
{
|
||||
"notes": [
|
||||
{ "id": 43, "metric_id": "2.3.2", "note": "...", "group_id": "a1b2c3d4-...", "created_at": "...", "created_by": "jsmith" },
|
||||
{ "id": 42, "metric_id": "2.1.1", "note": "...", "group_id": "a1b2c3d4-...", "created_at": "...", "created_by": "jsmith" },
|
||||
{ "id": 10, "metric_id": "2.1.1", "note": "...", "group_id": "legacy-10", "created_at": "...", "created_by": "admin" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The frontend groups consecutive notes by `group_id` to render multi-metric notes as a single card.
|
||||
|
||||
## 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: Select All / Deselect All round-trip
|
||||
|
||||
*For any* set of active metrics with size > 1, clicking "Select All" should result in all metrics being selected, and then clicking "Deselect All" should result in only the first metric remaining selected (minimum selection invariant).
|
||||
|
||||
**Validates: Requirements 2.1, 2.2**
|
||||
|
||||
### Property 2: Toggle label reflects selection state
|
||||
|
||||
*For any* set of active metrics, if the user manually selects every metric one by one, the toggle label should read "Deselect All" — the label is a pure function of whether all metrics are selected, regardless of how that state was reached.
|
||||
|
||||
**Validates: Requirements 2.3**
|
||||
|
||||
### Property 3: Multi-metric submission creates correct rows with shared group_id
|
||||
|
||||
*For any* valid hostname, non-empty note text, and non-empty array of valid metric IDs, submitting a note should create exactly N rows in `compliance_notes` (where N = length of the metric IDs array), all sharing the same `note` text, `created_by` user, `created_at` timestamp, and `group_id` value.
|
||||
|
||||
**Validates: Requirements 3.1, 3.2, 5.3, 5.7, 6.1**
|
||||
|
||||
### Property 4: Whitespace-only notes are rejected
|
||||
|
||||
*For any* string composed entirely of whitespace characters (spaces, tabs, newlines, or combinations thereof), the Notes API should reject the submission with a 400 error and create zero rows in the database.
|
||||
|
||||
**Validates: Requirements 3.3**
|
||||
|
||||
### Property 5: Atomic validation — invalid metric IDs reject the entire batch
|
||||
|
||||
*For any* array of metric IDs where at least one entry is invalid (empty string, exceeds 50 characters, or non-string), the Notes API should reject the entire request with a 400 error and insert zero rows, even if all other entries are valid.
|
||||
|
||||
**Validates: Requirements 5.2, 5.6**
|
||||
|
||||
### Property 6: Note grouping display
|
||||
|
||||
*For any* set of notes where multiple notes share the same `group_id`, the Detail Panel should render them as a single note entry displaying all associated Metric Chips, rather than as separate entries.
|
||||
|
||||
**Validates: Requirements 4.1, 4.2, 6.4**
|
||||
|
||||
### Property 7: Reverse chronological note ordering
|
||||
|
||||
*For any* set of notes with varying `created_at` timestamps and group sizes, the Detail Panel should display note groups in reverse chronological order (newest `created_at` first), regardless of how many metrics each group covers.
|
||||
|
||||
**Validates: Requirements 4.3**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Backend
|
||||
|
||||
| Scenario | Response | Behavior |
|
||||
|---|---|---|
|
||||
| Empty or whitespace-only note text | 400 `{ error: "Note cannot be empty" }` | No rows inserted |
|
||||
| `metric_ids` is empty array | 400 `{ error: "At least one metric ID is required" }` | No rows inserted |
|
||||
| Any metric ID in array is empty or >50 chars | 400 `{ error: "Invalid metric_id at index N" }` | No rows inserted (atomic rejection) |
|
||||
| `metric_ids` is not an array (when provided) | 400 `{ error: "metric_ids must be an array" }` | Falls back to checking `metric_id` |
|
||||
| Neither `metric_id` nor `metric_ids` provided | 400 `{ error: "metric_id or metric_ids is required" }` | No rows inserted |
|
||||
| Database error during transaction | 500 `{ error: "Failed to save note" }` | Transaction rolled back, no partial inserts |
|
||||
| Invalid hostname format | 400 `{ error: "Invalid hostname format" }` | No rows inserted (unchanged) |
|
||||
|
||||
Transaction safety: all inserts for a multi-metric note happen inside `BEGIN TRANSACTION` / `COMMIT`. If any insert fails, the transaction is rolled back and no rows are persisted.
|
||||
|
||||
### Frontend
|
||||
|
||||
| Scenario | Behavior |
|
||||
|---|---|
|
||||
| API returns 400 validation error | Display error message below the note input (existing `noteError` state) |
|
||||
| API returns 500 server error | Display error message below the note input |
|
||||
| Network failure | Display "Failed to save note" error |
|
||||
| No metrics selected | Submit button is disabled, no API call made |
|
||||
| Successful submission | Clear note text, refresh notes list, retain metric selection |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (example-based)
|
||||
|
||||
- **Backend:**
|
||||
- Legacy `metric_id` field still creates a single note row (backward compatibility)
|
||||
- Both `metric_id` and `metric_ids` provided — `metric_ids` takes precedence
|
||||
- Single active metric pre-selects and is non-removable
|
||||
- Response shape includes all created rows with `group_id` and `username`
|
||||
|
||||
- **Frontend:**
|
||||
- MetricChipSelector renders correct number of chips for given active metrics
|
||||
- Clicking a chip toggles its selection state
|
||||
- Submit button disabled when note text is empty or no metrics selected
|
||||
- Notes without `group_id` (legacy) render as individual entries
|
||||
- Single active metric auto-selects and hides Select All toggle
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based tests use `fast-check` (JavaScript PBT library) with a minimum of 100 iterations per property.
|
||||
|
||||
Each property test is tagged with a comment referencing the design property:
|
||||
- **Feature: compliance-multi-metric-notes, Property 3: Multi-metric submission creates correct rows with shared group_id**
|
||||
- **Feature: compliance-multi-metric-notes, Property 4: Whitespace-only notes are rejected**
|
||||
- **Feature: compliance-multi-metric-notes, Property 5: Atomic validation — invalid metric IDs reject the entire batch**
|
||||
|
||||
Backend properties (3, 4, 5) are tested against the route handler using a test SQLite database. Frontend properties (1, 2, 6, 7) are tested against the component rendering/grouping logic using React Testing Library with generated inputs.
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- End-to-end flow: open detail panel → select multiple metrics → submit note → verify grouped display
|
||||
- Migration script: verify `group_id` column exists and legacy rows are backfilled
|
||||
- Backward compatibility: existing `GET /items/:hostname` response includes `group_id` field on notes
|
||||
85
.kiro/specs/compliance-multi-metric-notes/requirements.md
Normal file
85
.kiro/specs/compliance-multi-metric-notes/requirements.md
Normal file
@@ -0,0 +1,85 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The compliance detail panel currently allows users to add notes to a single metric at a time via a dropdown selector. When a remediation action, vendor ticket, or status update applies to multiple metrics on the same device, users must repeat the same note for each metric individually. This feature adds multi-metric selection to the note creation flow so that a single note can be associated with multiple metrics in one action, while preserving the existing per-metric note history and display.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Detail_Panel**: The slide-out panel (`ComplianceDetailPanel.js`) that opens when a user clicks a device row on the Compliance page. It displays failing metrics, resolved metrics, upload history, and notes for a single hostname.
|
||||
- **Note**: A timestamped, user-attributed text entry stored in the `compliance_notes` table, keyed on `(hostname, metric_id)`. Notes persist across uploads and form a historical record.
|
||||
- **Metric_Selector**: The UI control in the Detail_Panel's notes section that allows the user to choose which metric(s) a note applies to. Currently a single-select dropdown; this feature replaces it with a multi-select control.
|
||||
- **Metric_Chip**: A small colored badge displaying a metric ID, used throughout the compliance UI to visually identify metrics by category color.
|
||||
- **Notes_API**: The `POST /api/compliance/notes` endpoint that persists a note to the database.
|
||||
- **Active_Metric**: A compliance item with `status = 'active'` for the selected hostname — these are the metrics currently failing.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Multi-Metric Selection UI
|
||||
|
||||
**User Story:** As a compliance analyst, I want to select multiple metrics when adding a note, so that I can document a single remediation action that covers several metrics without repeating myself.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Detail_Panel is open for a hostname with more than one Active_Metric, THE Metric_Selector SHALL display all Active_Metrics as individually selectable options.
|
||||
2. WHEN the user interacts with the Metric_Selector, THE Metric_Selector SHALL allow the user to select one or more Active_Metrics simultaneously.
|
||||
3. WHEN the Detail_Panel is open for a hostname with exactly one Active_Metric, THE Metric_Selector SHALL pre-select that metric and remain visible as a single non-removable selection.
|
||||
4. WHEN the Detail_Panel first opens for a hostname with multiple Active_Metrics, THE Metric_Selector SHALL pre-select the first Active_Metric by default.
|
||||
5. THE Metric_Selector SHALL display each option using the Metric_Chip component with the metric's category color, so that metrics are visually distinguishable.
|
||||
|
||||
### Requirement 2: Select All / Deselect All
|
||||
|
||||
**User Story:** As a compliance analyst, I want a quick way to select or deselect all metrics, so that I can efficiently apply a note to every failing metric on a device.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the hostname has more than one Active_Metric, THE Metric_Selector SHALL display a "Select All" toggle that selects all Active_Metrics when activated.
|
||||
2. WHEN all Active_Metrics are already selected, THE "Select All" toggle SHALL change to "Deselect All" and deselect all Active_Metrics when activated.
|
||||
3. WHEN the user manually selects all Active_Metrics one by one, THE toggle label SHALL update to "Deselect All" to reflect the current state.
|
||||
|
||||
### Requirement 3: Multi-Metric Note Submission
|
||||
|
||||
**User Story:** As a compliance analyst, I want the system to save my note against all selected metrics in one action, so that the historical record accurately reflects which metrics the note covers.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the user submits a note with multiple metrics selected, THE Notes_API SHALL create one `compliance_notes` row per selected metric, all sharing the same note text, `created_by`, and `created_at` timestamp.
|
||||
2. WHEN the user submits a note with a single metric selected, THE Notes_API SHALL create exactly one `compliance_notes` row, preserving backward compatibility with the existing behavior.
|
||||
3. IF the note text is empty or contains only whitespace, THEN THE Notes_API SHALL reject the submission and return a validation error.
|
||||
4. IF no metrics are selected, THEN THE Detail_Panel SHALL disable the submit button and prevent submission.
|
||||
5. WHEN a multi-metric note is successfully saved, THE Detail_Panel SHALL clear the note text field, refresh the notes list, and retain the current metric selection.
|
||||
|
||||
### Requirement 4: Multi-Metric Note Display
|
||||
|
||||
**User Story:** As a compliance analyst, I want to see which metrics a note was applied to, so that I can understand the scope of past remediation actions.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a note was submitted for multiple metrics simultaneously, THE Detail_Panel SHALL display all associated Metric_Chips together on that note entry, visually grouped.
|
||||
2. WHEN a note was submitted for a single metric, THE Detail_Panel SHALL continue to display a single Metric_Chip on that note entry, matching the current behavior.
|
||||
3. THE Detail_Panel SHALL display notes in reverse chronological order, with the newest note first, regardless of how many metrics each note covers.
|
||||
|
||||
### Requirement 5: Backend Multi-Metric Notes Endpoint
|
||||
|
||||
**User Story:** As a developer, I want the notes API to accept an array of metric IDs, so that the frontend can submit a note for multiple metrics in a single request.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Notes_API SHALL accept a `metric_ids` field (array of strings) in the request body as an alternative to the existing `metric_id` field (single string).
|
||||
2. WHEN `metric_ids` is provided, THE Notes_API SHALL validate that each entry is a non-empty string of 50 characters or fewer.
|
||||
3. WHEN `metric_ids` is provided, THE Notes_API SHALL insert one `compliance_notes` row per metric ID, all within the same database transaction, sharing the same `created_at` timestamp.
|
||||
4. WHEN the legacy `metric_id` field is provided instead of `metric_ids`, THE Notes_API SHALL continue to function as before, inserting a single row.
|
||||
5. IF both `metric_id` and `metric_ids` are provided, THEN THE Notes_API SHALL use `metric_ids` and ignore `metric_id`.
|
||||
6. IF any metric ID in the `metric_ids` array fails validation, THEN THE Notes_API SHALL reject the entire request and return a 400 error without inserting any rows.
|
||||
7. THE Notes_API SHALL return all created note rows in the response, so the frontend can update the display without a separate fetch.
|
||||
|
||||
### Requirement 6: Note Grouping Identifier
|
||||
|
||||
**User Story:** As a developer, I want notes that were created together to share a group identifier, so that the frontend can visually group multi-metric notes in the display.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN multiple notes are created from a single submission, THE Notes_API SHALL assign the same `group_id` value to all rows in that batch.
|
||||
2. WHEN a single note is created, THE Notes_API SHALL assign a unique `group_id` to that row.
|
||||
3. THE `group_id` SHALL be stored as a text column in the `compliance_notes` table.
|
||||
4. THE Detail_Panel SHALL use the `group_id` to visually group notes that were submitted together, displaying them as a single note entry with multiple Metric_Chips rather than as separate entries.
|
||||
105
.kiro/specs/compliance-multi-metric-notes/tasks.md
Normal file
105
.kiro/specs/compliance-multi-metric-notes/tasks.md
Normal file
@@ -0,0 +1,105 @@
|
||||
# Implementation Plan: Multi-Metric Notes for Compliance Detail Panel
|
||||
|
||||
## Overview
|
||||
|
||||
Extend the compliance notes system so a single note can be associated with multiple metrics in one action. Changes span three layers: a new migration script adding `group_id` to `compliance_notes`, updates to the `POST /notes` endpoint in `backend/routes/compliance.js` to accept `metric_ids` (array) and insert rows transactionally, and frontend changes in `ComplianceDetailPanel.js` to replace the single-select dropdown with a multi-select chip selector and group notes by `group_id` in the display.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Create database migration for `group_id` column
|
||||
- [x] 1.1 Create `backend/migrations/add_compliance_notes_group_id.js`
|
||||
- Add `group_id TEXT` column to `compliance_notes` table via `ALTER TABLE`
|
||||
- Create index `idx_compliance_notes_group` on `compliance_notes(group_id)`
|
||||
- Backfill existing rows: `UPDATE compliance_notes SET group_id = 'legacy-' || id WHERE group_id IS NULL`
|
||||
- Follow the existing migration pattern (sqlite3, serialize, console logging)
|
||||
- _Requirements: 6.1, 6.2, 6.3_
|
||||
|
||||
- [x] 2. Update `POST /notes` endpoint to support multi-metric submissions
|
||||
- [x] 2.1 Modify the `POST /notes` handler in `backend/routes/compliance.js` to accept `metric_ids` array
|
||||
- Accept `metric_ids` (array of strings) as an alternative to `metric_id` (single string)
|
||||
- When both are provided, `metric_ids` takes precedence
|
||||
- When neither is provided, return 400 with `"metric_id or metric_ids is required"`
|
||||
- When `metric_ids` is provided but is not an array, return 400 with `"metric_ids must be an array"`
|
||||
- Normalize single `metric_id` into a one-element array internally so the rest of the logic is uniform
|
||||
- _Requirements: 5.1, 5.4, 5.5_
|
||||
|
||||
- [x] 2.2 Add validation for `metric_ids` array entries
|
||||
- Validate that `metric_ids` has at least one entry; return 400 with `"At least one metric ID is required"` if empty
|
||||
- Validate each entry is a non-empty string of 50 characters or fewer; return 400 with `"Invalid metric_id at index N"` on failure
|
||||
- Reject the entire request if any entry fails validation (atomic rejection, no partial inserts)
|
||||
- _Requirements: 5.2, 5.6_
|
||||
|
||||
- [x] 2.3 Implement transactional multi-row insert with `group_id`
|
||||
- Generate a `group_id` using `crypto.randomUUID()` for each submission (single or multi)
|
||||
- Wrap all inserts in `BEGIN TRANSACTION` / `COMMIT` with `ROLLBACK` on error
|
||||
- Insert one `compliance_notes` row per metric ID, all sharing the same `note`, `group_id`, `created_by`, and `created_at`
|
||||
- _Requirements: 3.1, 3.2, 5.3, 6.1, 6.2_
|
||||
|
||||
- [x] 2.4 Update the response to return all created note rows
|
||||
- After commit, query all created rows (joined with `users` for `username`) and return as `{ notes: [...] }`
|
||||
- Each row includes `id`, `hostname`, `metric_id`, `note`, `group_id`, `created_at`, `created_by`
|
||||
- Return HTTP 201 status
|
||||
- _Requirements: 5.7_
|
||||
|
||||
- [x] 3. Update `GET /items/:hostname` to include `group_id` in notes response
|
||||
- Add `cn.group_id` to the SELECT in the notes query within the `GET /items/:hostname` handler
|
||||
- The existing query already fetches notes for the hostname; just add the column
|
||||
- No other changes to this endpoint
|
||||
- _Requirements: 6.3, 6.4_
|
||||
|
||||
- [x] 4. Checkpoint — Verify backend changes
|
||||
- Ensure all backend changes are syntactically correct, ask the user if questions arise.
|
||||
|
||||
- [x] 5. Replace single-select dropdown with multi-select MetricChipSelector in `ComplianceDetailPanel.js`
|
||||
- [x] 5.1 Replace `noteMetric` (string) state with `selectedMetrics` (array) state
|
||||
- Initialize `selectedMetrics` with the first active metric's ID when detail loads (matching current default behavior)
|
||||
- When there is exactly one active metric, pre-select it as a non-removable selection
|
||||
- _Requirements: 1.3, 1.4_
|
||||
|
||||
- [x] 5.2 Build the multi-select chip-based metric selector UI
|
||||
- Replace the existing `<select>` dropdown with a row of clickable `MetricChip` components
|
||||
- Each active metric renders as a chip; selected chips get a highlighted border/background
|
||||
- Clicking an unselected chip adds it to `selectedMetrics`
|
||||
- Clicking a selected chip removes it, unless it is the only selected chip (minimum 1 selection)
|
||||
- Only show the chip selector when there are 2+ active metrics (single metric is auto-selected)
|
||||
- Style chips using existing `MetricChip` component patterns and category colors
|
||||
- _Requirements: 1.1, 1.2, 1.5_
|
||||
|
||||
- [x] 5.3 Add Select All / Deselect All toggle
|
||||
- Show a text toggle above or beside the chip row when there are 2+ active metrics
|
||||
- "Select All" selects all active metrics; label changes to "Deselect All"
|
||||
- "Deselect All" deselects all except the first metric (minimum selection invariant)
|
||||
- Toggle label is a pure function of whether all metrics are selected
|
||||
- Hide the toggle when there is only one active metric
|
||||
- _Requirements: 2.1, 2.2, 2.3_
|
||||
|
||||
- [x] 6. Update note submission logic to send `metric_ids` array
|
||||
- Modify `handleAddNote` to send `{ hostname, metric_ids: selectedMetrics, note }` instead of `{ hostname, metric_id: noteMetric, note }`
|
||||
- Disable the submit button when `selectedMetrics` is empty or note text is empty
|
||||
- On success, clear note text, refresh the detail panel, and retain the current metric selection
|
||||
- Handle the new response shape (`{ notes: [...] }`) from the updated API
|
||||
- _Requirements: 3.1, 3.4, 3.5_
|
||||
|
||||
- [x] 7. Update note display to group by `group_id`
|
||||
- [x] 7.1 Add note grouping logic
|
||||
- Group the `detail.notes` array by `group_id` before rendering
|
||||
- Notes sharing a `group_id` are displayed as a single card with multiple `MetricChip` badges
|
||||
- Notes without a `group_id` (pre-migration legacy, should not occur after backfill) render as individual entries
|
||||
- Maintain reverse chronological order (newest `created_at` first) across groups
|
||||
- _Requirements: 4.1, 4.2, 4.3, 6.4_
|
||||
|
||||
- [x] 7.2 Update the note card rendering
|
||||
- For grouped notes, display all associated `MetricChip` components in the card header
|
||||
- For single-metric notes, display one `MetricChip` (matching current behavior)
|
||||
- Preserve existing note card styling (background, border, padding, typography)
|
||||
- _Requirements: 4.1, 4.2_
|
||||
|
||||
- [x] 8. Final checkpoint — Verify full feature
|
||||
- Ensure frontend compiles without errors, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- No automated tests — feature is validated manually per user preference
|
||||
- No new components or route modules required; all changes are scoped to existing files plus one migration
|
||||
- The `group_id` backfill ensures legacy notes render correctly without null checks
|
||||
- Each task references specific requirements for traceability
|
||||
1
.kiro/specs/compliance-schema-drift-check/.config.kiro
Normal file
1
.kiro/specs/compliance-schema-drift-check/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "e83a2e8f-4508-4669-9697-41219c8a7c71", "workflowType": "requirements-first", "specType": "feature"}
|
||||
364
.kiro/specs/compliance-schema-drift-check/design.md
Normal file
364
.kiro/specs/compliance-schema-drift-check/design.md
Normal file
@@ -0,0 +1,364 @@
|
||||
# Design Document: Compliance Schema Drift Check
|
||||
|
||||
## Overview
|
||||
|
||||
This feature adds schema drift detection to the compliance xlsx upload flow. When a user uploads a weekly NTS_AEO report, the backend extracts the xlsx structural schema (sheet names, column headers, metric values) and compares it against a shared parser configuration file. The comparison produces a categorised drift report with three severity levels: breaking (blocks upload), silent-miss (warns but allows proceeding), and cosmetic (informational). The frontend displays these findings in a new drift review phase inside the upload modal, inserted between the upload spinner and the existing diff preview.
|
||||
|
||||
The parser configuration dicts (`METRIC_CATEGORIES`, `CORE_COLS`, `SKIP_SHEETS`) currently defined inline in `parse_compliance_xlsx.py` are extracted into a shared JSON file (`backend/scripts/compliance_config.json`) that both the Python parser and the Node.js drift checker read. This establishes a single source of truth for parser configuration.
|
||||
|
||||
### Design Decisions
|
||||
|
||||
1. **Shared JSON config over database storage**: The parser config is a developer-maintained mapping, not user data. A JSON file is version-controllable, diffable, and readable by both Python and Node.js without additional dependencies.
|
||||
|
||||
2. **Python subprocess for schema extraction**: The existing `dump_xlsx_schema.py` already uses openpyxl to extract xlsx structure. We adapt this into a new `extract_xlsx_schema.py` script that the Node.js backend invokes as a subprocess, consistent with how `parse_compliance_xlsx.py` is already called.
|
||||
|
||||
3. **Node.js drift comparison logic**: The drift comparison is pure object comparison (sets of strings) with no xlsx parsing. Implementing it in Node.js avoids a second Python subprocess call and keeps the logic co-located with the route handler.
|
||||
|
||||
4. **Graceful degradation**: If the drift check fails, the upload flow proceeds normally with `drift: null` and a `drift_error` message. The drift check is additive and must never block the existing workflow.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant Modal as ComplianceUploadModal
|
||||
participant API as POST /api/compliance/preview
|
||||
participant Schema as extract_xlsx_schema.py
|
||||
participant Drift as driftChecker (Node.js)
|
||||
participant Config as compliance_config.json
|
||||
participant Parser as parse_compliance_xlsx.py
|
||||
|
||||
User->>Modal: Drops xlsx file
|
||||
Modal->>API: POST /preview (multipart)
|
||||
API->>Schema: spawn python3 extract_xlsx_schema.py <file>
|
||||
Schema-->>API: JSON { sheets: [...] }
|
||||
API->>Config: fs.readFileSync(compliance_config.json)
|
||||
API->>Drift: compareSchemaToDrift(schema, config)
|
||||
Drift-->>API: { breaking: [...], silent_miss: [...], cosmetic: [...] }
|
||||
API->>Parser: spawn python3 parse_compliance_xlsx.py <file>
|
||||
Parser->>Config: reads compliance_config.json
|
||||
Parser-->>API: JSON { items, summary, ... }
|
||||
API->>API: computeDiff(db, items)
|
||||
API-->>Modal: { drift, diff, tempFile, ... }
|
||||
alt drift has findings
|
||||
Modal->>User: Show drift review phase
|
||||
alt breaking findings exist
|
||||
Modal->>User: Block "Continue to Preview"
|
||||
else no breaking findings
|
||||
User->>Modal: Click "Continue to Preview"
|
||||
Modal->>User: Show diff preview
|
||||
end
|
||||
else no drift findings
|
||||
Modal->>User: Show diff preview directly
|
||||
end
|
||||
```
|
||||
|
||||
### File Layout
|
||||
|
||||
```
|
||||
backend/
|
||||
scripts/
|
||||
compliance_config.json # NEW — shared parser config (single source of truth)
|
||||
extract_xlsx_schema.py # NEW — extracts xlsx structure as JSON
|
||||
parse_compliance_xlsx.py # MODIFIED — reads config from JSON file
|
||||
dump_xlsx_schema.py # UNCHANGED — standalone diagnostic tool
|
||||
routes/
|
||||
compliance.js # MODIFIED — drift check in /preview, new driftChecker module
|
||||
helpers/
|
||||
driftChecker.js # NEW — compareSchemaToDrift() function
|
||||
|
||||
frontend/
|
||||
src/components/pages/
|
||||
ComplianceUploadModal.js # MODIFIED — new drift-review phase
|
||||
```
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### 1. Shared Parser Configuration (`compliance_config.json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"metric_categories": {
|
||||
"2.3.4i": "Vulnerability Management",
|
||||
"2.3.6i": "Vulnerability Management",
|
||||
"5.2.4": "Access & MFA"
|
||||
},
|
||||
"core_cols": [
|
||||
"Preferred - Hostname",
|
||||
"GRANITE - IPv4_Address",
|
||||
"GRANITE - Type",
|
||||
"Team",
|
||||
"Compliant",
|
||||
"Source_Network",
|
||||
"Vertical",
|
||||
"GRANITE - Equip_Inst_ID",
|
||||
"GRANITE - RESPONSIBLE_TEAM"
|
||||
],
|
||||
"skip_sheets": ["Summary", "CMDB_9box", "Vulns", "Aging Dashboard"]
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Schema Extractor (`extract_xlsx_schema.py`)
|
||||
|
||||
**Input**: File path as CLI argument.
|
||||
|
||||
**Output** (stdout JSON):
|
||||
```json
|
||||
{
|
||||
"sheets": [
|
||||
{
|
||||
"name": "Summary",
|
||||
"columns": ["Metric", "Non-Compliant", "..."],
|
||||
"metric_values": ["2.3.4i", "5.2.4", "..."]
|
||||
},
|
||||
{
|
||||
"name": "2.3.4i",
|
||||
"columns": ["Preferred - Hostname", "GRANITE - IPv4_Address", "..."]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- Uses openpyxl in read-only mode.
|
||||
- Extracts sheet names, first-row column headers per sheet, and unique metric values from the Summary sheet (header at row 4, data from row 5 onward).
|
||||
- On error, returns `{ "error": "..." }` on stdout and exits with non-zero code.
|
||||
|
||||
### 3. Drift Checker (`backend/helpers/driftChecker.js`)
|
||||
|
||||
**Function**: `compareSchemaToDrift(schema, config) => DriftReport`
|
||||
|
||||
**Parameters**:
|
||||
- `schema` — object returned by `extract_xlsx_schema.py`
|
||||
- `config` — object parsed from `compliance_config.json`
|
||||
|
||||
**Returns** (`DriftReport`):
|
||||
```javascript
|
||||
{
|
||||
breaking: [
|
||||
{ severity: 'breaking', message: 'Detail sheet "2.3.4i" is missing core column "Team"', value: 'Team', sheet: '2.3.4i' }
|
||||
],
|
||||
silent_miss: [
|
||||
{ severity: 'silent_miss', message: 'Unknown metric "9.1.2" in Summary — not in metric_categories', value: '9.1.2' }
|
||||
],
|
||||
cosmetic: [
|
||||
{ severity: 'cosmetic', message: 'New column "Extra_Field" in sheet "2.3.4i" — will be captured in extra_json', value: 'Extra_Field', sheet: '2.3.4i' }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Drift rules**:
|
||||
|
||||
| Rule | Severity | Condition |
|
||||
|---|---|---|
|
||||
| Missing core column | `breaking` | A detail sheet (not in `skip_sheets`, present in xlsx) is missing a column from `core_cols` |
|
||||
| Missing detail sheet | `breaking` | A sheet name in `metric_categories` (and not in `skip_sheets`) is absent from the xlsx |
|
||||
| Unknown metric value | `silent_miss` | A metric value in the Summary sheet is not a key in `metric_categories` |
|
||||
| Unknown sheet | `silent_miss` | An xlsx sheet is not in `skip_sheets` and not in `metric_categories` |
|
||||
| New column in detail sheet | `cosmetic` | A detail sheet has columns not in `core_cols` |
|
||||
| Stale metric category | `cosmetic` | A key in `metric_categories` does not appear in the Summary sheet's metric values |
|
||||
|
||||
### 4. Preview Endpoint Changes (`POST /api/compliance/preview`)
|
||||
|
||||
The existing `/preview` handler is modified to:
|
||||
|
||||
1. After receiving the uploaded file, spawn `extract_xlsx_schema.py` to get the xlsx schema.
|
||||
2. Read `compliance_config.json` from disk.
|
||||
3. Call `compareSchemaToDrift(schema, config)` to produce the drift report.
|
||||
4. Proceed with the existing `parseXlsx()` call and `computeDiff()`.
|
||||
5. Include `drift` (the DriftReport object) and optionally `drift_error` (string) in the response.
|
||||
|
||||
If the schema extraction or drift check throws, set `drift: null` and `drift_error: <message>`, then continue with the normal flow.
|
||||
|
||||
**Updated response shape**:
|
||||
```json
|
||||
{
|
||||
"drift": {
|
||||
"breaking": [],
|
||||
"silent_miss": [],
|
||||
"cosmetic": []
|
||||
},
|
||||
"drift_error": null,
|
||||
"diff": { "new_count": 5, "recurring_count": 120, "resolved_count": 3 },
|
||||
"tempFile": "/path/to/temp.json",
|
||||
"filename": "NTS_AEO_2026_03_25.xlsx",
|
||||
"report_date": "2026-03-25",
|
||||
"total_items": 125
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Upload Modal Changes (`ComplianceUploadModal.js`)
|
||||
|
||||
**New phase**: `drift-review` inserted between `uploading` and `preview`.
|
||||
|
||||
**Phase flow**:
|
||||
```
|
||||
idle → uploading → drift-review (if findings) → preview → committing → done
|
||||
→ preview (if no findings)
|
||||
```
|
||||
|
||||
**Drift review UI**:
|
||||
- Findings grouped by severity: breaking first, then silent-miss, then cosmetic.
|
||||
- Each group has a header with severity label and count badge.
|
||||
- Groups with more than 5 findings collapse with a "Show N more" toggle.
|
||||
- Each finding shows the message text and the triggering value.
|
||||
- Breaking findings: red text (`#EF4444`), red left-border accent.
|
||||
- Silent-miss findings: amber text (`#F59E0B`), amber left-border accent.
|
||||
- Cosmetic findings: muted text (`#94A3B8`), subtle left-border accent.
|
||||
- "Cancel" button returns to idle. "Continue to Preview" button advances to diff preview.
|
||||
- "Continue to Preview" is disabled when breaking findings exist, with a message explaining the block.
|
||||
- When `drift` is `null` (drift check failed), skip drift-review and go straight to preview.
|
||||
|
||||
## Data Models
|
||||
|
||||
### DriftFinding
|
||||
|
||||
```javascript
|
||||
{
|
||||
severity: 'breaking' | 'silent_miss' | 'cosmetic',
|
||||
message: string, // Human-readable description
|
||||
value: string, // The specific column/sheet/metric that triggered the finding
|
||||
sheet: string|null // Sheet name context (when applicable)
|
||||
}
|
||||
```
|
||||
|
||||
### DriftReport
|
||||
|
||||
```javascript
|
||||
{
|
||||
breaking: DriftFinding[],
|
||||
silent_miss: DriftFinding[],
|
||||
cosmetic: DriftFinding[]
|
||||
}
|
||||
```
|
||||
|
||||
### ParserConfig
|
||||
|
||||
```javascript
|
||||
{
|
||||
metric_categories: { [metricId: string]: string }, // metric ID → category name
|
||||
core_cols: string[], // column names for main item fields
|
||||
skip_sheets: string[] // sheet names excluded from parsing
|
||||
}
|
||||
```
|
||||
|
||||
### XlsxSchema (output of extract_xlsx_schema.py)
|
||||
|
||||
```javascript
|
||||
{
|
||||
sheets: [
|
||||
{
|
||||
name: string,
|
||||
columns: string[],
|
||||
metric_values?: string[] // only present on Summary sheet
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 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: Breaking drift completeness
|
||||
|
||||
*For any* xlsx schema and parser config, the drift checker SHALL produce a breaking finding for every core column missing from every detail sheet, and for every detail sheet (present in `metric_categories` but not in `skip_sheets`) absent from the xlsx — and no other breaking findings. The set of breaking findings is exactly the union of missing-core-column findings and missing-detail-sheet findings.
|
||||
|
||||
**Validates: Requirements 3.1, 3.2, 3.3**
|
||||
|
||||
### Property 2: Silent-miss drift completeness
|
||||
|
||||
*For any* xlsx schema and parser config, the drift checker SHALL produce a silent-miss finding for every metric value in the Summary sheet not present in `metric_categories`, and for every xlsx sheet not in `skip_sheets` and not in `metric_categories` — and no other silent-miss findings. The set of silent-miss findings is exactly the union of unknown-metric findings and unknown-sheet findings.
|
||||
|
||||
**Validates: Requirements 4.1, 4.2, 4.3**
|
||||
|
||||
### Property 3: Cosmetic drift completeness
|
||||
|
||||
*For any* xlsx schema and parser config, the drift checker SHALL produce a cosmetic finding for every column in a detail sheet not present in `core_cols`, and for every key in `metric_categories` not present in the Summary sheet's metric values — and no other cosmetic findings. The set of cosmetic findings is exactly the union of new-column findings and stale-metric findings.
|
||||
|
||||
**Validates: Requirements 5.1, 5.2, 5.3**
|
||||
|
||||
### Property 4: Drift severity ordering
|
||||
|
||||
*For any* drift report containing a mix of breaking, silent-miss, and cosmetic findings, the grouping function SHALL always return findings ordered by severity: all breaking findings first, then all silent-miss findings, then all cosmetic findings.
|
||||
|
||||
**Validates: Requirements 8.1**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Python Script Failures
|
||||
|
||||
| Failure | Handling |
|
||||
|---|---|
|
||||
| `extract_xlsx_schema.py` exits non-zero | Preview endpoint sets `drift: null`, `drift_error: <stderr message>`, continues with normal parse flow |
|
||||
| `extract_xlsx_schema.py` returns invalid JSON | Same as above — caught in JSON.parse, treated as drift check failure |
|
||||
| `compliance_config.json` missing or invalid (Node.js read) | Preview endpoint returns 500 with message "Configuration file could not be loaded" |
|
||||
| `compliance_config.json` missing or invalid (Python parser read) | Parser exits non-zero, stderr describes the error, preview endpoint returns 500 with parse error |
|
||||
| xlsx file cannot be opened by schema extractor | Schema extractor returns `{ "error": "..." }` on stdout, exits non-zero; drift check skipped gracefully |
|
||||
|
||||
### Frontend Error States
|
||||
|
||||
| Condition | Behavior |
|
||||
|---|---|
|
||||
| `drift` is `null` in preview response | Skip drift-review phase, proceed directly to diff preview |
|
||||
| `drift_error` is present | Optionally display a subtle warning in the diff preview that drift check was skipped |
|
||||
| Network error during upload | Existing error phase handling (unchanged) |
|
||||
|
||||
### Config File Validation
|
||||
|
||||
The Node.js config loader validates that:
|
||||
- The file exists and is readable.
|
||||
- The content parses as valid JSON.
|
||||
- The parsed object contains `metric_categories` (object), `core_cols` (array), and `skip_sheets` (array).
|
||||
|
||||
If any check fails, the loader throws with a descriptive message. The preview handler catches this and returns a 500 response.
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
|
||||
**Drift checker (`driftChecker.js`)**:
|
||||
- Breaking: missing core column produces finding with correct severity, message, value, and sheet.
|
||||
- Breaking: missing detail sheet produces finding.
|
||||
- Silent-miss: unknown metric value produces finding.
|
||||
- Silent-miss: unknown sheet produces finding.
|
||||
- Cosmetic: new column in detail sheet produces finding.
|
||||
- Cosmetic: stale metric category produces finding.
|
||||
- Empty schema (no sheets) produces appropriate findings.
|
||||
- Config with empty metric_categories, core_cols, or skip_sheets.
|
||||
- Schema and config that are perfectly aligned produce zero findings.
|
||||
|
||||
**Config loader**:
|
||||
- Valid config file loads correctly.
|
||||
- Missing file throws descriptive error.
|
||||
- Invalid JSON throws descriptive error.
|
||||
- Config missing required keys throws descriptive error.
|
||||
|
||||
**Frontend drift review component**:
|
||||
- Drift review phase renders when findings exist.
|
||||
- "Continue to Preview" button disabled when breaking findings present.
|
||||
- "Continue to Preview" button enabled when no breaking findings.
|
||||
- Groups collapse at 5+ findings with correct "Show N more" count.
|
||||
- Cancel returns to idle phase.
|
||||
- Skips drift review when drift is null or has no findings.
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based tests use `fast-check` (JavaScript) to verify the four correctness properties defined above. Each test generates random schema and config objects and verifies the drift checker output against the expected set-theoretic result.
|
||||
|
||||
**Configuration**:
|
||||
- Minimum 100 iterations per property test.
|
||||
- Each test tagged with: **Feature: compliance-schema-drift-check, Property {N}: {title}**
|
||||
|
||||
**Generators**:
|
||||
- `arbitraryParserConfig`: generates random `metric_categories` (object with 0–20 string keys mapped to category strings), `core_cols` (array of 0–15 unique column name strings), `skip_sheets` (array of 0–5 unique sheet name strings).
|
||||
- `arbitraryXlsxSchema`: generates random sheets array, each with a name, columns array, and optionally metric_values (for the Summary sheet). Sheet names, column names, and metric values drawn from a shared pool to ensure meaningful overlap with the config.
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- Preview endpoint returns drift report alongside existing diff data.
|
||||
- Preview endpoint returns 200 with breaking drift (does not error).
|
||||
- Preview endpoint gracefully degrades when drift check fails (`drift: null`, `drift_error` present).
|
||||
- Preview endpoint returns 500 when config file is missing.
|
||||
- Python parser reads from `compliance_config.json` and produces same output as before.
|
||||
- Commit endpoint is unchanged and does not reference drift.
|
||||
128
.kiro/specs/compliance-schema-drift-check/requirements.md
Normal file
128
.kiro/specs/compliance-schema-drift-check/requirements.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The compliance upload flow in the STEAM Security Dashboard parses weekly NTS_AEO xlsx reports using a Python parser (`parse_compliance_xlsx.py`) that relies on three hand-maintained configuration dicts: `METRIC_CATEGORIES` (metric ID to category mapping), `CORE_COLS` (column names that become main item fields), and `SKIP_SHEETS` (sheet names excluded from parsing). When the xlsx report structure changes — new metrics appear, sheets are renamed, columns are added or removed — the parser silently miscategorises data, drops fields, or fails outright. Currently, detecting this drift requires a separate manual agent workflow.
|
||||
|
||||
This feature builds schema drift detection directly into the upload flow. During the preview step, the backend extracts the xlsx structure and compares it against the parser configuration. The frontend displays categorised drift findings (breaking, silent-miss, cosmetic) in the upload modal before the user sees the diff preview. Breaking findings block the upload; silent-miss findings warn but allow proceeding; cosmetic findings are informational. The parser configuration dicts are extracted into a shared JSON config file that both the Python parser and the Node.js backend can read, establishing a single source of truth.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Drift_Checker**: The backend module that compares an xlsx file's structural schema against the Parser_Config and produces a categorised Drift_Report.
|
||||
- **Parser_Config**: A shared JSON configuration file (`backend/scripts/compliance_config.json`) containing `metric_categories`, `core_cols`, and `skip_sheets`. This file is the single source of truth read by both the Python parser and the Node.js backend.
|
||||
- **Drift_Report**: A structured object returned by the Drift_Checker containing arrays of findings grouped by severity: `breaking`, `silent_miss`, and `cosmetic`.
|
||||
- **Drift_Finding**: A single entry in the Drift_Report, containing a severity level, a human-readable message, and the specific value that triggered the finding (e.g., a column name, sheet name, or metric ID).
|
||||
- **Breaking_Finding**: A Drift_Finding indicating the xlsx structure will cause parse errors or data loss. Examples: a core column missing from a detail sheet, a previously existing sheet removed or renamed.
|
||||
- **Silent_Miss_Finding**: A Drift_Finding indicating data exists in the xlsx but will be dropped or miscategorised by the parser. Examples: a new metric value in the Summary sheet not present in `metric_categories`, a new sheet not in `skip_sheets` and not in `metric_categories`.
|
||||
- **Cosmetic_Finding**: A Drift_Finding indicating a minor discrepancy worth noting but not blocking. Examples: new columns in known sheets (automatically captured in `extra_json`), stale entries in `metric_categories` that no longer appear in the xlsx.
|
||||
- **Upload_Modal**: The `ComplianceUploadModal.js` component that manages the file upload flow through phases: idle, uploading, drift-review, preview, committing, done, and error.
|
||||
- **Preview_Endpoint**: The `POST /api/compliance/preview` endpoint that parses the uploaded xlsx, runs the drift check, computes the diff, and returns both the Drift_Report and diff counts.
|
||||
- **Schema_Extractor**: The logic (adapted from `dump_xlsx_schema.py`) that reads an xlsx file using openpyxl and extracts sheet names, column headers per sheet, and metric values from the Summary sheet.
|
||||
- **Detail_Sheet**: Any sheet in the xlsx that is not in the `skip_sheets` set and is parsed for non-compliant item rows.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Shared Parser Configuration File
|
||||
|
||||
**User Story:** As a developer, I want the parser configuration dicts extracted into a shared JSON file, so that both the Python parser and the Node.js backend read from a single source of truth.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Parser_Config SHALL be stored at `backend/scripts/compliance_config.json` as a JSON file containing three keys: `metric_categories` (object mapping metric ID strings to category name strings), `core_cols` (array of column name strings), and `skip_sheets` (array of sheet name strings).
|
||||
2. THE Parser_Config SHALL contain the same values currently defined inline in `METRIC_CATEGORIES`, `CORE_COLS`, and `SKIP_SHEETS` in `parse_compliance_xlsx.py`.
|
||||
3. WHEN the Python parser starts, THE Python parser SHALL read `metric_categories`, `core_cols`, and `skip_sheets` from the Parser_Config file instead of using inline dict definitions.
|
||||
4. IF the Parser_Config file is missing or contains invalid JSON, THEN THE Python parser SHALL exit with a non-zero exit code and print a descriptive error message to stderr.
|
||||
5. WHEN the Node.js backend handles a preview request, THE Drift_Checker SHALL read the Parser_Config file to obtain the current metric categories, core columns, and skip sheets.
|
||||
6. IF the Parser_Config file is missing or contains invalid JSON when the Node.js backend reads it, THEN THE Preview_Endpoint SHALL return a 500 error with a message indicating the configuration file could not be loaded.
|
||||
|
||||
### Requirement 2: Schema Extraction from Uploaded xlsx
|
||||
|
||||
**User Story:** As a developer, I want the backend to extract the structural schema from an uploaded xlsx file, so that the drift checker can compare it against the parser configuration.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN an xlsx file is uploaded to the Preview_Endpoint, THE Schema_Extractor SHALL extract the list of sheet names, the column headers from the first row of each sheet, and the unique metric values from the Summary sheet's Metric column (header at row 4, data from row 5 onward).
|
||||
2. THE Schema_Extractor SHALL use openpyxl in read-only mode to extract the xlsx structure, reusing the approach from `dump_xlsx_schema.py`.
|
||||
3. THE Schema_Extractor SHALL run as a Python subprocess invoked by the Node.js backend, returning the extracted schema as JSON on stdout.
|
||||
4. IF the xlsx file cannot be opened or contains no sheets, THEN THE Schema_Extractor SHALL return a JSON error object on stdout and exit with a non-zero exit code.
|
||||
|
||||
### Requirement 3: Drift Detection — Breaking Findings
|
||||
|
||||
**User Story:** As a compliance analyst, I want the system to detect structural changes that will cause parse failures or data loss, so that I do not upload a report that produces corrupt data.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a Detail_Sheet is missing one or more columns listed in `core_cols` of the Parser_Config, THE Drift_Checker SHALL produce a Breaking_Finding for each missing column, identifying the sheet name and column name.
|
||||
2. WHEN a sheet name that previously existed as a Detail_Sheet (present in `metric_categories` but not in `skip_sheets`) is absent from the uploaded xlsx, THE Drift_Checker SHALL produce a Breaking_Finding identifying the missing sheet name.
|
||||
3. THE Drift_Checker SHALL classify all Breaking_Findings with severity `"breaking"`.
|
||||
|
||||
### Requirement 4: Drift Detection — Silent-Miss Findings
|
||||
|
||||
**User Story:** As a compliance analyst, I want the system to detect when new data in the xlsx will be silently miscategorised or dropped, so that I can update the parser configuration before proceeding.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Summary sheet contains metric values not present as keys in `metric_categories` of the Parser_Config, THE Drift_Checker SHALL produce a Silent_Miss_Finding for each unknown metric value.
|
||||
2. WHEN the xlsx contains sheets that are not in `skip_sheets` and whose names do not appear as keys in `metric_categories`, THE Drift_Checker SHALL produce a Silent_Miss_Finding for each unknown sheet, indicating it will be parsed with an 'Other' category.
|
||||
3. THE Drift_Checker SHALL classify all Silent_Miss_Findings with severity `"silent_miss"`.
|
||||
|
||||
### Requirement 5: Drift Detection — Cosmetic Findings
|
||||
|
||||
**User Story:** As a compliance analyst, I want to see informational notes about minor schema differences, so that I have full visibility into how the xlsx structure has evolved.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a Detail_Sheet contains columns not present in `core_cols` of the Parser_Config, THE Drift_Checker SHALL produce a Cosmetic_Finding for each new column, noting that the column data will be captured in `extra_json`.
|
||||
2. WHEN `metric_categories` in the Parser_Config contains metric IDs that do not appear in the Summary sheet's metric values, THE Drift_Checker SHALL produce a Cosmetic_Finding for each stale metric ID.
|
||||
3. THE Drift_Checker SHALL classify all Cosmetic_Findings with severity `"cosmetic"`.
|
||||
|
||||
### Requirement 6: Preview Endpoint Drift Integration
|
||||
|
||||
**User Story:** As a developer, I want the preview endpoint to include the drift report in its response, so that the frontend can display drift findings before showing the diff preview.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Preview_Endpoint processes an uploaded xlsx file, THE Preview_Endpoint SHALL run the Schema_Extractor and Drift_Checker before running the existing parser and diff computation.
|
||||
2. THE Preview_Endpoint SHALL include a `drift` field in the JSON response containing the Drift_Report with `breaking`, `silent_miss`, and `cosmetic` arrays.
|
||||
3. WHEN the drift check produces Breaking_Findings, THE Preview_Endpoint SHALL still return a 200 response with the Drift_Report, allowing the frontend to display the findings and block the commit.
|
||||
4. IF the Schema_Extractor or Drift_Checker fails unexpectedly, THEN THE Preview_Endpoint SHALL proceed with the normal parse and diff flow, returning a `drift` field set to `null` and a `drift_error` field with a descriptive message, so that the upload flow is not blocked by drift check failures.
|
||||
|
||||
### Requirement 7: Upload Modal Drift Review Phase
|
||||
|
||||
**User Story:** As a compliance analyst, I want to see drift findings in the upload modal after file upload and before the diff preview, so that I can assess schema compatibility before deciding to proceed.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Preview_Endpoint returns a Drift_Report with one or more findings, THE Upload_Modal SHALL display a drift review phase between the uploading spinner and the diff preview.
|
||||
2. THE Upload_Modal SHALL display Breaking_Findings with red text and a red left-border accent, using the dashboard danger color (`#EF4444`).
|
||||
3. THE Upload_Modal SHALL display Silent_Miss_Findings with amber text and an amber left-border accent, using the dashboard warning color (`#F59E0B`).
|
||||
4. THE Upload_Modal SHALL display Cosmetic_Findings with muted text and a subtle left-border accent, using the dashboard muted text color (`#94A3B8`).
|
||||
5. WHEN the Drift_Report contains one or more Breaking_Findings, THE Upload_Modal SHALL disable the "Continue to Preview" button and display a message indicating the upload is blocked until the parser configuration is updated.
|
||||
6. WHEN the Drift_Report contains Silent_Miss_Findings but no Breaking_Findings, THE Upload_Modal SHALL enable the "Continue to Preview" button and display a warning message advising the user to review the findings.
|
||||
7. WHEN the Drift_Report contains only Cosmetic_Findings, THE Upload_Modal SHALL enable the "Continue to Preview" button without a warning message.
|
||||
8. WHEN the Drift_Report contains no findings, THE Upload_Modal SHALL skip the drift review phase and proceed directly to the diff preview.
|
||||
|
||||
### Requirement 8: Drift Review UI Layout and Interaction
|
||||
|
||||
**User Story:** As a compliance analyst, I want the drift findings to be clearly organised and scannable, so that I can quickly understand what changed in the xlsx structure.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Upload_Modal SHALL group drift findings by severity, displaying Breaking_Findings first, then Silent_Miss_Findings, then Cosmetic_Findings.
|
||||
2. THE Upload_Modal SHALL display a count badge next to each severity group header showing the number of findings in that group.
|
||||
3. WHEN a severity group contains more than five findings, THE Upload_Modal SHALL collapse the group to show the first five findings with an expandable "Show N more" toggle.
|
||||
4. EACH Drift_Finding displayed in the Upload_Modal SHALL include the finding message and the specific value (column name, sheet name, or metric ID) that triggered the finding.
|
||||
5. THE Upload_Modal SHALL display a "Cancel" button that returns the modal to the idle phase, and a "Continue to Preview" button (when enabled) that advances to the diff preview phase.
|
||||
6. THE Upload_Modal drift review phase SHALL follow the dashboard's dark theme and monospace typography conventions defined in `DESIGN_SYSTEM.md`.
|
||||
|
||||
### Requirement 9: Existing Upload Flow Preservation
|
||||
|
||||
**User Story:** As a compliance analyst, I want the existing upload flow to remain intact, so that the drift check is an additive enhancement and does not disrupt the current preview-then-commit workflow.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the user clicks "Continue to Preview" from the drift review phase, THE Upload_Modal SHALL display the same diff preview (recurring, new, resolved counts) and "Confirm Upload" button as the current implementation.
|
||||
2. THE Preview_Endpoint SHALL continue to return `diff`, `tempFile`, `filename`, `report_date`, and `total_items` fields in the response alongside the new `drift` field.
|
||||
3. THE commit flow (`POST /api/compliance/commit`) SHALL remain unchanged and SHALL NOT perform any drift checking.
|
||||
4. WHEN the `drift` field in the preview response is `null` (drift check failed or was skipped), THE Upload_Modal SHALL proceed directly to the diff preview phase as if no drift was detected.
|
||||
|
||||
154
.kiro/specs/compliance-schema-drift-check/tasks.md
Normal file
154
.kiro/specs/compliance-schema-drift-check/tasks.md
Normal file
@@ -0,0 +1,154 @@
|
||||
# Implementation Plan: Compliance Schema Drift Check
|
||||
|
||||
## Overview
|
||||
|
||||
This plan implements schema drift detection in the compliance upload flow. The work proceeds in layers: first extract the shared config file, then build the Python schema extractor, then the Node.js drift checker, then wire it into the preview endpoint, and finally update the upload modal with the drift-review phase. Property-based tests validate the drift checker's correctness properties using fast-check.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Create shared parser configuration file and update Python parser
|
||||
- [x] 1.1 Create `backend/scripts/compliance_config.json` with `metric_categories`, `core_cols`, and `skip_sheets`
|
||||
- Extract the exact values from the inline dicts `METRIC_CATEGORIES`, `CORE_COLS`, and `SKIP_SHEETS` in `parse_compliance_xlsx.py`
|
||||
- `metric_categories` is an object mapping metric ID strings to category strings
|
||||
- `core_cols` is an array of column name strings
|
||||
- `skip_sheets` is an array of sheet name strings
|
||||
- _Requirements: 1.1, 1.2_
|
||||
|
||||
- [x] 1.2 Modify `backend/scripts/parse_compliance_xlsx.py` to read config from JSON file
|
||||
- Remove the inline `METRIC_CATEGORIES`, `CORE_COLS`, and `SKIP_SHEETS` definitions
|
||||
- Load them from `compliance_config.json` (resolved relative to the script's directory)
|
||||
- If the config file is missing or contains invalid JSON, print a descriptive error to stderr and exit with non-zero code
|
||||
- Ensure `CORE_COLS` is converted to a set after loading from the JSON array
|
||||
- _Requirements: 1.3, 1.4_
|
||||
|
||||
- [ ]* 1.3 Write unit tests for Python parser config loading
|
||||
- Test that parser loads config correctly and produces same output as before
|
||||
- Test that missing config file causes non-zero exit with descriptive stderr
|
||||
- Test that invalid JSON in config file causes non-zero exit with descriptive stderr
|
||||
- _Requirements: 1.3, 1.4_
|
||||
|
||||
- [x] 2. Create Python schema extractor script
|
||||
- [x] 2.1 Create `backend/scripts/extract_xlsx_schema.py`
|
||||
- Accept file path as CLI argument
|
||||
- Use openpyxl in read-only mode to extract: sheet names, first-row column headers per sheet, and unique metric values from the Summary sheet (header at row 4, data from row 5 onward)
|
||||
- Output JSON to stdout with shape `{ "sheets": [{ "name", "columns", "metric_values?" }] }`
|
||||
- On error, return `{ "error": "..." }` on stdout and exit with non-zero code
|
||||
- Reuse the approach from `dump_xlsx_schema.py` for Summary sheet metric extraction
|
||||
- _Requirements: 2.1, 2.2, 2.3, 2.4_
|
||||
|
||||
- [ ]* 2.2 Write unit tests for schema extractor
|
||||
- Test that valid xlsx produces correct schema JSON
|
||||
- Test that missing file returns error JSON and non-zero exit
|
||||
- Test that file with no sheets returns error JSON
|
||||
- _Requirements: 2.1, 2.4_
|
||||
|
||||
- [x] 3. Implement Node.js drift checker module
|
||||
- [x] 3.1 Create `backend/helpers/driftChecker.js` with `compareSchemaToDrift(schema, config)` function
|
||||
- Implement breaking rules: missing core column in detail sheets, missing detail sheet (in `metric_categories` but not `skip_sheets` and absent from xlsx)
|
||||
- Implement silent-miss rules: unknown metric value in Summary not in `metric_categories`, unknown sheet not in `skip_sheets` and not in `metric_categories`
|
||||
- Implement cosmetic rules: new column in detail sheet not in `core_cols`, stale metric in `metric_categories` not in Summary metric values
|
||||
- Each finding has shape `{ severity, message, value, sheet }` (sheet is null when not applicable)
|
||||
- Return `{ breaking: [], silent_miss: [], cosmetic: [] }`
|
||||
- Export `compareSchemaToDrift` and a `loadConfig(configPath)` function that reads and validates `compliance_config.json`
|
||||
- Config loader validates: file exists, parses as JSON, contains `metric_categories` (object), `core_cols` (array), `skip_sheets` (array)
|
||||
- _Requirements: 3.1, 3.2, 3.3, 4.1, 4.2, 4.3, 5.1, 5.2, 5.3, 1.5, 1.6_
|
||||
|
||||
- [ ] 3.2 Write property test: Breaking drift completeness (Property 1)
|
||||
- **Property 1: Breaking drift completeness**
|
||||
- For any generated schema and config, the set of breaking findings equals exactly the union of missing-core-column findings and missing-detail-sheet findings — no more, no fewer
|
||||
- Use fast-check with arbitrary generators for schema and config objects
|
||||
- Minimum 100 iterations
|
||||
- **Validates: Requirements 3.1, 3.2, 3.3**
|
||||
|
||||
- [ ]* 3.3 Write property test: Silent-miss drift completeness (Property 2)
|
||||
- **Property 2: Silent-miss drift completeness**
|
||||
- For any generated schema and config, the set of silent-miss findings equals exactly the union of unknown-metric findings and unknown-sheet findings
|
||||
- Use fast-check with arbitrary generators for schema and config objects
|
||||
- Minimum 100 iterations
|
||||
- **Validates: Requirements 4.1, 4.2, 4.3**
|
||||
|
||||
- [ ]* 3.4 Write property test: Cosmetic drift completeness (Property 3)
|
||||
- **Property 3: Cosmetic drift completeness**
|
||||
- For any generated schema and config, the set of cosmetic findings equals exactly the union of new-column findings and stale-metric findings
|
||||
- Use fast-check with arbitrary generators for schema and config objects
|
||||
- Minimum 100 iterations
|
||||
- **Validates: Requirements 5.1, 5.2, 5.3**
|
||||
|
||||
- [ ]* 3.5 Write property test: Drift severity ordering (Property 4)
|
||||
- **Property 4: Drift severity ordering**
|
||||
- For any drift report, the grouped output always returns all breaking findings first, then all silent-miss, then all cosmetic
|
||||
- Use fast-check to generate mixed drift reports and verify ordering
|
||||
- Minimum 100 iterations
|
||||
- **Validates: Requirements 8.1**
|
||||
|
||||
- [ ]* 3.6 Write unit tests for drift checker and config loader
|
||||
- Test each drift rule individually with hand-crafted schema/config pairs
|
||||
- Test config loader with valid file, missing file, invalid JSON, and missing required keys
|
||||
- Test that perfectly aligned schema and config produce zero findings
|
||||
- Test edge cases: empty metric_categories, empty core_cols, empty skip_sheets
|
||||
- _Requirements: 3.1, 3.2, 3.3, 4.1, 4.2, 4.3, 5.1, 5.2, 5.3, 1.5, 1.6_
|
||||
|
||||
- [x] 4. Checkpoint — Verify backend modules
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 5. Integrate drift check into preview endpoint
|
||||
- [x] 5.1 Modify `backend/routes/compliance.js` to add drift checking in `POST /preview`
|
||||
- After receiving the uploaded file, spawn `extract_xlsx_schema.py` as a Python subprocess to get the xlsx schema
|
||||
- Read `compliance_config.json` using the `loadConfig()` function from `driftChecker.js`
|
||||
- Call `compareSchemaToDrift(schema, config)` to produce the drift report
|
||||
- Proceed with the existing `parseXlsx()` call and `computeDiff()`
|
||||
- Include `drift` (DriftReport object) and `drift_error` (string or null) in the response
|
||||
- If schema extraction or drift check throws, set `drift: null` and `drift_error: <message>`, then continue with normal flow
|
||||
- If config file is missing or invalid, return 500 with descriptive message
|
||||
- Preserve all existing response fields: `diff`, `tempFile`, `filename`, `report_date`, `total_items`
|
||||
- _Requirements: 6.1, 6.2, 6.3, 6.4, 9.2_
|
||||
|
||||
- [ ]* 5.2 Write integration tests for preview endpoint drift behavior
|
||||
- Test that preview response includes `drift` field alongside existing `diff` data
|
||||
- Test that breaking drift still returns 200 (not an error)
|
||||
- Test graceful degradation when drift check fails (`drift: null`, `drift_error` present)
|
||||
- Test 500 response when config file is missing
|
||||
- Test that commit endpoint is unchanged and does not reference drift
|
||||
- _Requirements: 6.1, 6.2, 6.3, 6.4, 9.3_
|
||||
|
||||
- [x] 6. Update upload modal with drift-review phase
|
||||
- [x] 6.1 Modify `frontend/src/components/pages/ComplianceUploadModal.js` to add drift-review phase
|
||||
- Add `drift-review` phase between `uploading` and `preview` in the phase flow
|
||||
- After upload response, check if `drift` is non-null and has findings — if so, enter `drift-review`; otherwise skip to `preview`
|
||||
- When `drift` is `null` (drift check failed), skip drift-review and go straight to preview
|
||||
- Display findings grouped by severity: breaking first, then silent-miss, then cosmetic
|
||||
- Each severity group has a header with label and count badge
|
||||
- Groups with more than 5 findings collapse with a "Show N more" toggle
|
||||
- Each finding shows the message and the triggering value
|
||||
- Breaking findings: red text (`#EF4444`), red left-border accent
|
||||
- Silent-miss findings: amber text (`#F59E0B`), amber left-border accent
|
||||
- Cosmetic findings: muted text (`#94A3B8`), subtle left-border accent
|
||||
- "Cancel" button returns to idle phase; "Continue to Preview" button advances to diff preview
|
||||
- "Continue to Preview" disabled when breaking findings exist, with a message explaining the block
|
||||
- When no breaking findings but silent-miss exist, show warning message and enable "Continue to Preview"
|
||||
- When only cosmetic findings, enable "Continue to Preview" without warning
|
||||
- Follow dashboard dark theme and monospace typography from `DESIGN_SYSTEM.md`
|
||||
- Preserve existing diff preview, commit flow, done, and error phases unchanged
|
||||
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 9.1, 9.4_
|
||||
|
||||
- [ ]* 6.2 Write unit tests for upload modal drift-review phase
|
||||
- Test drift-review phase renders when findings exist
|
||||
- Test "Continue to Preview" button disabled when breaking findings present
|
||||
- Test "Continue to Preview" button enabled when no breaking findings
|
||||
- Test groups collapse at 5+ findings with correct "Show N more" count
|
||||
- Test cancel returns to idle phase
|
||||
- Test skips drift-review when drift is null or has no findings
|
||||
- _Requirements: 7.1, 7.5, 7.6, 7.7, 7.8, 8.3_
|
||||
|
||||
- [x] 7. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests (3.2–3.5) validate the four correctness properties from the design using fast-check
|
||||
- Unit tests validate specific examples and edge cases
|
||||
- The Python parser modification (1.2) must produce identical output to the current inline-dict version — this is a refactor, not a behavior change
|
||||
- The commit endpoint (`POST /api/compliance/commit`) is intentionally unchanged
|
||||
1
.kiro/specs/cve-tooltip-hover/.config.kiro
Normal file
1
.kiro/specs/cve-tooltip-hover/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "b8855eb4-3949-426e-86ac-36fe069a6bb1", "workflowType": "requirements-first", "specType": "feature"}
|
||||
229
.kiro/specs/cve-tooltip-hover/design.md
Normal file
229
.kiro/specs/cve-tooltip-hover/design.md
Normal file
@@ -0,0 +1,229 @@
|
||||
# Design Document: CVE Tooltip Hover
|
||||
|
||||
## Overview
|
||||
|
||||
This feature adds a hover tooltip to CVE badges in the Reporting Page findings table. When a user pauses their cursor over a CVE identifier badge, the system fetches a brief description and severity from the backend and displays it in a styled floating tooltip. Responses are cached in-memory to avoid redundant API calls, and a 300ms hover delay prevents tooltip flicker during fast mouse movement.
|
||||
|
||||
The implementation spans two layers:
|
||||
1. A new lightweight backend endpoint (`/api/cves/:cveId/tooltip`) that queries the existing `cves` SQLite table and returns a trimmed response.
|
||||
2. A frontend `CveTooltip` component rendered via a React portal, with an in-memory cache (React ref), hover delay timer, and viewport-aware positioning.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant CVEBadge as CVE Badge (ReportingPage)
|
||||
participant Tooltip as CveTooltip Component
|
||||
participant Cache as Tooltip Cache (useRef)
|
||||
participant API as /api/cves/:cveId/tooltip
|
||||
participant DB as SQLite (cves table)
|
||||
|
||||
User->>CVEBadge: mouseenter
|
||||
CVEBadge->>Tooltip: start 300ms delay timer
|
||||
Note over Tooltip: If mouseout before 300ms, cancel
|
||||
|
||||
alt Cache hit
|
||||
Tooltip->>Cache: lookup(cveId)
|
||||
Cache-->>Tooltip: cached data
|
||||
Tooltip->>User: show tooltip (or skip if exists:false)
|
||||
else Cache miss
|
||||
Tooltip->>API: GET /api/cves/:cveId/tooltip
|
||||
API->>DB: SELECT cve_id, description, severity FROM cves WHERE cve_id = ?
|
||||
DB-->>API: row or null
|
||||
API-->>Tooltip: { exists, cve_id, description, severity }
|
||||
Tooltip->>Cache: store response
|
||||
Tooltip->>User: show tooltip (or skip if exists:false)
|
||||
end
|
||||
|
||||
User->>CVEBadge: mouseleave
|
||||
CVEBadge->>Tooltip: hide + clear timer
|
||||
```
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
1. **Inline endpoint in server.js** — The tooltip endpoint is a single GET route on the existing `/api/cves` path prefix. It follows the pattern of other simple CVE endpoints already defined inline in `server.js` (e.g., `/api/cves/check/:cveId`, `/api/cves/:cveId/vendors`). No separate route module needed.
|
||||
|
||||
2. **React portal for tooltip rendering** — The tooltip is rendered via `ReactDOM.createPortal` to `document.body`, avoiding overflow/clipping issues from the table's scroll container. The ReportingPage already imports `ReactDOM` for other portal usage.
|
||||
|
||||
3. **useRef for cache instead of useState** — The cache is a plain `Map` stored in a `useRef`. This avoids re-renders when cache entries are added and persists across renders without triggering updates. The cache is cleared when the findings data is re-synced.
|
||||
|
||||
4. **Single shared tooltip instance** — Only one tooltip is visible at a time. The parent component tracks which CVE badge is hovered and passes the active CVE ID + badge position to the tooltip component.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend
|
||||
|
||||
#### `GET /api/cves/:cveId/tooltip`
|
||||
|
||||
Added inline in `server.js` alongside existing CVE endpoints.
|
||||
|
||||
- **Auth**: `requireAuth(db)` — session cookie required
|
||||
- **Params**: `:cveId` — validated against `CVE_ID_PATTERN` (`/^CVE-\d{4}-\d{4,}$/`)
|
||||
- **Query**: `SELECT cve_id, description, severity FROM cves WHERE cve_id = ? LIMIT 1`
|
||||
- **Response (found)**:
|
||||
```json
|
||||
{
|
||||
"exists": true,
|
||||
"cve_id": "CVE-2024-12345",
|
||||
"description": "A vulnerability in...",
|
||||
"severity": "High"
|
||||
}
|
||||
```
|
||||
- **Response (not found)**:
|
||||
```json
|
||||
{ "exists": false }
|
||||
```
|
||||
- **Description truncation**: If `description.length > 300`, return `description.substring(0, 300) + '…'`
|
||||
|
||||
### Frontend
|
||||
|
||||
#### `CveTooltip` Component (new file: `frontend/src/components/CveTooltip.js`)
|
||||
|
||||
A portal-rendered tooltip that receives positioning data and CVE info.
|
||||
|
||||
**Props:**
|
||||
| Prop | Type | Description |
|
||||
|------|------|-------------|
|
||||
| `cveId` | `string \| null` | The CVE ID to display. `null` hides the tooltip. |
|
||||
| `anchorRect` | `DOMRect \| null` | Bounding rect of the hovered badge for positioning. |
|
||||
| `cache` | `React.MutableRefObject<Map>` | Shared cache ref from parent. |
|
||||
|
||||
**Internal state:**
|
||||
- `data` — fetched tooltip payload (`{ exists, cve_id, description, severity }` or `null`)
|
||||
- `loading` — boolean, true while fetch is in-flight
|
||||
|
||||
**Behavior:**
|
||||
1. When `cveId` changes to a non-null value, check `cache.current` for the CVE ID.
|
||||
2. If cached and `exists: false`, render nothing.
|
||||
3. If cached and `exists: true`, display immediately.
|
||||
4. If not cached, set `loading = true`, fetch from API, store result in cache, set `loading = false`.
|
||||
5. Position the tooltip above the badge by default. If the tooltip would overflow the top of the viewport, position it below instead.
|
||||
6. Render via `ReactDOM.createPortal` to `document.body`.
|
||||
|
||||
#### ReportingPage Integration
|
||||
|
||||
Modifications to the existing `renderCell` function for the `'cves'` case:
|
||||
|
||||
- Add `onMouseEnter` / `onMouseLeave` handlers to each CVE badge `<span>`.
|
||||
- `onMouseEnter`: Start a 300ms `setTimeout`. On fire, set active CVE ID + badge `getBoundingClientRect()` into state.
|
||||
- `onMouseLeave`: Clear the timeout. Set active CVE ID to `null`.
|
||||
- Render a single `<CveTooltip>` instance at the bottom of the component, passing the active CVE ID, anchor rect, and cache ref.
|
||||
- On data sync (when findings are refreshed), call `cache.current.clear()`.
|
||||
|
||||
## Data Models
|
||||
|
||||
### Existing: `cves` Table (SQLite)
|
||||
|
||||
The tooltip endpoint queries the existing table. No schema changes required.
|
||||
|
||||
```sql
|
||||
CREATE TABLE cves (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
cve_id TEXT NOT NULL,
|
||||
vendor TEXT NOT NULL,
|
||||
severity TEXT CHECK(severity IN ('Critical', 'High', 'Medium', 'Low')),
|
||||
description TEXT,
|
||||
published_date TEXT,
|
||||
status TEXT DEFAULT 'Open',
|
||||
created_by INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(cve_id, vendor)
|
||||
);
|
||||
```
|
||||
|
||||
The query uses `LIMIT 1` since a CVE may have multiple vendor rows — the description and severity from any row suffice for the tooltip blurb.
|
||||
|
||||
### Frontend Cache Structure
|
||||
|
||||
```javascript
|
||||
// cache.current is a Map<string, object>
|
||||
// Key: CVE ID string (e.g. "CVE-2024-12345")
|
||||
// Value: API response object
|
||||
// { exists: false }
|
||||
// OR
|
||||
// { exists: true, cve_id: string, description: string, severity: string }
|
||||
```
|
||||
|
||||
|
||||
## 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: Tooltip endpoint returns correct data for existing CVEs
|
||||
|
||||
*For any* CVE record inserted into the `cves` table with a valid `cve_id`, `description`, and `severity`, a GET request to `/api/cves/:cveId/tooltip` SHALL return `{ exists: true }` with the matching `cve_id` and `severity`, and a `description` that is either the original (if ≤ 300 chars) or truncated to 300 chars + ellipsis.
|
||||
|
||||
**Validates: Requirements 1.1, 1.3, 1.5**
|
||||
|
||||
### Property 2: Description truncation preserves content and enforces length
|
||||
|
||||
*For any* string of arbitrary length, the truncation function SHALL return the original string unchanged if its length is ≤ 300, or return exactly the first 300 characters followed by "…" if its length exceeds 300. In both cases, the output starts with the same characters as the input.
|
||||
|
||||
**Validates: Requirements 1.5**
|
||||
|
||||
### Property 3: Tooltip positioning flips based on available viewport space
|
||||
|
||||
*For any* anchor rectangle position and viewport height, the tooltip SHALL be positioned above the anchor when `anchorRect.top` provides sufficient space for the tooltip height, and below the anchor otherwise. The tooltip SHALL never overflow the top or bottom of the viewport.
|
||||
|
||||
**Validates: Requirements 3.1, 3.2**
|
||||
|
||||
### Property 4: Cache round-trip — fetch then cache-hit avoids network call
|
||||
|
||||
*For any* CVE ID, after the tooltip system fetches data from the API and stores it in the cache, a subsequent tooltip request for the same CVE ID SHALL return the identical cached data object without making an additional network request.
|
||||
|
||||
**Validates: Requirements 4.1, 4.2**
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Layer | Behavior |
|
||||
|----------|-------|----------|
|
||||
| Invalid CVE ID format in URL param | Backend | Return `400 { error: 'Invalid CVE ID format.' }` |
|
||||
| Database query error | Backend | Log error, return `500 { error: 'Internal server error.' }` |
|
||||
| No session cookie / expired session | Backend | `requireAuth` middleware returns `401` |
|
||||
| Network error during fetch | Frontend | Catch error, hide tooltip (do not cache failures), log to console |
|
||||
| Fetch timeout / slow response | Frontend | Show loading state; if user moves away, cancel via AbortController |
|
||||
| Component unmounts during fetch | Frontend | AbortController signal aborts in-flight request, no state update |
|
||||
|
||||
**Key principle**: Transient errors (network failures, timeouts) are NOT cached. Only successful API responses (both `exists: true` and `exists: false`) are stored in the cache. This ensures a retry on next hover for failed requests.
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (Example-Based)
|
||||
|
||||
| Test | Validates |
|
||||
|------|-----------|
|
||||
| Endpoint returns `{ exists: false }` for unknown CVE ID | Req 1.2 |
|
||||
| Endpoint returns 401 without session cookie | Req 1.4 |
|
||||
| Endpoint returns 400 for malformed CVE ID (e.g. "not-a-cve") | Req 1.1 (error path) |
|
||||
| Tooltip appears after 300ms hover delay | Req 5.1 |
|
||||
| Tooltip cancelled if mouseout before 300ms | Req 5.2 |
|
||||
| Tooltip hidden on mouseleave | Req 2.2 |
|
||||
| Loading indicator shown while fetching | Req 2.5 |
|
||||
| No tooltip shown when API returns `exists: false` | Req 2.6 |
|
||||
| Severity badge uses correct color per level | Req 2.4 |
|
||||
| Tooltip has max-width of 320px | Req 3.3 |
|
||||
| Tooltip includes directional arrow element | Req 3.5 |
|
||||
| Cache cleared on data sync/refresh | Req 4.4 |
|
||||
| Cached `exists: false` suppresses tooltip and API call | Req 4.3 |
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based tests use **fast-check** (JavaScript PBT library, already compatible with the Jest/react-scripts test runner).
|
||||
|
||||
Each property test runs a minimum of **100 iterations**.
|
||||
|
||||
| Property | Tag | Focus |
|
||||
|----------|-----|-------|
|
||||
| Property 1 | `Feature: cve-tooltip-hover, Property 1: Tooltip endpoint returns correct data for existing CVEs` | Generate random CVE records (varying description lengths 0–1000, all 4 severity levels), insert into test DB, call endpoint, verify response shape and truncation |
|
||||
| Property 2 | `Feature: cve-tooltip-hover, Property 2: Description truncation preserves content and enforces length` | Generate random strings of length 0–2000, apply truncation function, verify length invariant and prefix preservation |
|
||||
| Property 3 | `Feature: cve-tooltip-hover, Property 3: Tooltip positioning flips based on available viewport space` | Generate random anchorRect.top (0–2000), tooltip height (50–200), viewport height (400–1200), verify position is within viewport bounds |
|
||||
| Property 4 | `Feature: cve-tooltip-hover, Property 4: Cache round-trip` | Generate random CVE IDs and response payloads, store in cache Map, verify subsequent lookups return identical objects and no fetch is triggered |
|
||||
|
||||
### Test Configuration
|
||||
|
||||
- Test runner: `react-scripts test` (Jest) — already configured in the project
|
||||
- PBT library: `fast-check` — install via `npm install --save-dev fast-check` in the `frontend/` directory
|
||||
- Backend endpoint tests: Use supertest or direct handler invocation with a test SQLite DB
|
||||
- Frontend component tests: React Testing Library with mocked fetch
|
||||
73
.kiro/specs/cve-tooltip-hover/requirements.md
Normal file
73
.kiro/specs/cve-tooltip-hover/requirements.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
Add a hover tooltip to CVE badges in the Reporting Page (vuln triage view). When a user hovers over a CVE identifier badge in the findings table, the system checks whether that CVE exists in the local SQLite database. If it does, a small tooltip appears showing a brief description/blurb about that CVE. CVEs not present in the database show no tooltip.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Reporting_Page**: The vulnerability triage view at `frontend/src/components/pages/ReportingPage.js` that displays Ivanti host findings in a sortable, filterable table.
|
||||
- **CVE_Badge**: The styled `<span>` element in the CVEs column of the findings table that displays a CVE identifier (e.g. CVE-2024-12345) with a purple pill/box appearance.
|
||||
- **CVE_Tooltip**: A small floating box that appears on mouse hover over a CVE_Badge, displaying a text blurb about the CVE.
|
||||
- **CVE_Database**: The `cves` table in the SQLite database (`backend/cve_database.db`) that stores CVE records including descriptions, severity, and vendor information.
|
||||
- **Tooltip_Cache**: An in-memory lookup (React state or ref) that stores previously fetched CVE descriptions to avoid redundant API calls during the same session.
|
||||
- **API_Server**: The Express backend at `backend/server.js` that serves CVE data via `/api` endpoints.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: CVE Tooltip Data Endpoint
|
||||
|
||||
**User Story:** As a frontend component, I want to fetch a brief description for a given CVE ID, so that the tooltip can display relevant information without loading unnecessary data.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a GET request is made to `/api/cves/:cveId/tooltip`, THE API_Server SHALL return a JSON object containing the `cve_id`, `description`, and `severity` fields for the matching CVE record.
|
||||
2. WHEN a GET request is made to `/api/cves/:cveId/tooltip` for a CVE ID that does not exist in the CVE_Database, THE API_Server SHALL return a JSON object with `{ exists: false }` and HTTP status 200.
|
||||
3. WHEN a GET request is made to `/api/cves/:cveId/tooltip` for a CVE ID that exists in the CVE_Database, THE API_Server SHALL return a JSON object with `{ exists: true, cve_id, description, severity }` and HTTP status 200.
|
||||
4. THE API_Server SHALL require a valid session cookie for the `/api/cves/:cveId/tooltip` endpoint.
|
||||
5. WHEN the `description` field exceeds 300 characters, THE API_Server SHALL truncate the description to 300 characters and append an ellipsis ("…").
|
||||
|
||||
### Requirement 2: Tooltip Display on CVE Badge Hover
|
||||
|
||||
**User Story:** As a security analyst triaging findings, I want to see a brief description of a CVE when I hover over its badge in the findings table, so that I can quickly understand the vulnerability without leaving the page.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the user hovers the mouse cursor over a CVE_Badge in the Reporting_Page findings table, THE Reporting_Page SHALL display a CVE_Tooltip near the hovered badge.
|
||||
2. WHEN the user moves the mouse cursor away from the CVE_Badge, THE Reporting_Page SHALL hide the CVE_Tooltip.
|
||||
3. THE CVE_Tooltip SHALL display the CVE description text returned by the API_Server.
|
||||
4. THE CVE_Tooltip SHALL display the severity level of the CVE using the existing severity color scheme (Critical: red, High: amber, Medium: sky blue, Low: emerald).
|
||||
5. WHILE the CVE data is being fetched from the API_Server, THE CVE_Tooltip SHALL display a loading indicator.
|
||||
6. WHEN the API_Server returns `exists: false` for a CVE ID, THE Reporting_Page SHALL not display a CVE_Tooltip for that badge.
|
||||
|
||||
### Requirement 3: Tooltip Positioning and Styling
|
||||
|
||||
**User Story:** As a security analyst, I want the CVE tooltip to be readable and not obstruct other table content, so that I can continue triaging while viewing CVE details.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE CVE_Tooltip SHALL appear above the hovered CVE_Badge by default.
|
||||
2. WHEN there is insufficient viewport space above the CVE_Badge, THE CVE_Tooltip SHALL appear below the badge instead.
|
||||
3. THE CVE_Tooltip SHALL have a maximum width of 320 pixels.
|
||||
4. THE CVE_Tooltip SHALL use the design system dark theme styling: dark background gradient, accent border, monospace font for the CVE ID, and standard font for the description text.
|
||||
5. THE CVE_Tooltip SHALL include a small directional arrow pointing toward the CVE_Badge.
|
||||
|
||||
### Requirement 4: Tooltip Response Caching
|
||||
|
||||
**User Story:** As a security analyst scrolling through many findings, I want CVE tooltip data to load instantly for CVEs I have already hovered over, so that repeated hovers do not cause redundant network requests.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Reporting_Page fetches tooltip data for a CVE ID, THE Tooltip_Cache SHALL store the response for that CVE ID.
|
||||
2. WHEN the user hovers over a CVE_Badge for a CVE ID that exists in the Tooltip_Cache, THE Reporting_Page SHALL display the cached data without making an API call.
|
||||
3. WHEN the user hovers over a CVE_Badge for a CVE ID where the Tooltip_Cache stores `exists: false`, THE Reporting_Page SHALL not display a tooltip and SHALL not make an API call.
|
||||
4. WHEN the Reporting_Page performs a full data sync (refresh), THE Tooltip_Cache SHALL be cleared.
|
||||
|
||||
### Requirement 5: Hover Delay
|
||||
|
||||
**User Story:** As a security analyst, I want the tooltip to only appear after a brief pause on a CVE badge, so that tooltips do not flash distractingly when I move the mouse across the table quickly.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the user hovers over a CVE_Badge, THE Reporting_Page SHALL wait 300 milliseconds before initiating the tooltip display sequence.
|
||||
2. IF the user moves the mouse away from the CVE_Badge before 300 milliseconds have elapsed, THEN THE Reporting_Page SHALL cancel the tooltip display and not make an API call.
|
||||
107
.kiro/specs/cve-tooltip-hover/tasks.md
Normal file
107
.kiro/specs/cve-tooltip-hover/tasks.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# Implementation Plan: CVE Tooltip Hover
|
||||
|
||||
## Overview
|
||||
|
||||
Implement a hover tooltip for CVE badges in the Reporting Page findings table. The feature spans a backend endpoint (`GET /api/cves/:cveId/tooltip`) and a frontend `CveTooltip` portal component with in-memory caching and 300ms hover delay. Tasks are ordered backend-first, then frontend component, then integration, with property tests alongside each layer.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Add backend tooltip endpoint
|
||||
- [x] 1.1 Add `GET /api/cves/:cveId/tooltip` route inline in `backend/server.js`
|
||||
- Place it alongside existing CVE endpoints (after `/api/cves/:cveId/vendors`)
|
||||
- Validate `:cveId` against existing `CVE_ID_PATTERN`; return 400 for invalid format
|
||||
- Query: `SELECT cve_id, description, severity FROM cves WHERE cve_id = ? LIMIT 1`
|
||||
- If no row: return `{ exists: false }` with status 200
|
||||
- If row found: truncate `description` to 300 chars + "…" if needed, return `{ exists: true, cve_id, description, severity }`
|
||||
- Protect with `requireAuth(db)` middleware
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5_
|
||||
|
||||
- [ ]* 1.2 Write property test for tooltip endpoint data correctness
|
||||
- **Property 1: Tooltip endpoint returns correct data for existing CVEs**
|
||||
- Install `fast-check` as dev dependency in `frontend/` (shared test runner)
|
||||
- Generate random CVE records with description lengths 0–1000 and all 4 severity levels
|
||||
- Verify response shape, truncation at 300 chars, and prefix preservation
|
||||
- **Validates: Requirements 1.1, 1.3, 1.5**
|
||||
|
||||
- [ ]* 1.3 Write property test for description truncation
|
||||
- **Property 2: Description truncation preserves content and enforces length**
|
||||
- Extract truncation logic into a testable pure function
|
||||
- Generate random strings of length 0–2000, verify length invariant and prefix match
|
||||
- **Validates: Requirements 1.5**
|
||||
|
||||
- [x] 2. Checkpoint — Verify backend endpoint
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 3. Create CveTooltip frontend component
|
||||
- [x] 3.1 Create `frontend/src/components/CveTooltip.js`
|
||||
- Portal-rendered component using `ReactDOM.createPortal` to `document.body`
|
||||
- Props: `cveId` (string|null), `anchorRect` (DOMRect|null), `cache` (useRef Map)
|
||||
- Internal state: `data`, `loading`
|
||||
- On `cveId` change: check cache → if miss, fetch from `/api/cves/:cveId/tooltip` with AbortController
|
||||
- If cached `exists: false` or fetch returns `exists: false`, render nothing
|
||||
- Show loading spinner (Loader from lucide-react) while fetching
|
||||
- Display: CVE ID in monospace, severity badge with design system colors, description text
|
||||
- Max-width 320px, dark theme gradient background, accent border, directional arrow
|
||||
- Position above anchor by default; flip below if insufficient viewport space above
|
||||
- Do not cache transient errors (network failures)
|
||||
- _Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 3.1, 3.2, 3.3, 3.4, 3.5_
|
||||
|
||||
- [ ]* 3.2 Write property test for tooltip positioning logic
|
||||
- **Property 3: Tooltip positioning flips based on available viewport space**
|
||||
- Extract positioning calculation into a pure function
|
||||
- Generate random anchorRect.top (0–2000), tooltip height (50–200), viewport height (400–1200)
|
||||
- Verify tooltip never overflows top or bottom of viewport
|
||||
- **Validates: Requirements 3.1, 3.2**
|
||||
|
||||
- [ ]* 3.3 Write unit tests for CveTooltip component
|
||||
- Test loading state renders spinner
|
||||
- Test `exists: false` renders nothing
|
||||
- Test severity badge uses correct color per level
|
||||
- Test max-width constraint
|
||||
- Test directional arrow element is present
|
||||
- _Requirements: 2.4, 2.5, 2.6, 3.3, 3.5_
|
||||
|
||||
- [x] 4. Checkpoint — Verify CveTooltip component
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 5. Integrate tooltip into ReportingPage
|
||||
- [x] 5.1 Add hover state and cache ref to ReportingPage
|
||||
- Add state: `tooltipCveId` (string|null), `tooltipAnchorRect` (DOMRect|null)
|
||||
- Add `useRef(new Map())` for tooltip cache
|
||||
- Add `useRef` for hover delay timer
|
||||
- Clear cache when findings data is re-synced (inside existing sync callback)
|
||||
- _Requirements: 4.1, 4.4, 5.1_
|
||||
|
||||
- [x] 5.2 Add mouseenter/mouseleave handlers to CVE badge spans
|
||||
- In the `renderCell` function for the `'cves'` column case, wrap each CVE badge `<span>` with `onMouseEnter` and `onMouseLeave`
|
||||
- `onMouseEnter`: start 300ms setTimeout; on fire, set `tooltipCveId` and `tooltipAnchorRect` from `getBoundingClientRect()`
|
||||
- `onMouseLeave`: clear timeout, set `tooltipCveId` to null
|
||||
- _Requirements: 2.1, 2.2, 5.1, 5.2_
|
||||
|
||||
- [x] 5.3 Render CveTooltip instance in ReportingPage
|
||||
- Add single `<CveTooltip>` at the bottom of the ReportingPage return, passing `tooltipCveId`, `tooltipAnchorRect`, and cache ref
|
||||
- _Requirements: 2.1, 4.2, 4.3_
|
||||
|
||||
- [ ]* 5.4 Write property test for cache round-trip behavior
|
||||
- **Property 4: Cache round-trip — fetch then cache-hit avoids network call**
|
||||
- Generate random CVE IDs and response payloads, store in Map, verify lookups return identical objects
|
||||
- **Validates: Requirements 4.1, 4.2**
|
||||
|
||||
- [ ]* 5.5 Write unit tests for hover delay and cache integration
|
||||
- Test tooltip appears after 300ms delay (use fake timers)
|
||||
- Test tooltip cancelled if mouseout before 300ms
|
||||
- Test cached `exists: false` suppresses tooltip and API call
|
||||
- Test cache cleared on data sync/refresh
|
||||
- _Requirements: 4.3, 4.4, 5.1, 5.2_
|
||||
|
||||
- [x] 6. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests validate universal correctness properties from the design document
|
||||
- Unit tests validate specific examples and edge cases
|
||||
- The project uses plain JavaScript (no TypeScript), fast-check for PBT, and react-scripts test (Jest)
|
||||
293
.kiro/specs/finding-archive-tracking/design.md
Normal file
293
.kiro/specs/finding-archive-tracking/design.md
Normal file
@@ -0,0 +1,293 @@
|
||||
# Design Document: Finding Archive Tracking
|
||||
|
||||
## Overview
|
||||
|
||||
The Finding Archive Tracking system adds a detection layer to the existing Ivanti sync pipeline that identifies findings which disappear from sync results due to severity score drift. It tracks these findings through a four-state lifecycle (ACTIVE → ARCHIVED → RETURNED → CLOSED) with full transition history stored in two new SQLite tables. Three new API endpoints expose archive data, and an Archive Summary Bar UI component provides at-a-glance state counts on the Ivanti dashboard.
|
||||
|
||||
The system integrates directly into the existing `syncFindings()` function in `ivantiFindings.js`, comparing current sync results against the previous set to detect disappearances and reappearances. This approach requires no additional API calls to Ivanti and leverages the already-cached findings data.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Ivanti Sync Pipeline
|
||||
A[syncFindings] --> B[Fetch all pages from Ivanti API]
|
||||
B --> C[Store findings in ivanti_findings_cache]
|
||||
C --> D[Archive Detection]
|
||||
end
|
||||
|
||||
subgraph Archive Detection
|
||||
D --> E{Compare previous vs current finding IDs}
|
||||
E -->|Missing from current| F[Create/Update Archive Record → ARCHIVED]
|
||||
E -->|Returned in current| G[Update Archive Record → RETURNED]
|
||||
E -->|Closed in Ivanti| H[Update Archive Record → CLOSED]
|
||||
F --> I[Insert Transition History]
|
||||
G --> I
|
||||
H --> I
|
||||
end
|
||||
|
||||
subgraph Archive API
|
||||
J[GET /api/ivanti/archive] --> K[(ivanti_finding_archives)]
|
||||
L[GET /api/ivanti/archive/:findingId/history] --> M[(ivanti_archive_transitions)]
|
||||
N[GET /api/ivanti/archive/stats] --> K
|
||||
end
|
||||
|
||||
subgraph Frontend
|
||||
O[Archive Summary Bar] -->|fetch stats| N
|
||||
O -->|click state| J
|
||||
P[Transition History Panel] -->|fetch history| L
|
||||
end
|
||||
```
|
||||
|
||||
### Integration Points
|
||||
|
||||
1. **Sync Pipeline Hook**: Archive detection runs after `syncFindings()` successfully stores new findings in the cache. It reads the previous findings from the cache before the update, then compares against the new set.
|
||||
2. **Route Registration**: The archive router is mounted at `/api/ivanti/archive` in `server.js`, following the same factory pattern as existing Ivanti routes.
|
||||
3. **Frontend Integration**: The Archive Summary Bar is rendered on the existing Ivanti findings page, above the findings table.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### 1. Archive Detection Module (`detectArchiveChanges`)
|
||||
|
||||
Located within `backend/routes/ivantiFindings.js`, this async function runs after a successful sync.
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* Compare previous and current finding sets to detect archive state changes.
|
||||
* @param {sqlite3.Database} db - SQLite database instance
|
||||
* @param {Array} previousFindings - Findings from before the sync update
|
||||
* @param {Array} currentFindings - Findings from the latest sync
|
||||
*/
|
||||
async function detectArchiveChanges(db, previousFindings, currentFindings) {
|
||||
// 1. Build ID sets from previous and current
|
||||
// 2. Disappeared = in previous but not in current → ARCHIVED
|
||||
// 3. Returned = in current AND has existing ARCHIVED record → RETURNED
|
||||
// 4. For each state change, upsert archive record + insert transition
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Closed Finding Detection (`detectClosedFindings`)
|
||||
|
||||
Runs during the closed count sync to detect findings that transitioned to CLOSED in Ivanti.
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* Check archived findings against Ivanti closed findings to detect remediation.
|
||||
* @param {sqlite3.Database} db - SQLite database instance
|
||||
* @param {Array} closedFindingIds - IDs of findings confirmed closed in Ivanti
|
||||
*/
|
||||
async function detectClosedFindings(db, closedFindingIds) {
|
||||
// For each archived/returned finding, if it appears in closed set → CLOSED
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Archive API Router (`createIvantiArchiveRouter`)
|
||||
|
||||
Located at `backend/routes/ivantiArchive.js`, follows the existing factory pattern.
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* @param {sqlite3.Database} db - SQLite database instance
|
||||
* @param {Function} requireAuth - Auth middleware factory
|
||||
* @returns {express.Router}
|
||||
*/
|
||||
function createIvantiArchiveRouter(db, requireAuth) {
|
||||
const router = express.Router();
|
||||
router.use(requireAuth(db));
|
||||
|
||||
// GET / - List archive records, optional ?state= filter
|
||||
// GET /stats - Summary counts by state
|
||||
// GET /:findingId/history - Transition history for a finding
|
||||
|
||||
return router;
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Archive Summary Bar Component (`ArchiveSummaryBar`)
|
||||
|
||||
Located at `frontend/src/components/pages/ArchiveSummaryBar.js`.
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* Displays four stat cards for ACTIVE, ARCHIVED, RETURNED, CLOSED counts.
|
||||
* @param {Object} props
|
||||
* @param {Function} props.onStateClick - Callback when a state card is clicked
|
||||
* @param {string|null} props.activeFilter - Currently selected state filter
|
||||
*/
|
||||
function ArchiveSummaryBar({ onStateClick, activeFilter }) { ... }
|
||||
```
|
||||
|
||||
### API Endpoint Specifications
|
||||
|
||||
| Endpoint | Method | Auth | Query Params | Response |
|
||||
|----------|--------|------|-------------|----------|
|
||||
| `/api/ivanti/archive` | GET | Required | `state` (optional: ACTIVE, ARCHIVED, RETURNED, CLOSED) | `{ archives: [...], total: N }` |
|
||||
| `/api/ivanti/archive/stats` | GET | Required | None | `{ ARCHIVED: N, RETURNED: N, CLOSED: N, total: N }` |
|
||||
| `/api/ivanti/archive/:findingId/history` | GET | Required | None | `{ finding_id: "...", transitions: [...] }` |
|
||||
|
||||
## Data Models
|
||||
|
||||
### `ivanti_finding_archives` Table
|
||||
|
||||
| Column | Type | Constraints | Description |
|
||||
|--------|------|-------------|-------------|
|
||||
| `id` | INTEGER | PRIMARY KEY AUTOINCREMENT | Row ID |
|
||||
| `finding_id` | TEXT | NOT NULL UNIQUE | Ivanti finding identifier |
|
||||
| `finding_title` | TEXT | NOT NULL DEFAULT '' | Finding title at time of archival |
|
||||
| `host_name` | TEXT | NOT NULL DEFAULT '' | Host name at time of archival |
|
||||
| `ip_address` | TEXT | NOT NULL DEFAULT '' | IP address at time of archival |
|
||||
| `current_state` | TEXT | NOT NULL CHECK(IN ('ARCHIVED','RETURNED','CLOSED')) | Current lifecycle state |
|
||||
| `last_severity` | REAL | NOT NULL DEFAULT 0 | Last known severity score |
|
||||
| `first_archived_at` | DATETIME | NOT NULL DEFAULT CURRENT_TIMESTAMP | When first archived |
|
||||
| `last_transition_at` | DATETIME | NOT NULL DEFAULT CURRENT_TIMESTAMP | When last state change occurred |
|
||||
| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Row creation time |
|
||||
|
||||
**Indexes:**
|
||||
- `idx_archive_finding_id` on `finding_id`
|
||||
- `idx_archive_current_state` on `current_state`
|
||||
|
||||
### `ivanti_archive_transitions` Table
|
||||
|
||||
| Column | Type | Constraints | Description |
|
||||
|--------|------|-------------|-------------|
|
||||
| `id` | INTEGER | PRIMARY KEY AUTOINCREMENT | Row ID |
|
||||
| `archive_id` | INTEGER | NOT NULL, FK → ivanti_finding_archives(id) | Parent archive record |
|
||||
| `from_state` | TEXT | NOT NULL | Previous state (or 'NONE' for initial) |
|
||||
| `to_state` | TEXT | NOT NULL | New state |
|
||||
| `severity_at_transition` | REAL | NOT NULL DEFAULT 0 | Severity score at time of transition |
|
||||
| `reason` | TEXT | NOT NULL DEFAULT '' | Human-readable reason |
|
||||
| `transitioned_at` | DATETIME | NOT NULL DEFAULT CURRENT_TIMESTAMP | When transition occurred |
|
||||
|
||||
**Indexes:**
|
||||
- `idx_transition_archive_id` on `archive_id`
|
||||
|
||||
### State Transition Diagram
|
||||
|
||||
Archive records are only created when a finding first disappears from sync results. Findings that remain present in sync results do not get archive records — they are simply "active" in the findings cache. The three database states are ARCHIVED, RETURNED, and CLOSED.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> ARCHIVED : Finding disappears from sync (score drift)
|
||||
ARCHIVED --> RETURNED : Reappeared in sync
|
||||
ARCHIVED --> CLOSED : Confirmed remediated in Ivanti
|
||||
RETURNED --> ARCHIVED : Disappeared again
|
||||
RETURNED --> CLOSED : Confirmed remediated in Ivanti
|
||||
```
|
||||
|
||||
### Valid State Transitions
|
||||
|
||||
| From State | To State | Reason |
|
||||
|-----------|----------|--------|
|
||||
| NONE → | ARCHIVED | `severity_score_drift` (first disappearance) |
|
||||
| ARCHIVED → | RETURNED | `reappeared_in_sync` |
|
||||
| ARCHIVED → | CLOSED | `remediated_in_ivanti` |
|
||||
| RETURNED → | ARCHIVED | `severity_score_drift` |
|
||||
| RETURNED → | CLOSED | `remediated_in_ivanti` |
|
||||
|
||||
|
||||
## 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: Disappeared findings are archived with complete metadata
|
||||
|
||||
*For any* set of previous findings and current findings, every finding present in the previous set but absent from the current set should have an Archive_Record with state ARCHIVED, and that record should contain the correct finding_id, finding_title, host_name, ip_address, and last_severity matching the original finding's data.
|
||||
|
||||
**Validates: Requirements 1.1, 1.2, 2.2**
|
||||
|
||||
### Property 2: Returned findings transition from ARCHIVED to RETURNED
|
||||
|
||||
*For any* finding that has an Archive_Record with state ARCHIVED, if that finding reappears in the current sync results, the Archive_Record state should be updated to RETURNED and the last_severity should reflect the finding's current severity score.
|
||||
|
||||
**Validates: Requirements 1.3**
|
||||
|
||||
### Property 3: Re-disappeared findings transition from RETURNED to ARCHIVED
|
||||
|
||||
*For any* finding that has an Archive_Record with state RETURNED, if that finding disappears from the current sync results, the Archive_Record state should be updated back to ARCHIVED.
|
||||
|
||||
**Validates: Requirements 1.4**
|
||||
|
||||
### Property 4: Every state transition produces a history record with all required fields
|
||||
|
||||
*For any* state transition on an Archive_Record, a Transition_History row should be inserted containing a valid archive_id, the correct from_state and to_state, a severity_at_transition value, a non-empty reason string, and a transitioned_at timestamp.
|
||||
|
||||
**Validates: Requirements 2.1**
|
||||
|
||||
### Property 5: Closed findings transition to CLOSED state
|
||||
|
||||
*For any* finding that has an Archive_Record with state ARCHIVED or RETURNED, if that finding appears in the Ivanti closed findings set, the Archive_Record state should be updated to CLOSED and the transition reason should be "remediated_in_ivanti".
|
||||
|
||||
**Validates: Requirements 2.3**
|
||||
|
||||
### Property 6: State filter returns only matching records
|
||||
|
||||
*For any* set of Archive_Records with various states, querying the archive list endpoint with a state filter should return only records whose current_state matches the filter, and the count should equal the number of records in that state.
|
||||
|
||||
**Validates: Requirements 4.1**
|
||||
|
||||
### Property 7: Transition history is ordered by timestamp descending
|
||||
|
||||
*For any* finding with multiple Transition_History entries, the history endpoint should return entries ordered by transitioned_at descending, such that each entry's timestamp is greater than or equal to the next entry's timestamp.
|
||||
|
||||
**Validates: Requirements 4.2**
|
||||
|
||||
### Property 8: Stats counts match actual record distribution
|
||||
|
||||
*For any* set of Archive_Records, the stats endpoint should return counts where the sum of all state counts equals the total number of Archive_Records, and each individual state count matches the actual number of records in that state.
|
||||
|
||||
**Validates: Requirements 4.3**
|
||||
|
||||
### Property 9: Migration idempotency
|
||||
|
||||
*For any* number of consecutive executions of the migration script, the resulting database schema should be identical and no errors should occur on subsequent runs.
|
||||
|
||||
**Validates: Requirements 6.2**
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| Sync fails (API error, timeout) | Archive detection is skipped entirely for that cycle. No archive records are created or modified. The sync error is logged as usual. |
|
||||
| Database error during archive upsert | Log the error, continue processing remaining findings. Do not abort the entire archive detection pass. |
|
||||
| Database error during transition insert | Log the error. The archive record state may have been updated but the transition history may be incomplete. This is acceptable as the current state is the source of truth. |
|
||||
| Invalid state transition attempted | The detection logic only performs valid transitions per the state diagram. Invalid transitions (e.g., CLOSED → ARCHIVED) are not possible by design since closed findings are excluded from the sync pipeline. |
|
||||
| Missing finding metadata | Use empty string defaults for finding_title, host_name, ip_address if the finding object lacks these fields. Severity defaults to 0. |
|
||||
| Archive API query with invalid state parameter | Return a 400 status code with message "Invalid state parameter. Valid values: ACTIVE, ARCHIVED, RETURNED, CLOSED". Explicit errors surface frontend bugs faster than silent fallbacks. |
|
||||
| History query for non-existent finding | Return 200 with empty transitions array (not 404), per requirement 4.5. |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
|
||||
Unit tests cover specific examples and edge cases:
|
||||
|
||||
- Migration script creates both tables and all indexes (example, Req 3.1–3.4)
|
||||
- Archive detection skips when sync errors occur (example, Req 1.5)
|
||||
- Unauthenticated requests return 401 (example, Req 4.4)
|
||||
- History endpoint returns empty array for unknown finding (edge case, Req 4.5)
|
||||
- Archive Summary Bar renders four stat cards (example, Req 5.1)
|
||||
- Archive Summary Bar fetches stats on mount (example, Req 5.2)
|
||||
- Clicking a state card triggers filter callback (example, Req 5.3)
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based tests use a PBT library (e.g., `fast-check`) to verify universal properties across generated inputs. Each test runs a minimum of 100 iterations.
|
||||
|
||||
| Property | Test Description | Tag |
|
||||
|----------|-----------------|-----|
|
||||
| Property 1 | Generate random previous/current finding sets, run detection, verify all disappeared findings have correct ARCHIVED records | **Feature: finding-archive-tracking, Property 1: Disappeared findings are archived with complete metadata** |
|
||||
| Property 2 | Generate archived findings, add some back to current set, verify RETURNED state | **Feature: finding-archive-tracking, Property 2: Returned findings transition from ARCHIVED to RETURNED** |
|
||||
| Property 3 | Generate returned findings, remove some from current set, verify ARCHIVED state | **Feature: finding-archive-tracking, Property 3: Re-disappeared findings transition from RETURNED to ARCHIVED** |
|
||||
| Property 4 | Generate random state transitions, verify each produces a complete history row | **Feature: finding-archive-tracking, Property 4: Every state transition produces a history record** |
|
||||
| Property 5 | Generate archived/returned findings, mark some as closed, verify CLOSED state and reason | **Feature: finding-archive-tracking, Property 5: Closed findings transition to CLOSED state** |
|
||||
| Property 6 | Generate archive records with random states, query with filter, verify only matching records returned | **Feature: finding-archive-tracking, Property 6: State filter returns only matching records** |
|
||||
| Property 7 | Generate multiple transitions for a finding, query history, verify descending order | **Feature: finding-archive-tracking, Property 7: Transition history is ordered by timestamp descending** |
|
||||
| Property 8 | Generate archive records with random states, query stats, verify counts match | **Feature: finding-archive-tracking, Property 8: Stats counts match actual record distribution** |
|
||||
| Property 9 | Run migration N times, verify no errors and schema is consistent | **Feature: finding-archive-tracking, Property 9: Migration idempotency** |
|
||||
|
||||
### Testing Tools
|
||||
|
||||
- **Test runner**: Jest (via react-scripts for frontend, direct for backend)
|
||||
- **Property-based testing**: `fast-check` library
|
||||
- **Database**: In-memory SQLite (`:memory:`) for isolated test runs
|
||||
- **HTTP testing**: `supertest` for API endpoint tests
|
||||
86
.kiro/specs/finding-archive-tracking/requirements.md
Normal file
86
.kiro/specs/finding-archive-tracking/requirements.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The Finding Archive Tracking system extends the Ivanti sync pipeline in the STEAM Security Dashboard to detect and track findings that disappear from sync results due to severity score drift (not remediation). Findings follow a four-state lifecycle (ACTIVE → ARCHIVED → RETURNED → CLOSED) with full transition history, enabling the security team to maintain visibility into findings that fall below the severity threshold and may reappear.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Sync_Pipeline**: The existing Ivanti/RiskSense host finding sync process that fetches open findings matching BU and severity filters on a daily schedule.
|
||||
- **Finding**: A single host-level vulnerability record identified by a unique `finding_id` from Ivanti/RiskSense.
|
||||
- **Archive_Record**: A database row in the `ivanti_finding_archives` table tracking a finding's current lifecycle state and metadata.
|
||||
- **Transition_History**: A database row in the `ivanti_archive_transitions` table recording a single state change event with timestamps, severity scores, and reason.
|
||||
- **Archive_Detector**: The logic within the sync pipeline that compares previous sync results against current results to identify disappeared and returned findings.
|
||||
- **Archive_Summary_Bar**: A React UI component displaying counts for each lifecycle state (ACTIVE, ARCHIVED, RETURNED, CLOSED) with click-through navigation.
|
||||
- **Archive_API**: The set of three Express route endpoints serving archived finding data, transition history, and summary statistics.
|
||||
- **Lifecycle_State**: One of three database states an archive record can occupy: ARCHIVED (disappeared from sync results due to score drift), RETURNED (reappeared after being archived), CLOSED (remediated in Ivanti). Findings that remain present in sync results have no archive record.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Archive Detection During Sync
|
||||
|
||||
**User Story:** As a security analyst, I want the system to automatically detect findings that disappear from sync results, so that I can track findings lost due to severity score drift rather than actual remediation.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Sync_Pipeline completes a sync, THE Archive_Detector SHALL compare the current sync result finding IDs against the previous sync result finding IDs to identify findings that are no longer present.
|
||||
2. WHEN a finding is present in the previous sync but absent from the current sync, THE Archive_Detector SHALL create an Archive_Record with state ARCHIVED, recording the finding metadata, last known severity score, and a timestamp.
|
||||
3. WHEN a finding already has an Archive_Record with state ARCHIVED and the finding reappears in the current sync results, THE Archive_Detector SHALL update the Archive_Record state to RETURNED and record the new severity score.
|
||||
4. WHEN a finding has an Archive_Record with state RETURNED and the finding disappears again from sync results, THE Archive_Detector SHALL update the Archive_Record state to ARCHIVED and record the severity score at time of disappearance.
|
||||
5. IF the Sync_Pipeline encounters a sync error, THEN THE Archive_Detector SHALL skip archive detection for that sync cycle to avoid false positives from incomplete data.
|
||||
|
||||
### Requirement 2: Lifecycle State Transitions
|
||||
|
||||
**User Story:** As a security analyst, I want every state change to be recorded with context, so that I can audit the full history of a finding's lifecycle.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN an Archive_Record changes state, THE Sync_Pipeline SHALL insert a Transition_History row containing the previous state, new state, timestamp, severity score at time of transition, and a reason string.
|
||||
2. THE Archive_Record SHALL store the finding_id, finding_title, host_name, ip_address, current state, last known severity score, initial archive timestamp, and last transition timestamp.
|
||||
3. WHEN a finding is confirmed as remediated (closed) in Ivanti, THE Sync_Pipeline SHALL update the Archive_Record state to CLOSED and record a Transition_History entry with reason "remediated_in_ivanti".
|
||||
4. THE Transition_History SHALL store the archive_record_id, from_state, to_state, transition timestamp, severity_at_transition, and reason.
|
||||
|
||||
### Requirement 3: Database Schema
|
||||
|
||||
**User Story:** As a developer, I want the archive data stored in two normalized SQLite tables, so that the data model supports efficient queries and maintains referential integrity.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Sync_Pipeline SHALL create an `ivanti_finding_archives` table with columns for id, finding_id (unique), finding_title, host_name, ip_address, current_state, last_severity, first_archived_at, last_transition_at, and created_at.
|
||||
2. THE Sync_Pipeline SHALL create an `ivanti_archive_transitions` table with columns for id, archive_id (foreign key to ivanti_finding_archives), from_state, to_state, severity_at_transition, reason, and transitioned_at.
|
||||
3. THE Sync_Pipeline SHALL create indexes on ivanti_finding_archives(finding_id) and ivanti_finding_archives(current_state) for query performance.
|
||||
4. THE Sync_Pipeline SHALL create an index on ivanti_archive_transitions(archive_id) for efficient history lookups.
|
||||
|
||||
### Requirement 4: Archive API Endpoints
|
||||
|
||||
**User Story:** As a frontend developer, I want REST API endpoints to query archived findings, transition history, and summary statistics, so that I can build the archive tracking UI.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a GET request is made to `/api/ivanti/archive`, THE Archive_API SHALL return a list of all Archive_Records with optional filtering by current_state query parameter.
|
||||
2. WHEN a GET request is made to `/api/ivanti/archive/:findingId/history`, THE Archive_API SHALL return the Transition_History entries for the specified finding ordered by transitioned_at descending.
|
||||
3. WHEN a GET request is made to `/api/ivanti/archive/stats`, THE Archive_API SHALL return an object containing the count of Archive_Records in each Lifecycle_State (ACTIVE, ARCHIVED, RETURNED, CLOSED).
|
||||
4. WHEN an unauthenticated request is made to any Archive_API endpoint, THE Archive_API SHALL return a 401 status code.
|
||||
5. WHEN a GET request is made to `/api/ivanti/archive/:findingId/history` with a finding_id that has no Archive_Record, THE Archive_API SHALL return an empty transitions array with a 200 status code.
|
||||
|
||||
### Requirement 5: Archive Summary Bar UI
|
||||
|
||||
**User Story:** As a security analyst, I want a visual summary bar on the Ivanti dashboard showing counts for each archive state, so that I can quickly assess the archive landscape and navigate to details.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Archive_Summary_Bar SHALL display four stat cards showing the count of findings in each Lifecycle_State: ACTIVE, ARCHIVED, RETURNED, and CLOSED.
|
||||
2. WHEN the Archive_Summary_Bar loads, THE Archive_Summary_Bar SHALL fetch data from the `/api/ivanti/archive/stats` endpoint.
|
||||
3. WHEN a user clicks a state card in the Archive_Summary_Bar, THE Archive_Summary_Bar SHALL filter the displayed archive list to show only findings in that state.
|
||||
4. THE Archive_Summary_Bar SHALL use the existing design system colors: sky blue (#0EA5E9) for ACTIVE, amber (#F59E0B) for ARCHIVED, emerald (#10B981) for RETURNED, and red (#EF4444) for CLOSED.
|
||||
5. THE Archive_Summary_Bar SHALL use Lucide icons and monospace typography consistent with the existing dashboard design system.
|
||||
|
||||
### Requirement 6: Migration Script
|
||||
|
||||
**User Story:** As a developer, I want a standalone migration script to create the archive tables, so that the schema can be applied to existing deployments following the established migration pattern.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE migration script SHALL be located at `backend/migrations/add_finding_archive_tables.js` and follow the existing migration pattern of opening the database, running DDL statements in `db.serialize()`, and closing the connection.
|
||||
2. THE migration script SHALL use `CREATE TABLE IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS` to be idempotent.
|
||||
3. WHEN the migration script is executed, THE migration script SHALL log progress messages for each table and index created.
|
||||
134
.kiro/specs/finding-archive-tracking/tasks.md
Normal file
134
.kiro/specs/finding-archive-tracking/tasks.md
Normal file
@@ -0,0 +1,134 @@
|
||||
# Implementation Plan: Finding Archive Tracking
|
||||
|
||||
## Overview
|
||||
|
||||
Implement the Finding Archive Tracking system by creating the database migration, archive detection logic within the existing sync pipeline, three API endpoints via a new route module, and an Archive Summary Bar UI component. Each task builds incrementally — schema first, then detection logic, then API, then frontend.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Create database migration and archive tables
|
||||
- [x] 1.1 Create `backend/migrations/add_finding_archive_tables.js` migration script
|
||||
- Create `ivanti_finding_archives` table with columns: id, finding_id (UNIQUE), finding_title, host_name, ip_address, current_state (CHECK constraint for ACTIVE/ARCHIVED/RETURNED/CLOSED), last_severity, first_archived_at, last_transition_at, created_at
|
||||
- Create `ivanti_archive_transitions` table with columns: id, archive_id (FK), from_state, to_state, severity_at_transition, reason, transitioned_at
|
||||
- Create indexes: idx_archive_finding_id, idx_archive_current_state, idx_transition_archive_id
|
||||
- Use `CREATE TABLE IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS` for idempotency
|
||||
- Follow existing migration pattern: open db, `db.serialize()`, log progress, close db
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.4, 6.1, 6.2, 6.3_
|
||||
|
||||
- [ ]* 1.2 Write property test for migration idempotency
|
||||
- **Property 9: Migration idempotency**
|
||||
- Run migration logic multiple times against in-memory SQLite, verify no errors and schema is consistent
|
||||
- **Validates: Requirements 6.2**
|
||||
|
||||
- [x] 2. Implement archive detection logic in sync pipeline
|
||||
- [x] 2.1 Add `initArchiveTables(db)` function to `backend/routes/ivantiFindings.js`
|
||||
- Create both archive tables inline (same pattern as existing `initTables`) so they exist on startup
|
||||
- Call from `createIvantiFindingsRouter` during init alongside existing `initTables`
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.4_
|
||||
|
||||
- [x] 2.2 Implement `detectArchiveChanges(db, previousFindings, currentFindings)` function
|
||||
- Build ID sets from previous and current findings
|
||||
- For disappeared findings (in previous, not in current): upsert archive record with state ARCHIVED, insert transition history
|
||||
- For returned findings (in current, has ARCHIVED record): update to RETURNED, insert transition history
|
||||
- For re-disappeared findings (has RETURNED record, not in current): update to ARCHIVED, insert transition history
|
||||
- Use `db.run` with callbacks wrapped in promises (matching existing `dbRun` helper pattern)
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 2.1, 2.2_
|
||||
|
||||
- [x] 2.3 Implement `detectClosedFindings(db, closedFindingIds)` function
|
||||
- Query archive records with state ARCHIVED or RETURNED
|
||||
- For any that appear in the closed findings set, update to CLOSED with reason "remediated_in_ivanti"
|
||||
- Insert transition history for each state change
|
||||
- _Requirements: 2.3_
|
||||
|
||||
- [x] 2.4 Integrate archive detection into `syncFindings()` flow
|
||||
- Before updating the cache, read the current findings from `ivanti_findings_cache` as `previousFindings`
|
||||
- After successful cache update, call `detectArchiveChanges(db, previousFindings, currentFindings)`
|
||||
- Skip archive detection if sync encountered an error (requirement 1.5)
|
||||
- Call `detectClosedFindings` during `syncClosedCount` with closed finding IDs
|
||||
- _Requirements: 1.1, 1.5, 2.3_
|
||||
|
||||
- [ ]* 2.5 Write property test for archive detection — disappeared findings
|
||||
- **Property 1: Disappeared findings are archived with complete metadata**
|
||||
- Generate random previous/current finding sets using fast-check, run detectArchiveChanges against in-memory SQLite, verify all disappeared findings have ARCHIVED records with correct metadata
|
||||
- **Validates: Requirements 1.1, 1.2, 2.2**
|
||||
|
||||
- [ ]* 2.6 Write property test for archive detection — returned findings
|
||||
- **Property 2: Returned findings transition from ARCHIVED to RETURNED**
|
||||
- Generate archived findings, add some back to current set, verify RETURNED state and updated severity
|
||||
- **Validates: Requirements 1.3**
|
||||
|
||||
- [ ]* 2.7 Write property test for archive detection — re-disappeared findings
|
||||
- **Property 3: Re-disappeared findings transition from RETURNED to ARCHIVED**
|
||||
- Generate returned findings, remove some from current set, verify ARCHIVED state
|
||||
- **Validates: Requirements 1.4**
|
||||
|
||||
- [ ]* 2.8 Write property test for transition history completeness
|
||||
- **Property 4: Every state transition produces a history record with all required fields**
|
||||
- Generate random state transitions, verify each produces a complete history row with archive_id, from_state, to_state, severity_at_transition, reason, transitioned_at
|
||||
- **Validates: Requirements 2.1**
|
||||
|
||||
- [ ]* 2.9 Write property test for closed finding detection
|
||||
- **Property 5: Closed findings transition to CLOSED state**
|
||||
- Generate archived/returned findings, mark some as closed, verify CLOSED state and reason "remediated_in_ivanti"
|
||||
- **Validates: Requirements 2.3**
|
||||
|
||||
- [x] 3. Checkpoint — Verify archive detection logic
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 4. Implement Archive API endpoints
|
||||
- [x] 4.1 Create `backend/routes/ivantiArchive.js` route module
|
||||
- Export factory function `createIvantiArchiveRouter(db, requireAuth)` returning Express Router
|
||||
- Apply `requireAuth(db)` middleware to all routes
|
||||
- Implement GET `/` — list archive records with optional `?state=` filter, return `{ archives: [...], total: N }`. Return 400 with message "Invalid state parameter. Valid values: ACTIVE, ARCHIVED, RETURNED, CLOSED" if an unrecognized state value is provided.
|
||||
- Implement GET `/stats` — return `{ ACTIVE: N, ARCHIVED: N, RETURNED: N, CLOSED: N, total: N }`
|
||||
- Implement GET `/:findingId/history` — return `{ finding_id, transitions: [...] }` ordered by transitioned_at DESC, return empty array for unknown finding_id
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5_
|
||||
|
||||
- [x] 4.2 Register archive router in `backend/server.js`
|
||||
- Import `createIvantiArchiveRouter` from `./routes/ivantiArchive`
|
||||
- Mount at `/api/ivanti/archive` with `requireAuth` middleware
|
||||
- _Requirements: 4.1_
|
||||
|
||||
- [ ]* 4.3 Write property test for state filtering
|
||||
- **Property 6: State filter returns only matching records**
|
||||
- Generate archive records with random states, query with filter, verify only matching records returned
|
||||
- **Validates: Requirements 4.1**
|
||||
|
||||
- [ ]* 4.4 Write property test for history ordering
|
||||
- **Property 7: Transition history is ordered by timestamp descending**
|
||||
- Generate multiple transitions for a finding, query history, verify descending timestamp order
|
||||
- **Validates: Requirements 4.2**
|
||||
|
||||
- [ ]* 4.5 Write property test for stats accuracy
|
||||
- **Property 8: Stats counts match actual record distribution**
|
||||
- Generate archive records with random states, query stats, verify counts match actual distribution
|
||||
- **Validates: Requirements 4.3**
|
||||
|
||||
- [x] 5. Checkpoint — Verify API endpoints
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 6. Implement Archive Summary Bar UI component
|
||||
- [x] 6.1 Create `frontend/src/components/pages/ArchiveSummaryBar.js`
|
||||
- Fetch stats from `/api/ivanti/archive/stats` on mount
|
||||
- Render four stat cards: ACTIVE (sky blue #0EA5E9), ARCHIVED (amber #F59E0B), RETURNED (emerald #10B981), CLOSED (red #EF4444)
|
||||
- Each card shows the count and state label with Lucide icons and monospace typography
|
||||
- Accept `onStateClick` callback prop and `activeFilter` prop for highlighting the selected state
|
||||
- Use inline style objects matching the existing design system (dark gradients, glows, hover effects)
|
||||
- _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5_
|
||||
|
||||
- [x] 6.2 Integrate Archive Summary Bar into the Ivanti findings page
|
||||
- Import and render `ArchiveSummaryBar` in the Ivanti findings section of `App.js` (or the relevant page component)
|
||||
- Wire `onStateClick` to manage a state filter for the archive list display
|
||||
- _Requirements: 5.3_
|
||||
|
||||
- [x] 7. Final checkpoint — Verify full integration
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests use `fast-check` library with minimum 100 iterations per test
|
||||
- All backend code uses callback-based SQLite API wrapped in promises (matching existing patterns)
|
||||
- All frontend code uses plain JavaScript (no TypeScript)
|
||||
1
.kiro/specs/fp-attachment-library/.config.kiro
Normal file
1
.kiro/specs/fp-attachment-library/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "acff93bd-0045-4fcd-b948-cc52c7cc5ec6", "workflowType": "requirements-first", "specType": "feature"}
|
||||
362
.kiro/specs/fp-attachment-library/design.md
Normal file
362
.kiro/specs/fp-attachment-library/design.md
Normal file
@@ -0,0 +1,362 @@
|
||||
# Design Document: FP Attachment Library
|
||||
|
||||
## Overview
|
||||
|
||||
This feature extends the FP submission workflow to let users attach documents from the existing CVE document library (the `documents` table) alongside traditional local file uploads. The core change is a new **Attachment Source Picker** component shared by both the create and edit modals, backed by a new **Document Search API** endpoint. On submission, the backend reads library files from disk and sends them to the Ivanti API identically to local uploads.
|
||||
|
||||
The design prioritizes minimal disruption to the existing codebase: one new GET endpoint, modifications to two existing POST endpoints, and a shared React component inserted into both modals.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Frontend
|
||||
A[FpWorkflowModal] --> C[AttachmentSourcePicker]
|
||||
B[FpEditModal] --> C
|
||||
C -->|local files| D[File objects in state]
|
||||
C -->|library docs| E[Document IDs in state]
|
||||
end
|
||||
subgraph Backend
|
||||
F[GET /api/documents/search] -->|SQLite| G[(documents table)]
|
||||
H[POST /api/ivanti/fp-workflow] -->|reads disk| I[uploads/]
|
||||
H -->|multipart| J[Ivanti API]
|
||||
K[POST .../attachments] -->|reads disk| I
|
||||
K -->|multipart| J
|
||||
end
|
||||
C -->|fetch| F
|
||||
A -->|FormData + libraryDocIds| H
|
||||
B -->|FormData + libraryDocIds| K
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Request Flow
|
||||
|
||||
1. User opens FP Create or Edit modal
|
||||
2. Attachment Source Picker renders with two mode tabs: **Local Upload** and **Library**
|
||||
3. In Library mode, user types a search query → frontend debounces 300ms → calls `GET /api/documents/search?q=...`
|
||||
4. User selects library documents and/or local files
|
||||
5. On submit:
|
||||
- Frontend sends `FormData` with local files in `attachments` field and library document IDs in a `libraryDocIds` JSON field
|
||||
- Backend parses both, looks up library documents in the `documents` table, reads their files from disk
|
||||
- Backend combines local file buffers and library file buffers into a single `files` array
|
||||
- Backend calls `ivantiFormPost` with all files in one multipart request
|
||||
- Backend records results in `attachment_results_json` with a `source` field (`"local"` or `"library"`)
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
1. **Single shared component**: The `AttachmentSourcePicker` is used in both modals to avoid duplication. It receives callbacks for state management and renders the mode toggle, search UI, and unified attachment list.
|
||||
|
||||
2. **Library doc IDs sent as JSON field**: Rather than changing the multipart structure, library document IDs are sent as a JSON-encoded string field (`libraryDocIds`) alongside the existing `attachments` file field. This keeps the existing local upload path unchanged.
|
||||
|
||||
3. **Backend reads files from disk**: Library documents are read from disk using `fs.readFileSync(file_path)` at submission time. This avoids storing duplicate file buffers and keeps the Ivanti API call identical for both sources.
|
||||
|
||||
4. **No new database tables**: The feature uses the existing `documents` table for search and the existing `ivanti_fp_submissions` table for recording results. The only schema-level change is adding a `source` field to the JSON objects in `attachment_results_json`.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### New API Endpoint
|
||||
|
||||
#### `GET /api/documents/search`
|
||||
|
||||
Added to `backend/routes/ivantiFpWorkflow.js` (or as a new route in `server.js` alongside existing document routes).
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `q` | query string | No | Search term matched against `name`, `cve_id`, `vendor` using SQL `LIKE` |
|
||||
|
||||
**Response** (200):
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 42,
|
||||
"cve_id": "CVE-2024-1234",
|
||||
"vendor": "Microsoft",
|
||||
"name": "advisory-2024-1234.pdf",
|
||||
"type": "Advisory",
|
||||
"file_size": "245760",
|
||||
"mime_type": "application/pdf",
|
||||
"uploaded_at": "2024-11-15T10:30:00.000Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
**Implementation**:
|
||||
```javascript
|
||||
// Pseudocode
|
||||
router.get('/documents/search', requireAuth(db), (req, res) => {
|
||||
const q = (req.query.q || '').trim();
|
||||
let sql, params;
|
||||
if (q) {
|
||||
const like = `%${q}%`;
|
||||
sql = `SELECT id, cve_id, vendor, name, type, file_size, mime_type, uploaded_at
|
||||
FROM documents
|
||||
WHERE name LIKE ? OR cve_id LIKE ? OR vendor LIKE ?
|
||||
ORDER BY uploaded_at DESC
|
||||
LIMIT 50`;
|
||||
params = [like, like, like];
|
||||
} else {
|
||||
sql = `SELECT id, cve_id, vendor, name, type, file_size, mime_type, uploaded_at
|
||||
FROM documents
|
||||
ORDER BY uploaded_at DESC
|
||||
LIMIT 50`;
|
||||
params = [];
|
||||
}
|
||||
db.all(sql, params, (err, rows) => {
|
||||
if (err) return res.status(500).json({ error: 'Database error.' });
|
||||
res.json(rows || []);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Modified API Endpoints
|
||||
|
||||
#### `POST /api/ivanti/fp-workflow` (create)
|
||||
|
||||
**New field in multipart body**:
|
||||
- `libraryDocIds` — JSON-encoded array of document IDs (integers) from the `documents` table
|
||||
|
||||
**Backend changes**:
|
||||
1. Parse `libraryDocIds` from `req.body` (default to `[]`)
|
||||
2. Validate each ID is a positive integer
|
||||
3. Query `documents` table for matching records
|
||||
4. Validate all IDs were found (400 if any missing)
|
||||
5. Read each file from disk using `file_path` (error if file missing on disk)
|
||||
6. Combine local file buffers (`req.files`) and library file buffers into a single `formFiles` array
|
||||
7. Pass combined array to `ivantiFormPost`
|
||||
8. Record results with `source: "local"` or `source: "library"` in `attachment_results_json`
|
||||
|
||||
#### `POST /api/ivanti/fp-workflow/submissions/:id/attachments` (edit)
|
||||
|
||||
Same changes as the create endpoint — accepts `libraryDocIds` alongside `attachments` files.
|
||||
|
||||
### New Frontend Component
|
||||
|
||||
#### `AttachmentSourcePicker`
|
||||
|
||||
Defined inline in `ReportingPage.js` (consistent with existing component patterns).
|
||||
|
||||
**Props**:
|
||||
| Prop | Type | Description |
|
||||
|------|------|-------------|
|
||||
| `files` | `File[]` | Current local file attachments |
|
||||
| `onFilesChange` | `(files: File[]) => void` | Callback when local files change |
|
||||
| `libraryDocs` | `object[]` | Current selected library documents |
|
||||
| `onLibraryDocsChange` | `(docs: object[]) => void` | Callback when library selections change |
|
||||
| `disabled` | `boolean` | Disables all interactions (for approved submissions) |
|
||||
|
||||
**Internal state**:
|
||||
- `mode` — `'local'` or `'library'` (default: `'local'`)
|
||||
- `searchQuery` — current search input value
|
||||
- `searchResults` — array of document records from API
|
||||
- `searching` — loading state for search
|
||||
|
||||
**Behavior**:
|
||||
- Mode toggle renders two tab-style buttons at the top
|
||||
- Local mode shows the existing drag-and-drop zone
|
||||
- Library mode shows a search input + scrollable results list
|
||||
- Search is debounced at 300ms using `setTimeout`/`clearTimeout`
|
||||
- Selected library docs are tracked by `id` to prevent duplicates
|
||||
- Already-selected docs appear disabled/checked in search results
|
||||
- Unified attachment list below shows all attachments with source badges
|
||||
- Each attachment row shows: source badge, filename, file size, remove button
|
||||
- Library attachment rows additionally show CVE ID and vendor
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> LocalMode
|
||||
LocalMode --> LibraryMode: Click "Library" tab
|
||||
LibraryMode --> LocalMode: Click "Local Upload" tab
|
||||
|
||||
state LibraryMode {
|
||||
[*] --> Idle
|
||||
Idle --> Searching: User types (after 300ms debounce)
|
||||
Searching --> ResultsShown: API responds
|
||||
ResultsShown --> Searching: User types again
|
||||
ResultsShown --> DocSelected: User clicks result
|
||||
DocSelected --> ResultsShown: Doc added to list
|
||||
}
|
||||
```
|
||||
|
||||
### Integration Points
|
||||
|
||||
#### FpWorkflowModal (create)
|
||||
|
||||
- Replace the current file upload section with `<AttachmentSourcePicker>`
|
||||
- Add `libraryDocs` state array alongside existing `files` state
|
||||
- On submit, append `libraryDocIds` as JSON string to `FormData`:
|
||||
```javascript
|
||||
formData.append('libraryDocIds', JSON.stringify(libraryDocs.map(d => d.id)));
|
||||
```
|
||||
|
||||
#### FpEditModal (edit — attachments tab)
|
||||
|
||||
- Replace the static "upload in Ivanti" message with `<AttachmentSourcePicker>`
|
||||
- Keep existing attachment display above the picker
|
||||
- On submit, build `FormData` with both local files and `libraryDocIds`
|
||||
- Disable picker when `lifecycle_status === 'approved'`
|
||||
|
||||
## Data Models
|
||||
|
||||
### Existing: `documents` table (no changes)
|
||||
|
||||
| Column | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `id` | INTEGER PK | Auto-increment ID |
|
||||
| `cve_id` | VARCHAR(20) | Associated CVE identifier |
|
||||
| `vendor` | VARCHAR(100) | Vendor name |
|
||||
| `name` | VARCHAR(255) | Original filename |
|
||||
| `type` | VARCHAR(50) | Document type (Advisory, Patch, etc.) |
|
||||
| `file_path` | VARCHAR(500) | Relative path under `uploads/` |
|
||||
| `file_size` | VARCHAR(20) | Human-readable or byte size |
|
||||
| `mime_type` | VARCHAR(100) | MIME type |
|
||||
| `uploaded_at` | TIMESTAMP | Upload timestamp |
|
||||
| `notes` | TEXT | Optional notes |
|
||||
|
||||
### Modified: `attachment_results_json` shape
|
||||
|
||||
Current format per entry:
|
||||
```json
|
||||
{ "filename": "report.pdf", "success": true }
|
||||
```
|
||||
|
||||
New format per entry:
|
||||
```json
|
||||
{ "filename": "report.pdf", "success": true, "source": "local" }
|
||||
```
|
||||
or:
|
||||
```json
|
||||
{ "filename": "advisory-2024.pdf", "success": true, "source": "library", "documentId": 42 }
|
||||
```
|
||||
|
||||
The `source` field is added to distinguish attachment origins. The `documentId` field is included for library documents to enable traceability. Existing records without a `source` field are treated as `"local"` by the frontend for backward compatibility.
|
||||
|
||||
### Frontend State: Library Document Selection
|
||||
|
||||
```javascript
|
||||
// Shape of a selected library document in component state
|
||||
{
|
||||
id: 42, // documents.id
|
||||
cve_id: "CVE-2024-1234",
|
||||
vendor: "Microsoft",
|
||||
name: "advisory-2024-1234.pdf",
|
||||
file_size: "245760",
|
||||
mime_type: "application/pdf"
|
||||
}
|
||||
```
|
||||
|
||||
## 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: Search results match query
|
||||
|
||||
*For any* non-empty search query string `q` and any set of documents in the database, every document returned by the Document Search API SHALL have `q` as a case-insensitive substring of its `name`, `cve_id`, or `vendor` field.
|
||||
|
||||
**Validates: Requirements 1.1**
|
||||
|
||||
### Property 2: Default results are ordered by recency
|
||||
|
||||
*For any* set of documents in the database, when the Document Search API is called with no query, the returned results SHALL be ordered by `uploaded_at` descending (most recent first).
|
||||
|
||||
**Validates: Requirements 1.2**
|
||||
|
||||
### Property 3: Result set size is bounded
|
||||
|
||||
*For any* search query (including empty), the Document Search API SHALL return at most 50 records.
|
||||
|
||||
**Validates: Requirements 1.3**
|
||||
|
||||
### Property 4: Library document ID validation rejects non-positive-integers
|
||||
|
||||
*For any* value that is not a positive integer (e.g., negative numbers, zero, floats, non-numeric strings, null), the backend validation SHALL reject it as an invalid library document ID.
|
||||
|
||||
**Validates: Requirements 4.5**
|
||||
|
||||
### Property 5: Combined attachments are all sent to Ivanti
|
||||
|
||||
*For any* combination of local file uploads and library document references in a submission, the backend SHALL produce a files array for the Ivanti API call whose length equals the count of local files plus the count of valid library documents, and each library file buffer SHALL match the content read from the document's `file_path`.
|
||||
|
||||
**Validates: Requirements 4.1, 4.2**
|
||||
|
||||
### Property 6: Attachment results record source and filename correctly
|
||||
|
||||
*For any* mix of local and library attachments processed by the backend, each entry in `attachment_results_json` SHALL have a `source` field of `"local"` or `"library"`, and for library entries the `filename` SHALL equal the `name` field from the corresponding `documents` record.
|
||||
|
||||
**Validates: Requirements 4.6, 4.7**
|
||||
|
||||
### Property 7: No duplicate library documents in attachment list
|
||||
|
||||
*For any* sequence of library document selections applied to the Attachment Source Picker, the resulting attachment list SHALL contain at most one entry per document `id`.
|
||||
|
||||
**Validates: Requirements 5.1**
|
||||
|
||||
### Property 8: Attachment list displays all required fields per type
|
||||
|
||||
*For any* attachment in the list (local or library), the rendered display SHALL include the filename, file size, source indicator, and a remove action. *For any* library attachment, the display SHALL additionally include the CVE ID and vendor name.
|
||||
|
||||
**Validates: Requirements 6.1, 6.2, 6.3, 6.4**
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| Document search DB error | Return 500 with `{ error: 'Database error.' }` |
|
||||
| Invalid `libraryDocIds` JSON | Return 400 with `{ error: 'libraryDocIds must be a valid JSON array.' }` |
|
||||
| Non-positive-integer document ID | Return 400 identifying the invalid ID |
|
||||
| Document ID not found in DB | Return 400 identifying the missing document ID |
|
||||
| Library file missing from disk | Log warning, skip that attachment, include `{ success: false, error: 'File not found on disk' }` in attachment results, continue with remaining files |
|
||||
| Ivanti API failure for attachment upload | Record `{ success: false, error: '...' }` per file in results, return partial success if some files succeeded |
|
||||
| Network error calling Document Search API (frontend) | Show inline error message in search results area, allow retry |
|
||||
| Empty search results | Show "No documents found" message with suggestion to refine search |
|
||||
| Unauthenticated request to search endpoint | Return 401 (handled by existing `requireAuth` middleware) |
|
||||
|
||||
### Backward Compatibility
|
||||
|
||||
- Existing `attachment_results_json` entries without a `source` field are treated as `"local"` by the frontend
|
||||
- The `libraryDocIds` field is optional in both create and edit endpoints — omitting it preserves current behavior exactly
|
||||
- No database migrations required — the `documents` table already exists
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Property-Based Tests (fast-check)
|
||||
|
||||
The project uses plain JavaScript with React 19. Property-based tests will use [fast-check](https://github.com/dubzzz/fast-check) with the existing `react-scripts test` runner (Jest).
|
||||
|
||||
Each property test runs a minimum of 100 iterations and is tagged with a comment referencing its design property.
|
||||
|
||||
**Configuration**: `npm install --save-dev fast-check` in the frontend package (or backend if testing backend logic separately).
|
||||
|
||||
**Properties to test**:
|
||||
- Property 1: Search relevance — generate random documents and queries, verify all results match
|
||||
- Property 2: Default ordering — generate random documents, verify descending order
|
||||
- Property 3: Result limit — generate >50 documents, verify max 50 returned
|
||||
- Property 4: ID validation — generate random non-positive-integer values, verify rejection
|
||||
- Property 5: Combined attachment handling — generate random mixes, verify file array correctness
|
||||
- Property 6: Result record shape — generate random mixes, verify source and filename fields
|
||||
- Property 7: Duplicate prevention — generate random selection sequences, verify uniqueness
|
||||
- Property 8: Display completeness — generate random attachment lists, verify rendered fields
|
||||
|
||||
**Tag format**: `// Feature: fp-attachment-library, Property N: <property text>`
|
||||
|
||||
### Unit Tests (example-based)
|
||||
|
||||
- Authentication guard on search endpoint (1.5)
|
||||
- DB error handling returns 500 (1.6)
|
||||
- Mode toggle renders correctly in both modals (2.1, 2.2, 2.3)
|
||||
- Debounce behavior with fake timers (2.4)
|
||||
- Library doc selection adds to list with indicator (2.5)
|
||||
- Remove works for both types (2.6)
|
||||
- Mixed attachments in same submission (2.7)
|
||||
- Library doc displays name, size, CVE ID (2.8)
|
||||
- Edit modal replaces static message (3.1)
|
||||
- Existing attachments shown above picker (3.4)
|
||||
- Approved submission disables picker (3.5)
|
||||
- Missing file on disk returns error (4.3)
|
||||
- Invalid document ID returns 400 (4.4)
|
||||
- Already-selected docs shown as disabled (5.2)
|
||||
- Removed doc re-enabled in results (5.3)
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- End-to-end create flow with mixed local + library attachments
|
||||
- End-to-end edit flow adding library attachments to existing submission
|
||||
- Search endpoint with real SQLite database
|
||||
94
.kiro/specs/fp-attachment-library/requirements.md
Normal file
94
.kiro/specs/fp-attachment-library/requirements.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The FP Attachment Library feature extends the FP submission workflow (both create and edit flows) to allow users to attach existing documents from the CVE document library stored in the `documents` table, in addition to the current local file upload capability. This eliminates the need to re-download and re-upload files that already exist in the system, streamlining the attachment workflow for FP submissions.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Dashboard**: The STEAM Security Dashboard application
|
||||
- **FP_Create_Modal**: The FpWorkflowModal component used to create new FP workflow submissions (in ReportingPage.js)
|
||||
- **FP_Edit_Modal**: The FpEditModal component used to edit existing FP workflow submissions (in ReportingPage.js)
|
||||
- **Document_Library**: The collection of files stored in the `documents` table, organized by CVE ID and vendor, with files on disk under `uploads/{cve_id}/{vendor}/`
|
||||
- **Attachment_Source_Picker**: The UI component that lets users choose between uploading a local file or selecting an existing document from the Document_Library
|
||||
- **Document_Search_API**: The backend endpoint that searches and returns documents from the Document_Library for selection
|
||||
- **Library_Document**: A document record from the `documents` table, containing id, cve_id, vendor, name, type, file_path, file_size, mime_type, uploaded_at, and notes
|
||||
- **Ivanti_API**: The external Ivanti/RiskSense API that receives FP workflow submissions and file attachments
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Document Search API
|
||||
|
||||
**User Story:** As an editor, I want to search the document library from within the FP workflow, so that I can find and attach existing documents without leaving the modal.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a search query is provided, THE Document_Search_API SHALL return Library_Document records whose name, cve_id, or vendor fields contain the query string
|
||||
2. WHEN no search query is provided, THE Document_Search_API SHALL return the most recent Library_Document records ordered by uploaded_at descending
|
||||
3. THE Document_Search_API SHALL limit results to a maximum of 50 records per request
|
||||
4. THE Document_Search_API SHALL return each Library_Document with its id, cve_id, vendor, name, type, file_size, mime_type, and uploaded_at fields
|
||||
5. THE Document_Search_API SHALL require an authenticated session before returning results
|
||||
6. IF the database query fails, THEN THE Document_Search_API SHALL return an error response with a 500 status code
|
||||
|
||||
### Requirement 2: Attachment Source Picker in FP Create Modal
|
||||
|
||||
**User Story:** As an editor, I want to choose between uploading a local file or selecting a document from the library when creating an FP submission, so that I can attach evidence without re-uploading files that already exist in the system.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE FP_Create_Modal SHALL display the Attachment_Source_Picker with two modes: local file upload and library document selection
|
||||
2. WHEN the user selects local file upload mode, THE FP_Create_Modal SHALL display the existing drag-and-drop zone and file picker
|
||||
3. WHEN the user selects library document selection mode, THE FP_Create_Modal SHALL display a search input and a scrollable list of matching Library_Document records
|
||||
4. WHEN the user types in the library search input, THE FP_Create_Modal SHALL query the Document_Search_API and display matching results within 300 milliseconds of the last keystroke (debounced)
|
||||
5. WHEN the user selects a Library_Document from the search results, THE FP_Create_Modal SHALL add the document to the attachment list with a visual indicator distinguishing it from locally uploaded files
|
||||
6. THE FP_Create_Modal SHALL allow the user to remove any attachment from the list, whether it is a local file or a Library_Document
|
||||
7. THE FP_Create_Modal SHALL allow mixing local file uploads and Library_Document selections in the same submission
|
||||
8. THE FP_Create_Modal SHALL display the file name, file size, and CVE ID for each selected Library_Document in the attachment list
|
||||
|
||||
### Requirement 3: Attachment Source Picker in FP Edit Modal
|
||||
|
||||
**User Story:** As an editor, I want to attach existing library documents to an FP submission I am editing, so that I can add supporting evidence after the initial submission without re-uploading files.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE FP_Edit_Modal SHALL replace the static "upload in Ivanti" message on the attachments tab with the Attachment_Source_Picker
|
||||
2. WHEN the user selects library document selection mode, THE FP_Edit_Modal SHALL display a search input and a scrollable list of matching Library_Document records
|
||||
3. WHEN the user selects local file upload mode, THE FP_Edit_Modal SHALL display a drag-and-drop zone and file picker for local files
|
||||
4. THE FP_Edit_Modal SHALL continue to display existing attachments from the initial submission above the Attachment_Source_Picker
|
||||
5. WHILE the submission lifecycle_status is "approved", THE FP_Edit_Modal SHALL disable the Attachment_Source_Picker and prevent adding new attachments
|
||||
6. THE FP_Edit_Modal SHALL allow the user to upload or attach selected documents by clicking a submit action button
|
||||
|
||||
### Requirement 4: Backend Handling of Library Document Attachments
|
||||
|
||||
**User Story:** As an editor, I want library documents to be sent to the Ivanti API the same way as local uploads, so that all attachments appear correctly on the Ivanti workflow.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the FP submission includes Library_Document references, THE Dashboard backend SHALL read the referenced files from disk using the file_path stored in the documents table
|
||||
2. WHEN the FP submission includes both local files and Library_Document references, THE Dashboard backend SHALL send all attachments to the Ivanti_API in a single multipart request
|
||||
3. IF a referenced Library_Document file_path does not exist on disk, THEN THE Dashboard backend SHALL return an error identifying the missing file and skip that attachment
|
||||
4. IF a referenced Library_Document id does not exist in the documents table, THEN THE Dashboard backend SHALL return a 400 error identifying the invalid document ID
|
||||
5. THE Dashboard backend SHALL validate that each referenced Library_Document id is a positive integer before querying the database
|
||||
6. THE Dashboard backend SHALL include Library_Document attachments in the attachment_results_json field of the submission record, with a source indicator distinguishing them from local uploads
|
||||
7. WHEN recording attachment results, THE Dashboard backend SHALL store the original document name from the Library_Document record as the filename
|
||||
|
||||
### Requirement 5: Duplicate Attachment Prevention
|
||||
|
||||
**User Story:** As an editor, I want the system to prevent me from attaching the same library document twice, so that I do not create redundant attachments on the Ivanti workflow.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the user selects a Library_Document that is already in the attachment list, THE Attachment_Source_Picker SHALL not add a duplicate entry
|
||||
2. THE Attachment_Source_Picker SHALL visually indicate Library_Document records that are already attached by showing them as disabled or checked in the search results
|
||||
3. WHEN the user removes a previously selected Library_Document from the attachment list, THE Attachment_Source_Picker SHALL re-enable that document in the search results
|
||||
|
||||
### Requirement 6: Attachment List Display
|
||||
|
||||
**User Story:** As an editor, I want to clearly distinguish between local uploads and library documents in the attachment list, so that I know the source of each attachment before submitting.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Attachment_Source_Picker SHALL display a source badge or icon next to each attachment indicating whether it is a "Local Upload" or a "Library Document"
|
||||
2. THE Attachment_Source_Picker SHALL display the file name and file size for all attachments regardless of source
|
||||
3. WHEN displaying a Library_Document attachment, THE Attachment_Source_Picker SHALL also display the associated CVE ID and vendor name
|
||||
4. THE Attachment_Source_Picker SHALL display a remove button for each attachment in the list
|
||||
95
.kiro/specs/fp-attachment-library/tasks.md
Normal file
95
.kiro/specs/fp-attachment-library/tasks.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# Implementation Plan: FP Attachment Library
|
||||
|
||||
## Overview
|
||||
|
||||
This plan implements the FP Attachment Library feature, which allows users to attach existing CVE document library files to FP workflow submissions alongside traditional local file uploads. The implementation adds a new Document Search API endpoint, modifies two existing backend endpoints to handle library document references, and creates a shared AttachmentSourcePicker component used in both the create and edit modals.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Add Document Search API endpoint
|
||||
- [x] 1.1 Add `GET /api/documents/search` route in `backend/routes/ivantiFpWorkflow.js`
|
||||
- Add a new GET route handler for `/documents/search` inside `createIvantiFpWorkflowRouter`
|
||||
- Accept optional `q` query parameter for search term
|
||||
- When `q` is provided, query the `documents` table with `LIKE` matching against `name`, `cve_id`, and `vendor` columns (case-insensitive)
|
||||
- When `q` is empty or missing, return the most recent documents ordered by `uploaded_at DESC`
|
||||
- Limit results to 50 records maximum
|
||||
- Return each record with fields: `id`, `cve_id`, `vendor`, `name`, `type`, `file_size`, `mime_type`, `uploaded_at`
|
||||
- Protect with `requireAuth(db)` middleware
|
||||
- Return 500 with `{ error: 'Database error.' }` on DB failure
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6_
|
||||
|
||||
- [x] 2. Modify backend to handle library document attachments on create
|
||||
- [x] 2.1 Update `POST /api/ivanti/fp-workflow` in `backend/routes/ivantiFpWorkflow.js` to accept `libraryDocIds`
|
||||
- Parse `libraryDocIds` from `req.body` as a JSON-encoded array (default to `[]` if absent)
|
||||
- Return 400 if `libraryDocIds` is not valid JSON
|
||||
- Validate each ID is a positive integer; return 400 identifying any invalid ID
|
||||
- Query the `documents` table for all referenced IDs; return 400 if any ID is not found
|
||||
- Read each library file from disk using `fs.readFileSync(file_path)`; if a file is missing on disk, log a warning and include `{ success: false, error: 'File not found on disk', source: 'library', documentId: id }` in attachment results, skip that file
|
||||
- Combine local file buffers (`req.files`) and library file buffers into a single `formFiles` array passed to `ivantiFormPost`
|
||||
- Record attachment results with `source: "local"` for uploaded files and `source: "library"` plus `documentId` for library files
|
||||
- Use the `name` field from the `documents` record as the `filename` in attachment results for library files
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7_
|
||||
|
||||
- [x] 3. Modify backend to handle library document attachments on edit
|
||||
- [x] 3.1 Update `POST /api/ivanti/fp-workflow/submissions/:id/attachments` in `backend/routes/ivantiFpWorkflow.js` to accept `libraryDocIds`
|
||||
- Apply the same `libraryDocIds` parsing, validation, disk-read, and combined upload logic as task 2.1
|
||||
- Combine local file buffers and library file buffers into a single `formFiles` array for the Ivanti API call
|
||||
- Record attachment results with `source` and `documentId` fields matching the create endpoint behavior
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7_
|
||||
|
||||
- [x] 4. Checkpoint — Verify backend changes
|
||||
- Ensure all backend changes are syntactically correct and consistent with existing patterns. Ask the user if questions arise.
|
||||
|
||||
- [x] 5. Create AttachmentSourcePicker component
|
||||
- [x] 5.1 Implement `AttachmentSourcePicker` inline in `frontend/src/components/pages/ReportingPage.js`
|
||||
- Define the component above `FpWorkflowModal` in the file
|
||||
- Accept props: `files`, `onFilesChange`, `libraryDocs`, `onLibraryDocsChange`, `disabled`
|
||||
- Implement a mode toggle with two tab-style buttons: "Local Upload" and "Library" (default to "Local Upload")
|
||||
- In Local Upload mode, render the existing drag-and-drop zone with file input, file validation (extension + size), and file list
|
||||
- In Library mode, render a search input that queries `GET /api/documents/search?q=...` with 300ms debounce using `setTimeout`/`clearTimeout`
|
||||
- Display search results in a scrollable list showing document name, CVE ID, vendor, and file size
|
||||
- Show already-selected library documents as disabled/checked in search results to prevent duplicates
|
||||
- When a search result is clicked, add it to `libraryDocs` via `onLibraryDocsChange` (skip if already selected by `id`)
|
||||
- When a library doc is removed from the attachment list, re-enable it in search results
|
||||
- Render a unified attachment list below the mode-specific UI showing all attachments (local + library)
|
||||
- Each attachment row displays: source badge ("Local" or "Library"), filename, file size, and a remove button (Trash2 icon)
|
||||
- Library attachment rows additionally display CVE ID and vendor name
|
||||
- Disable all interactions when `disabled` prop is true
|
||||
- Style consistently with existing modal components using inline style objects, monospace font, dark theme colors from DESIGN_SYSTEM.md
|
||||
- Handle network errors on search by showing an inline error message in the results area
|
||||
- Show "No documents found" when search returns empty results
|
||||
- _Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 5.1, 5.2, 5.3, 6.1, 6.2, 6.3, 6.4_
|
||||
|
||||
- [x] 6. Integrate AttachmentSourcePicker into FpWorkflowModal (create flow)
|
||||
- [x] 6.1 Replace the file upload section in `FpWorkflowModal` with `AttachmentSourcePicker`
|
||||
- Add `libraryDocs` state (`useState([])`) alongside existing `files` state
|
||||
- Reset `libraryDocs` to `[]` when modal opens (in the existing `useEffect` on `open`)
|
||||
- Replace the current drag-and-drop zone and file list section with `<AttachmentSourcePicker>` passing `files`, `setFiles`, `libraryDocs`, `setLibraryDocs`, and `disabled={submitting}`
|
||||
- Remove the inline `addFiles`, `removeFile`, `handleDrop`, `handleDragOver` functions and `fileInputRef`/`dropRef` refs (these are now handled inside AttachmentSourcePicker)
|
||||
- On submit, append `libraryDocIds` as a JSON string to the FormData: `formData.append('libraryDocIds', JSON.stringify(libraryDocs.map(d => d.id)))`
|
||||
- Update the progress message to reflect combined attachment count
|
||||
- Update the result view to show source badges on attachment results (use `source` field, default to `"local"` for backward compatibility)
|
||||
- _Requirements: 2.1, 2.2, 2.3, 2.5, 2.6, 2.7_
|
||||
|
||||
- [x] 7. Integrate AttachmentSourcePicker into FpEditModal (edit flow)
|
||||
- [x] 7.1 Replace the static "upload in Ivanti" message on the attachments tab with `AttachmentSourcePicker`
|
||||
- Add `libraryDocs` state (`useState([])`) alongside existing `files` state
|
||||
- Reset `libraryDocs` to `[]` when submission changes (in the existing `useEffect` on `submission`)
|
||||
- Keep the existing attachment display section (showing attachments from initial submission) above the picker
|
||||
- Render `<AttachmentSourcePicker>` below existing attachments, passing `files`, `setFiles`, `libraryDocs`, `setLibraryDocs`, and `disabled={isApproved}`
|
||||
- Update `handleUploadAttachments` to build FormData with both local files and `libraryDocIds` JSON field
|
||||
- Enable the upload button when either `files.length > 0` or `libraryDocs.length > 0`
|
||||
- Disable the picker when `lifecycle_status === 'approved'`
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.4, 3.5, 3.6_
|
||||
|
||||
- [x] 8. Final checkpoint — Verify all changes
|
||||
- Ensure all changes are complete and consistent across backend and frontend. Ensure no hanging or orphaned code. Ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- No testing tasks included per user request — testing will be done on the dev server
|
||||
- The project uses plain JavaScript (no TypeScript) throughout
|
||||
- All frontend styling uses inline style objects consistent with the existing dark theme design system
|
||||
- The `documents` table already exists — no database migrations are needed
|
||||
- The `libraryDocIds` field is optional in both endpoints, preserving full backward compatibility
|
||||
- Existing `attachment_results_json` entries without a `source` field are treated as `"local"` by the frontend
|
||||
1
.kiro/specs/fp-submission-editing/.config.kiro
Normal file
1
.kiro/specs/fp-submission-editing/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "a7e2c1f8-9b34-4d6a-b5e0-8f1c3a2d7e90", "workflowType": "requirements-first", "specType": "feature"}
|
||||
428
.kiro/specs/fp-submission-editing/design.md
Normal file
428
.kiro/specs/fp-submission-editing/design.md
Normal file
@@ -0,0 +1,428 @@
|
||||
# Design Document: FP Submission Editing
|
||||
|
||||
## Overview
|
||||
|
||||
This feature extends the existing FP workflow submission system to support viewing, editing, and resubmitting False Positive submissions. It adds lifecycle status tracking, an edit modal triggered from clickable workflow badges in the Reporting Table and from a submissions list in the Queue Panel, backend endpoints that proxy update/map/attach operations to the Ivanti API, and a submission history audit trail.
|
||||
|
||||
The design builds on the existing `ivantiFpWorkflow.js` route, `FpWorkflowModal` component, and `ivanti_fp_submissions` table. It follows the same conventions: factory-pattern Express routes, inline React components with the dark tactical theme, Multer for file uploads, and the `ivantiFormPost()` / `ivantiPost()` helpers for Ivanti API calls.
|
||||
|
||||
Key Ivanti API endpoints used for editing:
|
||||
- `POST /workflowBatch/falsePositive/update` — update workflow metadata
|
||||
- `POST /workflowBatch/falsePositive/{uuid}/map` — add findings to existing workflow
|
||||
- `POST /workflowBatch/falsePositive/{uuid}/attach` — upload additional attachments
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as User
|
||||
participant FE as React Frontend
|
||||
participant BE as Express Backend
|
||||
participant IV as Ivanti API
|
||||
participant DB as SQLite
|
||||
|
||||
Note over U,FE: Entry Point A: Clickable Workflow Badge
|
||||
U->>FE: Click Reworked/Rejected/Expired badge in Reporting Table
|
||||
FE->>FE: Look up FP_Submission by workflow batch ID
|
||||
FE->>FE: Open FpEditModal pre-populated with submission data
|
||||
|
||||
Note over U,FE: Entry Point B: Queue Panel Submissions List
|
||||
U->>FE: Click submission in Queue Panel submissions list
|
||||
FE->>FE: Open FpEditModal pre-populated with submission data
|
||||
|
||||
Note over U,DB: Load Submission Data
|
||||
FE->>BE: GET /api/ivanti/fp-submissions
|
||||
BE->>DB: SELECT from ivanti_fp_submissions
|
||||
DB-->>BE: Submission records
|
||||
BE-->>FE: JSON array of submissions
|
||||
|
||||
Note over U,IV: Edit Form Fields
|
||||
U->>FE: Modify name/reason/description/expiration, click Save
|
||||
FE->>BE: PUT /api/ivanti/fp-submissions/:id
|
||||
BE->>BE: Validate input
|
||||
BE->>IV: POST /workflowBatch/falsePositive/update
|
||||
IV-->>BE: 200 OK
|
||||
BE->>DB: UPDATE ivanti_fp_submissions
|
||||
BE->>DB: INSERT ivanti_fp_submission_history
|
||||
BE->>DB: INSERT audit_log
|
||||
BE-->>FE: 200 + updated record
|
||||
|
||||
Note over U,IV: Add Findings
|
||||
U->>FE: Select additional FP queue items, click Add
|
||||
FE->>BE: POST /api/ivanti/fp-submissions/:id/findings
|
||||
BE->>IV: POST /workflowBatch/falsePositive/{uuid}/map
|
||||
IV-->>BE: 200 OK
|
||||
BE->>DB: UPDATE finding_ids_json
|
||||
BE->>DB: UPDATE queue items → complete
|
||||
BE->>DB: INSERT history + audit
|
||||
BE-->>FE: 200 + updated record
|
||||
|
||||
Note over U,IV: Add Attachments
|
||||
U->>FE: Upload files, click Attach
|
||||
FE->>BE: POST /api/ivanti/fp-submissions/:id/attachments (multipart)
|
||||
loop Each file
|
||||
BE->>IV: POST /workflowBatch/falsePositive/{uuid}/attach
|
||||
IV-->>BE: 200 OK
|
||||
end
|
||||
BE->>DB: UPDATE attachment_count, attachment_results_json
|
||||
BE->>DB: INSERT history + audit
|
||||
BE-->>FE: 200 + attachment results
|
||||
|
||||
Note over U,DB: Status Transition
|
||||
U->>FE: Change lifecycle status
|
||||
FE->>BE: PATCH /api/ivanti/fp-submissions/:id/status
|
||||
BE->>DB: UPDATE lifecycle_status, INSERT history + audit
|
||||
BE-->>FE: 200 OK
|
||||
```
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend
|
||||
|
||||
#### Extended Route Module: `backend/routes/ivantiFpWorkflow.js`
|
||||
|
||||
Extends the existing `createIvantiFpWorkflowRouter(db, requireAuth)` with five new endpoints. All endpoints use `requireAuth(db)` and `requireGroup('Admin', 'Standard_User')`, and verify the authenticated user owns the submission (returning 403 otherwise).
|
||||
|
||||
**Endpoint: `GET /api/ivanti/fp-submissions`**
|
||||
|
||||
Returns the authenticated user's FP submission records.
|
||||
|
||||
- Auth: `requireAuth(db)`, any authenticated user (viewers get read-only list)
|
||||
- Response:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"user_id": 5,
|
||||
"username": "jdoe",
|
||||
"ivanti_workflow_batch_id": 33418832,
|
||||
"ivanti_workflow_batch_uuid": "abc-123-def",
|
||||
"workflow_name": "FP - CVE-2024-1234",
|
||||
"reason": "Scanner false positive",
|
||||
"description": "Confirmed by manual review",
|
||||
"expiration_date": "2026-12-31",
|
||||
"scope_override": "Authorized",
|
||||
"finding_ids_json": "[\"2283734550\",\"2283734551\"]",
|
||||
"queue_item_ids_json": "[1,2]",
|
||||
"attachment_count": 2,
|
||||
"attachment_results_json": "[{\"filename\":\"evidence.pdf\",\"success\":true}]",
|
||||
"status": "success",
|
||||
"lifecycle_status": "rework",
|
||||
"error_message": null,
|
||||
"created_at": "2026-04-08T18:16:08",
|
||||
"updated_at": "2026-04-10T12:00:00"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
**Endpoint: `PUT /api/ivanti/fp-submissions/:id`**
|
||||
|
||||
Updates form fields and proxies to Ivanti update endpoint.
|
||||
|
||||
- Auth: `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Ownership: verified via `user_id` match
|
||||
- Lifecycle guard: rejects if `lifecycle_status === 'approved'`
|
||||
- Request body:
|
||||
```json
|
||||
{
|
||||
"name": "Updated FP - CVE-2024-1234",
|
||||
"reason": "Updated reason",
|
||||
"description": "Updated description",
|
||||
"expirationDate": "2027-06-01",
|
||||
"scopeOverride": "Authorized"
|
||||
}
|
||||
```
|
||||
- Validation: same rules as creation form (`validateFpWorkflowForm`)
|
||||
- Ivanti call: `POST /client/{clientId}/workflowBatch/falsePositive/update` with JSON body containing `workflowBatchId` and updated fields
|
||||
- On success: updates local record, inserts history row, logs audit, sets `lifecycle_status` to `resubmitted` if previous status was `rejected` or `rework`
|
||||
- Response: `{ success: true, submission: { ...updatedRecord } }`
|
||||
|
||||
**Endpoint: `POST /api/ivanti/fp-submissions/:id/findings`**
|
||||
|
||||
Maps additional findings to the existing workflow batch.
|
||||
|
||||
- Auth: `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Ownership: verified
|
||||
- Lifecycle guard: rejects if `lifecycle_status === 'approved'`
|
||||
- Request body:
|
||||
```json
|
||||
{
|
||||
"findingIds": ["2283734552", "2283734553"],
|
||||
"queueItemIds": [3, 4]
|
||||
}
|
||||
```
|
||||
- Validates queue items belong to user, are FP type, and pending
|
||||
- Ivanti call: `POST /client/{clientId}/workflowBatch/falsePositive/{uuid}/map` with `subjectFilterRequest` containing the new finding IDs
|
||||
- On success: appends new IDs to `finding_ids_json`, marks queue items complete, inserts history + audit
|
||||
- Response: `{ success: true, addedFindings: [...], queueItemsUpdated: 2 }`
|
||||
|
||||
**Endpoint: `POST /api/ivanti/fp-submissions/:id/attachments`**
|
||||
|
||||
Uploads additional files to the existing workflow batch.
|
||||
|
||||
- Auth: `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Content-Type: `multipart/form-data` (Multer)
|
||||
- Ownership: verified
|
||||
- Lifecycle guard: rejects if `lifecycle_status === 'approved'`
|
||||
- File constraints: same as creation (10 MB, allowed extensions)
|
||||
- Ivanti call: for each file, `POST /client/{clientId}/workflowBatch/falsePositive/{uuid}/attach`
|
||||
- On success: updates `attachment_count` and `attachment_results_json`, inserts history + audit
|
||||
- Response:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"attachmentResults": [
|
||||
{ "filename": "new-evidence.pdf", "success": true },
|
||||
{ "filename": "screenshot.png", "success": false, "error": "Upload failed" }
|
||||
],
|
||||
"status": "success"
|
||||
}
|
||||
```
|
||||
|
||||
**Endpoint: `PATCH /api/ivanti/fp-submissions/:id/status`**
|
||||
|
||||
Updates the lifecycle status of a submission.
|
||||
|
||||
- Auth: `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Ownership: verified
|
||||
- Request body:
|
||||
```json
|
||||
{
|
||||
"lifecycle_status": "rejected"
|
||||
}
|
||||
```
|
||||
- Validates status is one of: `submitted`, `approved`, `rejected`, `rework`, `resubmitted`
|
||||
- Validates transition is allowed (cannot transition FROM `approved`)
|
||||
- On success: updates `lifecycle_status` and `updated_at`, inserts history row with previous and new status, logs audit
|
||||
- Response: `{ success: true, previousStatus: "submitted", newStatus: "rejected" }`
|
||||
|
||||
#### Pure Helper Functions (exported for testing)
|
||||
|
||||
The following pure functions are extracted for testability:
|
||||
|
||||
- `validateFpWorkflowForm(body)` — already exists, reused for edit validation
|
||||
- `isAllowedFileExtension(filename)` — already exists, reused
|
||||
- `buildSubjectFilterRequest(findingIds)` — already exists, reused for map endpoint
|
||||
- `validateLifecycleTransition(currentStatus, newStatus)` — new, returns `{ valid: boolean, error?: string }`
|
||||
- `mergeFindings(existingJson, newIds)` — new, merges finding ID arrays, deduplicates, returns JSON string
|
||||
- `buildSubmissionHistoryEntry(changeType, details, userId, username)` — new, constructs a history record object
|
||||
|
||||
#### Ivanti API Calls
|
||||
|
||||
Uses existing helpers from `backend/helpers/ivantiApi.js`:
|
||||
|
||||
- **Update workflow**: `ivantiPost()` to `POST /client/{clientId}/workflowBatch/falsePositive/update` with JSON body
|
||||
- **Map findings**: `ivantiFormPost()` to `POST /client/{clientId}/workflowBatch/falsePositive/{uuid}/map` with `subjectFilterRequest`
|
||||
- **Attach file**: `ivantiMultipartPost()` to `POST /client/{clientId}/workflowBatch/falsePositive/{uuid}/attach` with file buffer
|
||||
|
||||
### Frontend
|
||||
|
||||
#### New Component: `FpEditModal`
|
||||
|
||||
Defined inline in `frontend/src/components/pages/ReportingPage.js`, following the existing `FpWorkflowModal` pattern.
|
||||
|
||||
**Props:**
|
||||
- `open` (boolean) — controls visibility
|
||||
- `onClose` (function) — close handler
|
||||
- `submission` (object) — the FP_Submission record to edit (null when closed)
|
||||
- `queueItems` (array) — user's current queue items (for adding findings)
|
||||
- `onSuccess` (function) — callback after successful edit, triggers data refresh
|
||||
|
||||
**State:**
|
||||
- `name`, `reason`, `description`, `expirationDate`, `scopeOverride` — editable form fields, initialized from `submission`
|
||||
- `files` — array of new File objects for upload
|
||||
- `additionalFindingIds` — selected queue items to add as findings
|
||||
- `saving` — boolean, disables form during save
|
||||
- `errors` — validation error map
|
||||
- `result` — operation result (success/failure)
|
||||
- `activeTab` — current tab: 'details' | 'findings' | 'attachments' | 'history'
|
||||
|
||||
**UI Layout:**
|
||||
- Modal overlay with dark backdrop (matching `FpWorkflowModal`)
|
||||
- Header: "Edit FP Workflow — {workflow_name}" with lifecycle status badge and close button
|
||||
- Tab bar: Details | Findings | Attachments | History
|
||||
- Details tab: editable form fields (name, reason, description, expiration, scope override) with Save button
|
||||
- Findings tab: current finding IDs list (read-only) + mechanism to select and add FP queue items
|
||||
- Attachments tab: existing attachments list + file upload area for new attachments
|
||||
- History tab: chronological list of changes from `ivanti_fp_submission_history`
|
||||
- Footer: contextual action buttons per tab
|
||||
- Approved submissions: all fields read-only with "This submission is finalized" message
|
||||
|
||||
#### Workflow Badge Modifications (Reporting Table)
|
||||
|
||||
The workflow column renderer (lines 1044–1070 of `ReportingPage.js`) is modified:
|
||||
|
||||
- For badges with state `reworked`, `rejected`, or `expired`:
|
||||
- Add `cursor: 'pointer'` and `onClick` handler
|
||||
- Append a small pencil icon (lucide `Edit3`, 10px) after the state text
|
||||
- On hover: increase border opacity and brighten background
|
||||
- On click: look up matching FP_Submission by `wf.id` (workflow batch ID), open `FpEditModal`
|
||||
- For badges with state `requested` or `approved`:
|
||||
- No changes — remain non-interactive (no cursor, no icon, no click handler)
|
||||
|
||||
#### QueuePanel Modifications
|
||||
|
||||
- Add a "Submissions" section below the existing queue items list
|
||||
- Fetches submissions via `GET /api/ivanti/fp-submissions` on panel open
|
||||
- Each submission row shows: workflow name, batch ID, lifecycle status badge, finding count, created date
|
||||
- Lifecycle status badges use color coding: submitted (sky blue), approved (emerald), rejected (red), rework (amber), resubmitted (sky blue)
|
||||
- Clicking a submission row opens `FpEditModal` with that submission's data
|
||||
- Viewers see the list but cannot click to edit
|
||||
|
||||
#### Lifecycle Status Badge Component
|
||||
|
||||
Inline helper function `lifecycleStatusBadge(status)` returning style object:
|
||||
|
||||
| Status | Border | Background | Text |
|
||||
|--------|--------|------------|------|
|
||||
| submitted | `rgba(14,165,233,0.4)` | `rgba(14,165,233,0.12)` | `#0EA5E9` |
|
||||
| approved | `rgba(16,185,129,0.4)` | `rgba(16,185,129,0.12)` | `#10B981` |
|
||||
| rejected | `rgba(239,68,68,0.4)` | `rgba(239,68,68,0.12)` | `#EF4444` |
|
||||
| rework | `rgba(245,158,11,0.4)` | `rgba(245,158,11,0.12)` | `#F59E0B` |
|
||||
| resubmitted | `rgba(14,165,233,0.4)` | `rgba(14,165,233,0.12)` | `#0EA5E9` |
|
||||
|
||||
## Data Models
|
||||
|
||||
### Schema Changes to `ivanti_fp_submissions`
|
||||
|
||||
Three new columns added to the existing table:
|
||||
|
||||
```sql
|
||||
ALTER TABLE ivanti_fp_submissions ADD COLUMN lifecycle_status TEXT NOT NULL DEFAULT 'submitted'
|
||||
CHECK(lifecycle_status IN ('submitted', 'approved', 'rejected', 'rework', 'resubmitted'));
|
||||
|
||||
ALTER TABLE ivanti_fp_submissions ADD COLUMN ivanti_workflow_batch_uuid TEXT;
|
||||
|
||||
ALTER TABLE ivanti_fp_submissions ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP;
|
||||
```
|
||||
|
||||
### New Table: `ivanti_fp_submission_history`
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS ivanti_fp_submission_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
submission_id INTEGER NOT NULL,
|
||||
user_id INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
change_type TEXT NOT NULL CHECK(change_type IN (
|
||||
'created', 'fields_updated', 'findings_added',
|
||||
'attachments_added', 'status_changed'
|
||||
)),
|
||||
change_details_json TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (submission_id) REFERENCES ivanti_fp_submissions(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fp_history_submission ON ivanti_fp_submission_history(submission_id);
|
||||
```
|
||||
|
||||
**change_details_json examples:**
|
||||
|
||||
- `fields_updated`: `{"changed": {"name": {"from": "old", "to": "new"}, "reason": {"from": "old", "to": "new"}}}`
|
||||
- `findings_added`: `{"addedFindingIds": ["123", "456"], "queueItemIds": [3, 4]}`
|
||||
- `attachments_added`: `{"files": [{"filename": "evidence.pdf", "success": true}]}`
|
||||
- `status_changed`: `{"from": "submitted", "to": "rejected"}`
|
||||
- `created`: `{"workflowBatchId": 33418832, "findingCount": 3, "attachmentCount": 1}`
|
||||
|
||||
### Migration Script: `backend/migrations/add_fp_submission_editing.js`
|
||||
|
||||
Applies all schema changes idempotently using `ALTER TABLE ... ADD COLUMN` wrapped in try/catch (SQLite throws if column already exists) and `CREATE TABLE IF NOT EXISTS` / `CREATE INDEX IF NOT EXISTS`.
|
||||
|
||||
|
||||
|
||||
## 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.*
|
||||
|
||||
Note: Properties for `validateFpWorkflowForm` and `isAllowedFileExtension` are already covered by the existing `ivanti-fp-workflow-submission` spec and are reused without modification. The properties below cover new pure functions introduced by this feature.
|
||||
|
||||
### Property 1: Finding Merge Preserves All IDs and Deduplicates
|
||||
|
||||
*For any* existing finding IDs JSON string (valid JSON array of strings) and any array of new finding ID strings, `mergeFindings(existingJson, newIds)` should produce a JSON string that, when parsed, contains every ID from the original array and every ID from the new array, contains no duplicate entries, and has a length less than or equal to the sum of the original and new array lengths.
|
||||
|
||||
**Validates: Requirements 3.3**
|
||||
|
||||
### Property 2: Lifecycle Transition Validation
|
||||
|
||||
*For any* pair of lifecycle status values (currentStatus, newStatus) drawn from the set {submitted, approved, rejected, rework, resubmitted}, `validateLifecycleTransition(currentStatus, newStatus)` should return `{ valid: false }` whenever currentStatus is "approved" (no transitions allowed from finalized state), and should return `{ valid: true }` for all other currentStatus values when newStatus is a valid lifecycle status. Additionally, when currentStatus is "rejected" or "rework" and newStatus is "resubmitted", the transition should always be valid.
|
||||
|
||||
**Validates: Requirements 5.4, 5.5**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Ivanti API Errors
|
||||
|
||||
| HTTP Status | Endpoint | User-Facing Message | System Behavior |
|
||||
|-------------|----------|---------------------|-----------------|
|
||||
| 401 | All | "Ivanti API key is invalid or missing. Contact your administrator." | Log error, preserve form state |
|
||||
| 419 | All | "API key lacks permissions for this operation." | Log error, preserve form state |
|
||||
| 429 | All | "Ivanti API rate limit reached. Please try again in a few minutes." | Log error, preserve form state |
|
||||
| 5xx | All | "Ivanti API is temporarily unavailable. Please try again later." | Log error, preserve form state |
|
||||
| Other | All | "Operation failed: {status} — {message}" | Log error with full response, preserve form state |
|
||||
|
||||
### Partial Failure (Attachment Upload)
|
||||
|
||||
When some attachment uploads succeed and others fail:
|
||||
- Response includes per-file success/failure details
|
||||
- Successfully uploaded files are recorded in `attachment_results_json`
|
||||
- Failed files are reported to the user with retry option
|
||||
- The submission record is updated with the successful uploads only
|
||||
|
||||
### Lifecycle Guard Errors
|
||||
|
||||
- Attempting to edit an "approved" submission returns 400: `"This submission is finalized and cannot be edited."`
|
||||
- Attempting an invalid status transition returns 400: `"Cannot transition from {current} to {new}."`
|
||||
|
||||
### Ownership Errors
|
||||
|
||||
- All edit endpoints verify `user_id` matches the authenticated user
|
||||
- Mismatch returns 403: `"You can only edit your own submissions."`
|
||||
|
||||
### Local Database Errors
|
||||
|
||||
- If history INSERT fails: log error, still return success (the Ivanti operation succeeded)
|
||||
- If audit log INSERT fails: fire-and-forget (existing `logAudit()` pattern)
|
||||
- If submission record UPDATE fails: return 500 with error message
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Property-Based Testing
|
||||
|
||||
Use `fast-check` as the property-based testing library. Each correctness property maps to a single property-based test with a minimum of 100 iterations.
|
||||
|
||||
Property tests focus on the new pure functions:
|
||||
- `mergeFindings(existingJson, newIds)` — Property 1
|
||||
- `validateLifecycleTransition(currentStatus, newStatus)` — Property 2
|
||||
|
||||
Tag format: **Feature: fp-submission-editing, Property {number}: {title}**
|
||||
|
||||
Test file: `backend/__tests__/fpSubmissionEditing.property.test.js`
|
||||
|
||||
### Unit Testing
|
||||
|
||||
Unit tests cover specific examples, edge cases, and integration points:
|
||||
|
||||
- **Validation reuse**: verify `validateFpWorkflowForm` is called correctly in the PUT endpoint
|
||||
- **Lifecycle badge styles**: verify each of the 5 statuses maps to the correct color scheme
|
||||
- **Clickable badge logic**: verify reworked/rejected/expired states produce clickable badges, requested/approved do not
|
||||
- **Ownership verification**: verify 403 when non-owner attempts edit
|
||||
- **Role guard**: verify non-Admin/Standard_User users are rejected
|
||||
- **Approved guard**: verify 400 when editing an approved submission
|
||||
- **Error mapping**: verify each Ivanti HTTP status maps to the correct error message
|
||||
- **History recording**: verify correct `change_type` and `change_details_json` for each operation type
|
||||
- **Migration idempotency**: verify migration can run multiple times without error
|
||||
|
||||
Test file: `backend/__tests__/fpSubmissionEditing.test.js`
|
||||
|
||||
### Integration Testing
|
||||
|
||||
Integration tests verify the full request/response cycle with mocked Ivanti API:
|
||||
|
||||
- GET submissions returns correct records for authenticated user
|
||||
- PUT update proxies to Ivanti and updates local record
|
||||
- POST findings maps to Ivanti and merges finding IDs
|
||||
- POST attachments uploads to Ivanti and updates attachment records
|
||||
- PATCH status updates lifecycle and creates history entry
|
||||
- Queue items marked complete after successful finding addition
|
||||
|
||||
Test file: `backend/__tests__/fpSubmissionEditing.integration.test.js`
|
||||
122
.kiro/specs/fp-submission-editing/requirements.md
Normal file
122
.kiro/specs/fp-submission-editing/requirements.md
Normal file
@@ -0,0 +1,122 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
This feature adds the ability to view, edit, and resubmit existing False Positive (FP) workflow submissions in the STEAM Security Dashboard. Users need to update FP workflows when assets or findings must be added, when supporting documentation needs to be supplemented, or when submissions are rejected or returned for rework by Ivanti reviewers. The feature introduces lifecycle status tracking for FP submissions, an edit modal that loads existing submission data, and backend endpoints that proxy update, map, and attach operations to the Ivanti API.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Dashboard**: The STEAM Security Dashboard application
|
||||
- **FP_Submission**: A local database record in the `ivanti_fp_submissions` table tracking a False Positive workflow submission, including its Ivanti workflow batch ID, form data, finding IDs, attachment history, and lifecycle status
|
||||
- **Ivanti_API**: The Ivanti/RiskSense REST API at https://platform4.risksense.com/api/v1, authenticated via x-api-key header
|
||||
- **Workflow_Batch**: An Ivanti API resource representing a group of findings submitted together under a single FP workflow request, identified by a numeric ID and a UUID
|
||||
- **Lifecycle_Status**: The current state of an FP submission in its review lifecycle: submitted, approved, rejected, rework, or resubmitted
|
||||
- **Edit_Modal**: The UI modal that loads an existing FP submission's data and allows the user to modify form fields, add findings, and upload additional attachments
|
||||
- **Submission_History**: A chronological log of changes made to an FP submission, including edits, finding additions, attachment uploads, and status transitions
|
||||
- **Queue_Panel**: The slide-out panel in the Reporting Page that displays the user's Ivanti todo queue items
|
||||
- **Workflow_Badge**: The colored status badge displayed in the Workflow column of the Reporting Page findings table, showing the workflow ID and state (e.g., "FP#12345 REWORKED"). States include: expired (red), rejected (red), reworked (amber), actionable (amber), requested (sky blue)
|
||||
- **Reporting_Table**: The findings table on the Reporting Page that displays host findings with columns including a Workflow column showing Workflow_Badges
|
||||
- **Ivanti_Update_Endpoint**: The Ivanti API endpoint `POST /workflowBatch/falsePositive/update` used to modify workflow batch metadata (name, reason, description, expiration date)
|
||||
- **Ivanti_Map_Endpoint**: The Ivanti API endpoint `POST /workflowBatch/falsePositive/{workflowBatchUuid}/map` used to add additional findings to an existing workflow batch
|
||||
- **Ivanti_Attach_Endpoint**: The Ivanti API endpoint `POST /workflowBatch/falsePositive/{workflowBatchUuid}/attach` used to upload additional file attachments to an existing workflow batch
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: View and Access Existing FP Submissions
|
||||
|
||||
**User Story:** As an editor or admin, I want to access my existing FP workflow submissions from the reporting table's workflow badges and from a submissions list, so that I can quickly identify and edit submissions that need attention.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL display a list of FP_Submissions for the authenticated user in the Queue_Panel, showing workflow name, Ivanti workflow batch ID, Lifecycle_Status, finding count, attachment count, and submission date
|
||||
2. WHEN the user clicks on an FP_Submission in the list, THE Dashboard SHALL open the Edit_Modal pre-populated with the submission's current data including form fields, associated finding IDs, and attachment history
|
||||
3. THE Dashboard SHALL visually distinguish FP_Submissions by Lifecycle_Status using color-coded status badges: submitted (sky blue), approved (emerald), rejected (red), rework (amber), resubmitted (sky blue)
|
||||
4. WHILE the user has the viewer role, THE Dashboard SHALL display the FP_Submission list in read-only mode with the edit action disabled
|
||||
5. WHEN a finding in the Reporting_Table has a Workflow_Badge with state "reworked", "rejected", or "expired", THE Dashboard SHALL render the Workflow_Badge as a clickable element with a pointer cursor and a subtle edit icon (pencil) appended to the badge
|
||||
6. WHEN the user clicks a clickable Workflow_Badge in the Reporting_Table, THE Dashboard SHALL look up the matching FP_Submission by the workflow batch ID displayed in the badge and open the Edit_Modal pre-populated with that submission's data
|
||||
7. WHEN the user hovers over a clickable Workflow_Badge, THE Dashboard SHALL display a hover effect (increased border opacity and slight background brightening) to indicate the badge is interactive
|
||||
8. WHILE a Workflow_Badge has state "requested" or "approved", THE Dashboard SHALL render the badge as non-interactive (no pointer cursor, no edit icon, no click handler) since those states do not require user action
|
||||
|
||||
### Requirement 2: Edit FP Workflow Form Fields
|
||||
|
||||
**User Story:** As an editor or admin, I want to update the name, reason, description, and expiration date of an existing FP submission, so that I can correct or supplement the justification when a submission is returned for rework.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Edit_Modal is opened for an existing FP_Submission, THE Dashboard SHALL load and display the current values for workflow name, reason, description, expiration date, and scope override authorization in editable form fields
|
||||
2. THE Dashboard SHALL apply the same validation rules to edited fields as the creation form: workflow name required and max 255 characters, reason required, description optional and max 2000 characters, expiration date required and must be a future date
|
||||
3. WHEN the user modifies form fields and clicks Save, THE Dashboard SHALL send the updated fields to the Ivanti_Update_Endpoint to modify the workflow batch metadata in the Ivanti platform
|
||||
4. IF the Ivanti_Update_Endpoint returns an error, THEN THE Dashboard SHALL display the error message and preserve the user's edits so the user can retry without re-entering data
|
||||
5. WHEN a form field update completes successfully, THE Dashboard SHALL update the local FP_Submission record with the new field values and record the change in Submission_History
|
||||
|
||||
### Requirement 3: Add Findings to Existing FP Submission
|
||||
|
||||
**User Story:** As an editor or admin, I want to add additional findings or assets to an existing FP submission, so that I can expand the scope of a false positive workflow when new related findings are identified.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Edit_Modal SHALL display the current list of finding IDs associated with the FP_Submission and provide a mechanism to add additional findings from the user's Ivanti queue
|
||||
2. WHEN the user selects additional FP-type queue items to add, THE Dashboard SHALL send the new finding IDs to the Ivanti_Map_Endpoint to map the findings to the existing Workflow_Batch
|
||||
3. WHEN findings are mapped successfully, THE Dashboard SHALL update the local FP_Submission record's finding_ids_json to include the newly added finding IDs
|
||||
4. WHEN findings are mapped successfully, THE Dashboard SHALL mark the corresponding queue items as complete and refresh the Queue_Panel
|
||||
5. IF the Ivanti_Map_Endpoint returns an error, THEN THE Dashboard SHALL display the error message and leave the queue items in their current status
|
||||
|
||||
### Requirement 4: Add Attachments to Existing FP Submission
|
||||
|
||||
**User Story:** As an editor or admin, I want to upload additional files and screenshots to an existing FP submission, so that I can provide supplementary evidence when reviewers request more documentation.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Edit_Modal SHALL display the list of previously uploaded attachments (filename and upload status) and provide a file upload area for adding new attachments
|
||||
2. THE Dashboard SHALL apply the same file constraints as the creation form: maximum 10 MB per file, allowed extensions .pdf, .png, .jpg, .jpeg, .gif, .doc, .docx, .xlsx, .csv, .txt, .zip
|
||||
3. WHEN the user uploads new files, THE Dashboard SHALL send each file to the Ivanti_Attach_Endpoint to attach the file to the existing Workflow_Batch
|
||||
4. WHEN an attachment upload completes successfully, THE Dashboard SHALL update the local FP_Submission record's attachment_count and attachment_results_json to include the new attachment
|
||||
5. IF an attachment upload fails, THEN THE Dashboard SHALL report which attachments failed and allow the user to retry the failed uploads without re-uploading successful attachments
|
||||
|
||||
### Requirement 5: FP Submission Lifecycle Status Tracking
|
||||
|
||||
**User Story:** As an editor or admin, I want the Dashboard to track the lifecycle status of my FP submissions, so that I can see which submissions are pending review, approved, rejected, or need rework.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL store a Lifecycle_Status field for each FP_Submission with allowed values: submitted, approved, rejected, rework, resubmitted
|
||||
2. WHEN a new FP workflow is created, THE Dashboard SHALL set the initial Lifecycle_Status to "submitted"
|
||||
3. WHEN the user manually updates the Lifecycle_Status of an FP_Submission (e.g., marking it as rejected or rework after receiving notification), THE Dashboard SHALL record the status change with a timestamp in Submission_History
|
||||
4. WHEN an FP_Submission with Lifecycle_Status "rejected" or "rework" is edited and resubmitted, THE Dashboard SHALL update the Lifecycle_Status to "resubmitted"
|
||||
5. THE Dashboard SHALL prevent editing of FP_Submissions with Lifecycle_Status "approved" and display a message indicating the submission is finalized
|
||||
|
||||
### Requirement 6: Submission History and Audit Trail
|
||||
|
||||
**User Story:** As an editor or admin, I want to see a history of changes made to an FP submission, so that I can track what was modified and when for audit purposes.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Edit_Modal SHALL display a Submission_History section showing a chronological list of changes made to the FP_Submission, including: initial creation, form field edits, finding additions, attachment uploads, and status transitions
|
||||
2. WHEN any modification is made to an FP_Submission, THE Dashboard SHALL log an audit entry with action "ivanti_fp_submission_edited", entity type "ivanti_workflow", the workflow batch ID as entity ID, and details including the type of change and changed values
|
||||
3. WHEN a Lifecycle_Status transition occurs, THE Dashboard SHALL log an audit entry with action "ivanti_fp_status_changed", entity type "ivanti_workflow", and details including the previous status and new status
|
||||
|
||||
### Requirement 7: Backend API Endpoints for FP Editing
|
||||
|
||||
**User Story:** As a system component, the backend needs API endpoints to retrieve, update, and extend existing FP submissions, so that the frontend can perform edit operations securely.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL provide a GET /api/ivanti/fp-submissions endpoint that returns the authenticated user's FP_Submission records with all stored fields and Lifecycle_Status
|
||||
2. THE Dashboard SHALL provide a PUT /api/ivanti/fp-submissions/:id endpoint that accepts updated form fields, validates the input, proxies the update to the Ivanti_Update_Endpoint, and updates the local record
|
||||
3. THE Dashboard SHALL provide a POST /api/ivanti/fp-submissions/:id/findings endpoint that accepts additional finding IDs, proxies the map operation to the Ivanti_Map_Endpoint, and updates the local record
|
||||
4. THE Dashboard SHALL provide a POST /api/ivanti/fp-submissions/:id/attachments endpoint that accepts file uploads, proxies each file to the Ivanti_Attach_Endpoint, and updates the local record
|
||||
5. THE Dashboard SHALL provide a PATCH /api/ivanti/fp-submissions/:id/status endpoint that accepts a new Lifecycle_Status value and updates the local record with the status transition
|
||||
6. THE Dashboard SHALL restrict all FP submission editing endpoints to users with "Admin" or "Standard_User" group membership
|
||||
7. THE Dashboard SHALL verify that the authenticated user owns the FP_Submission before allowing any edit operation, returning a 403 status if ownership verification fails
|
||||
|
||||
### Requirement 8: Database Schema Updates for Editing Support
|
||||
|
||||
**User Story:** As a system component, the database needs additional fields and tables to support FP submission editing, lifecycle tracking, and change history.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL add a lifecycle_status column to the ivanti_fp_submissions table with allowed values: submitted, approved, rejected, rework, resubmitted, defaulting to "submitted"
|
||||
2. THE Dashboard SHALL add an ivanti_workflow_batch_uuid column to the ivanti_fp_submissions table to store the UUID required by the Ivanti map and attach endpoints
|
||||
3. THE Dashboard SHALL add an updated_at column to the ivanti_fp_submissions table that is set to the current timestamp on each modification
|
||||
4. THE Dashboard SHALL create an ivanti_fp_submission_history table with columns: id, submission_id (foreign key), user_id, username, change_type, change_details_json, and created_at
|
||||
5. THE Dashboard SHALL provide a migration script at backend/migrations/add_fp_submission_editing.js that applies the schema changes idempotently
|
||||
182
.kiro/specs/fp-submission-editing/tasks.md
Normal file
182
.kiro/specs/fp-submission-editing/tasks.md
Normal file
@@ -0,0 +1,182 @@
|
||||
# Implementation Plan: FP Submission Editing
|
||||
|
||||
## Overview
|
||||
|
||||
Extends the existing FP workflow system with lifecycle status tracking, edit/resubmit capabilities, and a submission history audit trail. Implementation proceeds bottom-up: database migration → pure helpers → backend endpoints → frontend components → wiring and integration.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Database migration and schema changes
|
||||
- [x] 1.1 Create migration script `backend/migrations/add_fp_submission_editing.js`
|
||||
- Add `lifecycle_status` column to `ivanti_fp_submissions` with CHECK constraint and default `'submitted'`
|
||||
- Add `ivanti_workflow_batch_uuid` TEXT column to `ivanti_fp_submissions`
|
||||
- Add `updated_at` DATETIME column to `ivanti_fp_submissions` with default CURRENT_TIMESTAMP
|
||||
- Create `ivanti_fp_submission_history` table with columns: id, submission_id (FK), user_id, username, change_type (CHECK constraint), change_details_json, created_at
|
||||
- Create index `idx_fp_history_submission` on submission_id
|
||||
- Wrap ALTER TABLE statements in try/catch for idempotency; use CREATE TABLE IF NOT EXISTS / CREATE INDEX IF NOT EXISTS
|
||||
- _Requirements: 8.1, 8.2, 8.3, 8.4, 8.5_
|
||||
|
||||
- [x] 2. Implement pure helper functions in `backend/routes/ivantiFpWorkflow.js`
|
||||
- [x] 2.1 Implement `validateLifecycleTransition(currentStatus, newStatus)`
|
||||
- Accept two status strings from the set {submitted, approved, rejected, rework, resubmitted}
|
||||
- Return `{ valid: false, error }` when currentStatus is `'approved'` (finalized, no transitions allowed)
|
||||
- Return `{ valid: false, error }` when newStatus is not in the allowed set
|
||||
- Return `{ valid: true }` for all other valid transitions
|
||||
- Export from module for testing
|
||||
- _Requirements: 5.4, 5.5_
|
||||
|
||||
- [x] 2.2 Implement `mergeFindings(existingJson, newIds)`
|
||||
- Parse existingJson (JSON array of strings), concatenate with newIds array
|
||||
- Deduplicate by converting to Set, return JSON.stringify of the merged array
|
||||
- Handle edge cases: empty existing array, empty newIds, overlapping IDs
|
||||
- Export from module for testing
|
||||
- _Requirements: 3.3_
|
||||
|
||||
- [x] 2.3 Implement `buildSubmissionHistoryEntry(changeType, details, userId, username)`
|
||||
- Construct and return an object with: submission_id (to be set by caller), user_id, username, change_type, change_details_json (JSON.stringify of details), created_at (ISO string)
|
||||
- Export from module for testing
|
||||
- _Requirements: 6.1, 6.2_
|
||||
|
||||
- [ ]* 2.4 Write property test for `mergeFindings` — Property 1: Finding Merge Preserves All IDs and Deduplicates
|
||||
- **Property 1: Finding Merge Preserves All IDs and Deduplicates**
|
||||
- **Validates: Requirements 3.3**
|
||||
- Use fast-check to generate arbitrary arrays of string IDs for existing and new
|
||||
- Assert: parsed result contains every ID from both inputs, no duplicates, length ≤ sum of input lengths
|
||||
- Test file: `backend/__tests__/fpSubmissionEditing.property.test.js`
|
||||
|
||||
- [ ]* 2.5 Write property test for `validateLifecycleTransition` — Property 2: Lifecycle Transition Validation
|
||||
- **Property 2: Lifecycle Transition Validation**
|
||||
- **Validates: Requirements 5.4, 5.5**
|
||||
- Use fast-check to generate pairs from {submitted, approved, rejected, rework, resubmitted}
|
||||
- Assert: always invalid when currentStatus is 'approved'; always valid for other currentStatus values with valid newStatus; rejected/rework → resubmitted is always valid
|
||||
- Test file: `backend/__tests__/fpSubmissionEditing.property.test.js`
|
||||
|
||||
- [ ] 3. Checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 4. Implement backend API endpoints in `backend/routes/ivantiFpWorkflow.js`
|
||||
- [x] 4.1 Implement `GET /api/ivanti/fp-submissions`
|
||||
- Add route with `requireAuth(db)` — any authenticated user
|
||||
- Query `ivanti_fp_submissions` filtered by `req.user.id`
|
||||
- Return JSON array of submission records including lifecycle_status and updated_at
|
||||
- _Requirements: 7.1, 1.1_
|
||||
|
||||
- [x] 4.2 Implement `PUT /api/ivanti/fp-submissions/:id`
|
||||
- Add route with `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Verify ownership (user_id match → 403 if not)
|
||||
- Lifecycle guard: reject if lifecycle_status is 'approved' → 400
|
||||
- Validate body with existing `validateFpWorkflowForm`
|
||||
- Proxy to Ivanti update endpoint via `ivantiPost()`
|
||||
- On success: UPDATE local record fields + updated_at, INSERT history row (change_type: 'fields_updated'), log audit
|
||||
- If previous status was 'rejected' or 'rework', set lifecycle_status to 'resubmitted'
|
||||
- _Requirements: 7.2, 2.1, 2.2, 2.3, 2.4, 2.5, 5.4, 5.5, 7.6, 7.7_
|
||||
|
||||
- [x] 4.3 Implement `POST /api/ivanti/fp-submissions/:id/findings`
|
||||
- Add route with `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Verify ownership, lifecycle guard (reject if approved)
|
||||
- Validate findingIds and queueItemIds from body; verify queue items belong to user, are FP type, and pending
|
||||
- Proxy to Ivanti map endpoint via `ivantiFormPost()` using `buildSubjectFilterRequest`
|
||||
- On success: merge finding IDs with `mergeFindings()`, mark queue items complete, INSERT history + audit
|
||||
- _Requirements: 7.3, 3.1, 3.2, 3.3, 3.4, 3.5_
|
||||
|
||||
- [x] 4.4 Implement `POST /api/ivanti/fp-submissions/:id/attachments`
|
||||
- Add route with `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`, Multer middleware
|
||||
- Verify ownership, lifecycle guard (reject if approved)
|
||||
- Validate file constraints (10 MB, allowed extensions)
|
||||
- Loop each file: call `ivantiMultipartPost()` to Ivanti attach endpoint
|
||||
- Collect per-file success/failure results
|
||||
- Update attachment_count and attachment_results_json, INSERT history + audit
|
||||
- _Requirements: 7.4, 4.1, 4.2, 4.3, 4.4, 4.5_
|
||||
|
||||
- [x] 4.5 Implement `PATCH /api/ivanti/fp-submissions/:id/status`
|
||||
- Add route with `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Verify ownership
|
||||
- Validate new status is in allowed set
|
||||
- Use `validateLifecycleTransition()` to check transition validity
|
||||
- UPDATE lifecycle_status and updated_at, INSERT history row (change_type: 'status_changed'), log audit
|
||||
- _Requirements: 7.5, 5.1, 5.2, 5.3, 7.6, 7.7_
|
||||
|
||||
- [ ]* 4.6 Write unit tests for backend endpoints
|
||||
- Test ownership verification returns 403 for non-owner
|
||||
- Test lifecycle guard returns 400 for approved submissions
|
||||
- Test role guard rejects non-Admin/Standard_User
|
||||
- Test Ivanti error status mapping (401, 419, 429, 5xx)
|
||||
- Test history recording produces correct change_type and change_details_json
|
||||
- Test migration idempotency (can run multiple times without error)
|
||||
- Test file: `backend/__tests__/fpSubmissionEditing.test.js`
|
||||
- _Requirements: 7.6, 7.7, 5.5_
|
||||
|
||||
- [ ]* 4.7 Write integration tests for backend endpoints
|
||||
- Test GET returns correct records for authenticated user
|
||||
- Test PUT proxies to Ivanti and updates local record
|
||||
- Test POST findings maps to Ivanti and merges finding IDs
|
||||
- Test POST attachments uploads to Ivanti and updates attachment records
|
||||
- Test PATCH status updates lifecycle and creates history entry
|
||||
- Test queue items marked complete after successful finding addition
|
||||
- Test file: `backend/__tests__/fpSubmissionEditing.integration.test.js`
|
||||
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5_
|
||||
|
||||
- [ ] 5. Checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 6. Register new endpoints in `backend/server.js`
|
||||
- Wire the updated `ivantiFpWorkflow` router so the new GET/PUT/POST/PATCH routes are accessible under `/api/ivanti/fp-submissions`
|
||||
- Verify the existing POST `/api/ivanti/fp-workflow` route continues to work
|
||||
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5_
|
||||
|
||||
- [x] 7. Implement frontend components in `frontend/src/components/pages/ReportingPage.js`
|
||||
- [x] 7.1 Implement `lifecycleStatusBadge(status)` helper function
|
||||
- Return inline style object with border, background, and text color per status
|
||||
- Color mapping: submitted/resubmitted (sky blue), approved (emerald), rejected (red), rework (amber)
|
||||
- _Requirements: 1.3_
|
||||
|
||||
- [x] 7.2 Implement `FpEditModal` component
|
||||
- Props: open, onClose, submission, queueItems, onSuccess
|
||||
- State: form fields initialized from submission, activeTab, saving, errors, result
|
||||
- Tab bar with 4 tabs: Details, Findings, Attachments, History
|
||||
- Details tab: editable form fields (name, reason, description, expirationDate, scopeOverride) with Save button; calls PUT endpoint
|
||||
- Findings tab: read-only current finding IDs list + mechanism to select and add FP queue items; calls POST findings endpoint
|
||||
- Attachments tab: existing attachments list + file upload area; calls POST attachments endpoint
|
||||
- History tab: chronological list fetched from submission history (included in GET response or separate query)
|
||||
- Approved submissions: all fields read-only with finalized message
|
||||
- Dark tactical theme matching existing FpWorkflowModal
|
||||
- _Requirements: 1.2, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2, 3.4, 3.5, 4.1, 4.2, 4.3, 4.4, 4.5, 5.5, 6.1_
|
||||
|
||||
- [x] 7.3 Modify workflow badge renderer for clickable badges
|
||||
- In the workflow column renderer (~lines 1044–1070), for badges with state reworked/rejected/expired:
|
||||
- Add `cursor: 'pointer'` and `onClick` handler
|
||||
- Append pencil icon (lucide `Edit3`, 10px) after state text
|
||||
- On hover: increase border opacity and brighten background
|
||||
- On click: look up matching FP_Submission by workflow batch ID, open FpEditModal
|
||||
- For badges with state requested/approved: no changes (remain non-interactive)
|
||||
- _Requirements: 1.5, 1.6, 1.7, 1.8_
|
||||
|
||||
- [x] 7.4 Add submissions list section to QueuePanel
|
||||
- Fetch submissions via GET /api/ivanti/fp-submissions on panel open
|
||||
- Display each submission: workflow name, batch ID, lifecycle status badge, finding count, created date
|
||||
- Clicking a submission row opens FpEditModal with that submission's data
|
||||
- Viewers see the list but cannot click to edit
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4_
|
||||
|
||||
- [x] 8. Wire frontend state and data flow
|
||||
- [x] 8.1 Add submissions state and fetch logic to ReportingPage
|
||||
- Add state for submissions array and selected submission
|
||||
- Fetch submissions on page load and after successful edits (onSuccess callback)
|
||||
- Pass submissions and queueItems to FpEditModal and QueuePanel
|
||||
- _Requirements: 1.1, 1.2_
|
||||
|
||||
- [x] 8.2 Connect FpEditModal callbacks to refresh data
|
||||
- On successful edit/findings/attachments/status change, call onSuccess to refresh submissions list, queue items, and reporting table data
|
||||
- _Requirements: 2.5, 3.4, 4.4, 5.3_
|
||||
|
||||
- [ ] 9. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests validate universal correctness properties from the design document
|
||||
- The project uses plain JavaScript (no TypeScript) — all code should follow existing conventions
|
||||
- All new endpoints follow the existing factory-pattern router in `ivantiFpWorkflow.js`
|
||||
0
.kiro/specs/group-based-access-control/design.md
Normal file
0
.kiro/specs/group-based-access-control/design.md
Normal file
143
.kiro/specs/group-based-access-control/requirements.md
Normal file
143
.kiro/specs/group-based-access-control/requirements.md
Normal file
@@ -0,0 +1,143 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
Replace the existing simple role-based access control system (admin/editor/viewer) with a group-based access control model. The system supports exactly four user groups (Admin, Standard User, Leadership, Read Only) with distinct permission boundaries. This change affects the database schema, backend middleware, API endpoint authorization, frontend conditional rendering, and the admin panel user management interface.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Dashboard**: The STEAM Security Dashboard application comprising a React frontend and Express backend
|
||||
- **Group**: One of four access control categories (Admin, Standard_User, Leadership, Read_Only) that determines a user's permissions
|
||||
- **Admin_Group**: The group with full CRUD access to all resources, user management, and admin panel access
|
||||
- **Standard_User_Group**: The working group with view-all, create, edit, and conditional delete permissions plus basic export
|
||||
- **Leadership_Group**: The read-only group with additional export capabilities for reports, compliance documents, and visualizations
|
||||
- **Read_Only_Group**: The view-only group with no create, edit, delete, or export capabilities
|
||||
- **Permission_Middleware**: Backend Express middleware that validates a user's group membership before allowing an API action
|
||||
- **Cascade_Impact**: The set of associated Archer tickets, JIRA tickets, and documents that would be deleted when a CVE is deleted
|
||||
- **Compliance_Link**: An association between a ticket (Archer or JIRA) and a compliance report that blocks Standard_User deletion
|
||||
- **Group_Migration**: The database migration that replaces the role field with a group field and maps existing users
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Group Data Model
|
||||
|
||||
**User Story:** As a system administrator, I want the user model to reference one of four defined groups instead of the legacy role field, so that permissions are enforced through a well-defined group structure.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL store exactly four groups: Admin, Standard_User, Leadership, and Read_Only
|
||||
2. THE Dashboard SHALL assign each user to exactly one group via a group field on the user record
|
||||
3. WHEN a user record is created, THE Dashboard SHALL default the group to Read_Only
|
||||
4. THE Dashboard SHALL enforce a foreign key or CHECK constraint so that the group field only accepts valid group values
|
||||
|
||||
### Requirement 2: Group Migration
|
||||
|
||||
**User Story:** As a system administrator, I want existing users to be automatically mapped from the old role system to the new group system, so that no manual re-assignment is needed after the upgrade.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the migration runs, THE Group_Migration SHALL map users with role "admin" to Admin_Group
|
||||
2. WHEN the migration runs, THE Group_Migration SHALL map users with role "editor" to Standard_User_Group
|
||||
3. WHEN the migration runs, THE Group_Migration SHALL map users with role "viewer" to Read_Only_Group
|
||||
4. WHEN the migration runs, THE Group_Migration SHALL remove the CHECK constraint on the old role column and replace it with the new group field
|
||||
5. IF a user record has no role value or an unrecognized role value, THEN THE Group_Migration SHALL assign that user to Read_Only_Group
|
||||
|
||||
### Requirement 3: Backend Permission Enforcement
|
||||
|
||||
**User Story:** As a security-conscious developer, I want every API endpoint to check the requesting user's group before allowing the action, so that permissions are enforced server-side and cannot be bypassed through direct API calls.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Permission_Middleware SHALL replace the existing requireRole middleware with a requireGroup middleware that accepts one or more group names
|
||||
2. WHEN an unauthenticated request reaches a protected endpoint, THE Permission_Middleware SHALL return HTTP 401
|
||||
3. WHEN an authenticated user's group is not in the allowed groups for an endpoint, THE Permission_Middleware SHALL return HTTP 403
|
||||
4. THE Permission_Middleware SHALL attach the user's group to the request object for downstream route handlers to use
|
||||
5. WHEN a Standard_User_Group user attempts to delete a resource they did not create, THE Dashboard SHALL return HTTP 403
|
||||
6. WHEN a Standard_User_Group user attempts to delete a finding that is marked as resolved or closed, THE Dashboard SHALL return HTTP 403
|
||||
7. WHEN a Standard_User_Group user attempts to delete a ticket that is linked to a compliance report, THE Dashboard SHALL return HTTP 403
|
||||
8. WHEN a Standard_User_Group user attempts to delete a CVE they created, THE Dashboard SHALL check for Cascade_Impact and return the list of associated Archer tickets, JIRA tickets, and documents
|
||||
9. IF any ticket in the Cascade_Impact is linked to a compliance report, THEN THE Dashboard SHALL block the CVE deletion and return HTTP 403 with a message indicating Admin-only deletion is required
|
||||
10. WHEN an Admin_Group user performs any CRUD operation, THE Dashboard SHALL allow the operation without ownership or state restrictions
|
||||
|
||||
### Requirement 4: Admin Group Permissions
|
||||
|
||||
**User Story:** As an admin, I want full unrestricted access to all resources and management functions, so that I can manage the entire system without limitations.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL allow Admin_Group users to create, read, update, and delete all resources (CVEs, findings, tickets, comments, compliance reports)
|
||||
2. THE Dashboard SHALL allow Admin_Group users to access the admin panel
|
||||
3. THE Dashboard SHALL allow Admin_Group users to manage users and assign users to groups
|
||||
4. THE Dashboard SHALL allow Admin_Group users to export all data
|
||||
5. THE Dashboard SHALL allow Admin_Group users to delete any resource regardless of ownership, state, or compliance linkage
|
||||
|
||||
### Requirement 5: Standard User Group Permissions
|
||||
|
||||
**User Story:** As a standard user, I want to view all data and create/edit resources while having controlled delete access, so that I can do my daily work without accidentally removing critical linked data.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL allow Standard_User_Group users to view all data across the dashboard
|
||||
2. THE Dashboard SHALL allow Standard_User_Group users to create and edit CVEs, findings, tickets, and comments
|
||||
3. THE Dashboard SHALL allow Standard_User_Group users to delete their own findings, tickets, and comments subject to state and linkage restrictions
|
||||
4. WHEN a Standard_User_Group user attempts to delete a finding that is resolved or closed, THE Dashboard SHALL reject the deletion
|
||||
5. WHEN a Standard_User_Group user attempts to delete a ticket linked to a compliance report, THE Dashboard SHALL reject the deletion
|
||||
6. WHEN a Standard_User_Group user attempts to delete a CVE they created, THE Dashboard SHALL display a warning listing associated Archer tickets, JIRA tickets, and documents that will be cascade-deleted
|
||||
7. IF any associated ticket in the cascade is linked to a compliance report, THEN THE Dashboard SHALL block the CVE deletion entirely
|
||||
8. THE Dashboard SHALL allow Standard_User_Group users to perform basic exports (CSV and XLSX of CVEs and findings)
|
||||
|
||||
### Requirement 6: Leadership Group Permissions
|
||||
|
||||
**User Story:** As a leadership user, I want read-only access with export capabilities, so that I can review data and generate reports without risk of modifying records.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL allow Leadership_Group users to view all data across the dashboard
|
||||
2. THE Dashboard SHALL allow Leadership_Group users to export reports, compliance documents, and graph visualizations
|
||||
3. THE Dashboard SHALL prevent Leadership_Group users from creating, editing, or deleting any records
|
||||
4. THE Dashboard SHALL prevent Leadership_Group users from accessing the admin panel
|
||||
|
||||
### Requirement 7: Read Only Group Permissions
|
||||
|
||||
**User Story:** As a read-only user, I want view-only access to the dashboard, so that I can see data without any ability to modify or export it.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL allow Read_Only_Group users to view all data across the dashboard
|
||||
2. THE Dashboard SHALL prevent Read_Only_Group users from creating, editing, or deleting any records
|
||||
3. THE Dashboard SHALL prevent Read_Only_Group users from exporting any data
|
||||
4. THE Dashboard SHALL prevent Read_Only_Group users from accessing the admin panel
|
||||
|
||||
### Requirement 8: Admin Panel Group Management
|
||||
|
||||
**User Story:** As an admin, I want to view all users with their current group and reassign groups through the admin panel, so that I can manage access control centrally.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN an Admin_Group user opens the user management section, THE Dashboard SHALL display all users with their current group assignment
|
||||
2. WHEN an Admin_Group user changes a user's group, THE Dashboard SHALL update the group assignment and persist it to the database
|
||||
3. WHEN an Admin_Group user changes a user's group, THE Dashboard SHALL display a confirmation dialog before applying the change
|
||||
4. WHEN an Admin_Group user downgrades another Admin_Group user, THE Dashboard SHALL display an additional warning in the confirmation dialog
|
||||
5. THE Dashboard SHALL prevent an Admin_Group user from changing their own group to a non-Admin group
|
||||
|
||||
### Requirement 9: Audit Logging for Group Changes
|
||||
|
||||
**User Story:** As a system administrator, I want all group assignment changes to be logged with full context, so that I can audit who changed access for whom and when.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a user's group is changed, THE Dashboard SHALL log the change with the acting user's ID, the target user's ID, the previous group, the new group, and a timestamp
|
||||
2. THE Dashboard SHALL preserve existing audit trail behavior for all CRUD operations performed under the new group system
|
||||
3. WHEN a group change is logged, THE Dashboard SHALL record the IP address of the acting user
|
||||
|
||||
### Requirement 10: Frontend Conditional Rendering
|
||||
|
||||
**User Story:** As a user, I want the UI to show only the actions available to my group, so that I have a clear and uncluttered interface matching my permissions.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL conditionally render create, edit, and delete buttons based on the current user's group
|
||||
2. THE Dashboard SHALL conditionally render export options based on the current user's group
|
||||
3. THE Dashboard SHALL conditionally render the admin panel link based on the current user's group
|
||||
4. WHEN a Standard_User_Group user views a resource they did not create, THE Dashboard SHALL hide the delete button for that resource
|
||||
5. THE Dashboard SHALL replace the existing role-based helper functions (hasRole, canWrite, isAdmin) with group-based equivalents (isInGroup, canWrite, canDelete, canExport, isAdmin)
|
||||
279
.kiro/specs/group-based-access-control/tasks.md
Normal file
279
.kiro/specs/group-based-access-control/tasks.md
Normal file
@@ -0,0 +1,279 @@
|
||||
# Implementation Plan: Group-Based Access Control
|
||||
|
||||
## Overview
|
||||
|
||||
Replace the existing role-based access control (admin/editor/viewer) with a four-group model (Admin, Standard_User, Leadership, Read_Only). This touches the database schema, backend middleware, all route authorization, frontend permission helpers, and the admin panel UI. Tasks build incrementally: migration first, then middleware, then routes, then frontend.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [ ] 1. Create database migration for user groups
|
||||
- [x] 1.1 Create `backend/migrations/add_user_groups.js` migration script
|
||||
- Add `user_group` column (VARCHAR(20), NOT NULL, DEFAULT 'Read_Only') to users table
|
||||
- Map existing role values: admin to Admin, editor to Standard_User, viewer to Read_Only
|
||||
- Map NULL or unrecognized role values to Read_Only
|
||||
- Add CHECK constraint: user_group IN ('Admin', 'Standard_User', 'Leadership', 'Read_Only')
|
||||
- Add index `idx_users_user_group` on user_group column
|
||||
- Use idempotent checks so migration is safe to run multiple times
|
||||
- Follow existing migration pattern: open db, db.serialize(), log progress, close db
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 2.1, 2.2, 2.3, 2.4, 2.5_
|
||||
|
||||
- [ ]* 1.2 Write property test for migration role mapping
|
||||
- **Property 8: Migration maps all role values correctly**
|
||||
- Generate users with random roles from {admin, editor, viewer, NULL, arbitrary}, run migration against in-memory SQLite, verify mapping
|
||||
- **Validates: Requirements 2.1, 2.2, 2.3, 2.5**
|
||||
|
||||
- [ ]* 1.3 Write property test for migration idempotency
|
||||
- **Property 9: Migration is idempotent**
|
||||
- Run migration N times (N in 1-5) against in-memory SQLite, verify schema and data identical each time
|
||||
- **Validates: Requirements 2.4**
|
||||
|
||||
- [ ] 1.4 Write unit tests for migration
|
||||
- Test column creation with correct CHECK constraint
|
||||
- Test role mapping: admin to Admin, editor to Standard_User, viewer to Read_Only
|
||||
- Test NULL and unrecognized role handling defaults to Read_Only
|
||||
- Test new user defaults to Read_Only group
|
||||
- _Requirements: 1.3, 1.4, 2.1, 2.2, 2.3, 2.5_
|
||||
|
||||
- [ ] 2. Update auth middleware to use groups
|
||||
- [x] 2.1 Update `requireAuth` in `backend/middleware/auth.js`
|
||||
- Modify session join query to SELECT user_group and attach as req.user.group
|
||||
- _Requirements: 3.4_
|
||||
|
||||
- [x] 2.2 Add `requireGroup` middleware function
|
||||
- Accept spread of allowed group names
|
||||
- Return 401 if req.user is missing
|
||||
- Return 403 with error details if user group not in allowed set
|
||||
- Call next() if group is allowed
|
||||
- _Requirements: 3.1, 3.2, 3.3_
|
||||
|
||||
- [x] 2.3 Remove `requireRole` and export `requireGroup`
|
||||
- Remove requireRole function and its export
|
||||
- Export requireGroup in its place
|
||||
- _Requirements: 3.1_
|
||||
|
||||
- [ ]* 2.4 Write property test for group constraint
|
||||
- **Property 1: Group constraint rejects invalid values**
|
||||
- Generate random strings not in valid group set, attempt DB insert, verify constraint error
|
||||
- **Validates: Requirements 1.1, 1.4**
|
||||
|
||||
- [ ]* 2.5 Write property test for requireGroup
|
||||
- **Property 3: requireGroup rejects unauthorized groups**
|
||||
- Generate random group and allowedGroups pairs where group is not in allowed set, verify 403
|
||||
- **Validates: Requirements 3.3**
|
||||
|
||||
- [ ] 2.6 Write unit tests for requireGroup middleware
|
||||
- Test 401 for unauthenticated requests
|
||||
- Test 403 for wrong group
|
||||
- Test group attached to req.user
|
||||
- Test next() called for allowed group
|
||||
- _Requirements: 3.2, 3.3, 3.4_
|
||||
|
||||
- [x] 3. Checkpoint: Verify migration and middleware
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [ ] 4. Update auth routes to return group
|
||||
- [x] 4.1 Update login endpoint in `backend/routes/auth.js`
|
||||
- Return group (from user_group) instead of role in user response object
|
||||
- Update audit log details to log group instead of role
|
||||
- _Requirements: 3.4, 9.2_
|
||||
|
||||
- [x] 4.2 Update me endpoint in `backend/routes/auth.js`
|
||||
- Return group instead of role in user response object
|
||||
- _Requirements: 3.4_
|
||||
|
||||
- [ ] 5. Update user management routes
|
||||
- [x] 5.1 Switch `backend/routes/users.js` to use requireGroup
|
||||
- Replace requireRole('admin') with requireGroup('Admin')
|
||||
- _Requirements: 4.2, 4.3_
|
||||
|
||||
- [x] 5.2 Update GET endpoints to return user_group
|
||||
- Return user_group instead of role in user records
|
||||
- _Requirements: 8.1_
|
||||
|
||||
- [x] 5.3 Update POST create user to accept group param
|
||||
- Validate group against valid values
|
||||
- Default to Read_Only if not provided
|
||||
- Return 400 for invalid group values
|
||||
- _Requirements: 1.3, 8.2_
|
||||
|
||||
- [x] 5.4 Update PATCH update user to accept group param
|
||||
- Validate group against valid values
|
||||
- Prevent admin self-demotion (return 400)
|
||||
- _Requirements: 8.2, 8.5_
|
||||
|
||||
- [x] 5.5 Add audit logging for group changes
|
||||
- Log acting user ID, target user ID, previous group, new group, IP address, timestamp
|
||||
- _Requirements: 9.1, 9.3_
|
||||
|
||||
- [ ]* 5.6 Write property test for user group validity
|
||||
- **Property 2: Every user has exactly one valid group**
|
||||
- Generate random user sets, query all users, verify each has exactly one valid group
|
||||
- **Validates: Requirements 1.2**
|
||||
|
||||
- [ ] 5.7 Write unit tests for user management group logic
|
||||
- Test group validation rejects invalid values
|
||||
- Test self-demotion prevention
|
||||
- Test audit logging includes all required fields
|
||||
- _Requirements: 8.2, 8.5, 9.1, 9.3_
|
||||
|
||||
- [ ] 6. Update backend route authorization across all routes
|
||||
- [x] 6.1 Update `backend/routes/auditLog.js`
|
||||
- Replace requireRole('admin') with requireGroup('Admin')
|
||||
- _Requirements: 4.2_
|
||||
|
||||
- [x] 6.2 Update `backend/routes/archerTickets.js`
|
||||
- Use requireGroup('Admin', 'Standard_User') for create, update, delete
|
||||
- _Requirements: 5.2_
|
||||
|
||||
- [x] 6.3 Update `backend/routes/knowledgeBase.js`
|
||||
- Use requireGroup('Admin', 'Standard_User') for upload and delete
|
||||
- _Requirements: 5.2_
|
||||
|
||||
- [x] 6.4 Update `backend/routes/ivantiFindings.js`
|
||||
- Use requireGroup('Admin', 'Standard_User') for override endpoint
|
||||
- _Requirements: 5.2_
|
||||
|
||||
- [x] 6.5 Update `backend/routes/compliance.js`
|
||||
- Use requireGroup('Admin', 'Standard_User') for preview and commit
|
||||
- _Requirements: 5.2_
|
||||
|
||||
- [x] 6.6 Update `backend/server.js` inline CVE routes
|
||||
- Use requireGroup('Admin', 'Standard_User') for POST, PUT, PATCH, DELETE
|
||||
- _Requirements: 5.2_
|
||||
|
||||
- [x] 6.7 Update `backend/server.js` route mounting
|
||||
- Pass requireGroup instead of requireRole to route factories
|
||||
- _Requirements: 3.1_
|
||||
|
||||
- [ ]* 6.8 Write property test for Leadership restrictions
|
||||
- **Property 5: Leadership cannot mutate any resource**
|
||||
- Generate random mutation requests as Leadership, verify 403
|
||||
- **Validates: Requirements 6.3**
|
||||
|
||||
- [ ]* 6.9 Write property test for Read_Only restrictions
|
||||
- **Property 6: Read_Only cannot mutate or export**
|
||||
- Generate random mutation and export requests as Read_Only, verify 403
|
||||
- **Validates: Requirements 7.2, 7.3**
|
||||
|
||||
- [x] 7. Checkpoint: Verify backend route authorization
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [ ] 8. Implement Standard User conditional delete logic
|
||||
- [x] 8.1 Add created_by column tracking
|
||||
- Add created_by to CVE, finding, and ticket creation endpoints storing req.user.id on insert
|
||||
- _Requirements: 3.5_
|
||||
|
||||
- [x] 8.2 Implement ownership check for CVE delete
|
||||
- Standard_User can only delete CVEs they created
|
||||
- Return 403 if not owner
|
||||
- _Requirements: 3.5_
|
||||
|
||||
- [x] 8.3 Implement cascade impact check for CVE delete
|
||||
- Query associated Archer tickets and documents
|
||||
- Check compliance linkage on cascaded tickets
|
||||
- Return cascade_impact response schema
|
||||
- Block deletion if any cascaded ticket is compliance-linked
|
||||
- _Requirements: 3.8, 3.9_
|
||||
|
||||
- [x] 8.4 Implement state check for finding delete
|
||||
- Standard_User cannot delete resolved or closed findings
|
||||
- Return 403 with appropriate error message
|
||||
- _Requirements: 3.6_
|
||||
|
||||
- [x] 8.5 Implement compliance linkage check for ticket delete
|
||||
- Standard_User cannot delete tickets linked to compliance reports
|
||||
- Return 403 with appropriate error message
|
||||
- _Requirements: 3.7_
|
||||
|
||||
- [x] 8.6 Ensure Admin bypasses all delete restrictions
|
||||
- Admin group skips ownership, state, and compliance checks
|
||||
- _Requirements: 3.10, 4.5_
|
||||
|
||||
- [ ]* 8.7 Write property test for Admin delete bypass
|
||||
- **Property 4: Admin bypasses all delete restrictions**
|
||||
- Generate resources with random ownership, state, compliance linkage, delete as Admin, verify success
|
||||
- **Validates: Requirements 3.10, 4.1, 4.5**
|
||||
|
||||
- [ ] 8.8 Write unit tests for conditional delete logic
|
||||
- Test ownership rejection for non-owner
|
||||
- Test state rejection for resolved/closed findings
|
||||
- Test compliance linkage rejection
|
||||
- Test cascade impact response format
|
||||
- Test Admin bypass of all restrictions
|
||||
- _Requirements: 3.5, 3.6, 3.7, 3.8, 3.9, 3.10_
|
||||
|
||||
- [x] 9. Checkpoint: Verify conditional delete logic
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [ ] 10. Update frontend AuthContext with group helpers
|
||||
- [x] 10.1 Update `frontend/src/contexts/AuthContext.js`
|
||||
- Read group from user object instead of role
|
||||
- Replace hasRole with isInGroup(...groups) helper
|
||||
- Update canWrite to check isInGroup('Admin', 'Standard_User')
|
||||
- Add canDelete(resource) helper: Admin always true, Standard_User only if owns resource, others false
|
||||
- Add canExport() helper: true for Admin, Standard_User, Leadership
|
||||
- Update isAdmin() to check isInGroup('Admin')
|
||||
- _Requirements: 10.1, 10.2, 10.3, 10.4, 10.5_
|
||||
|
||||
- [ ]* 10.2 Write property test for permission helpers
|
||||
- **Property 7: Group permission helpers are consistent with group matrix**
|
||||
- Generate all valid group values, call each helper, verify against permission matrix
|
||||
- **Validates: Requirements 10.5**
|
||||
|
||||
- [ ] 11. Update frontend UI for group-based rendering
|
||||
- [x] 11.1 Update `App.js` conditional rendering
|
||||
- Use canWrite, canDelete, canExport, isAdmin for button and link visibility
|
||||
- _Requirements: 10.1, 10.2, 10.3_
|
||||
|
||||
- [x] 11.2 Update `NavDrawer.js`
|
||||
- Show admin panel link only when isAdmin() is true
|
||||
- _Requirements: 10.3_
|
||||
|
||||
- [x] 11.3 Update `UserMenu.js`
|
||||
- Display user group instead of role
|
||||
- _Requirements: 10.1_
|
||||
|
||||
- [x] 11.4 Update all components using hasRole or canWrite
|
||||
- Replace with new group-based helpers throughout components
|
||||
- _Requirements: 10.5_
|
||||
|
||||
- [x] 11.5 Hide delete buttons for non-owned resources
|
||||
- Standard_User sees delete only on resources they created
|
||||
- _Requirements: 10.4_
|
||||
|
||||
- [ ] 12. Update User Management UI
|
||||
- [x] 12.1 Replace role dropdown with group dropdown in `UserManagement.js`
|
||||
- Options: Admin, Standard_User, Leadership, Read_Only
|
||||
- _Requirements: 8.1, 8.2_
|
||||
|
||||
- [x] 12.2 Update form data and API calls to use group field
|
||||
- Send group instead of role in create and update requests
|
||||
- _Requirements: 8.2_
|
||||
|
||||
- [x] 12.3 Add confirmation dialog for group changes
|
||||
- Show confirmation before applying any group change
|
||||
- _Requirements: 8.3_
|
||||
|
||||
- [x] 12.4 Add extra warning when downgrading Admin
|
||||
- Show additional warning in confirmation dialog
|
||||
- _Requirements: 8.4_
|
||||
|
||||
- [x] 12.5 Prevent admin self-demotion in UI
|
||||
- Disable group change dropdown for current user if Admin
|
||||
- _Requirements: 8.5_
|
||||
|
||||
- [x] 12.6 Update user table to show group badges
|
||||
- Display group badge with appropriate colors instead of role badge
|
||||
- _Requirements: 8.1_
|
||||
|
||||
- [x] 13. Final checkpoint: Verify full integration
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests use `fast-check` library with minimum 100 iterations per test
|
||||
- All backend code uses callback-based SQLite API wrapped in promises (matching existing patterns)
|
||||
- All frontend code uses plain JavaScript (no TypeScript)
|
||||
321
.kiro/specs/ivanti-fp-workflow-submission/design.md
Normal file
321
.kiro/specs/ivanti-fp-workflow-submission/design.md
Normal file
@@ -0,0 +1,321 @@
|
||||
# Design Document: Ivanti FP Workflow Submission
|
||||
|
||||
## Overview
|
||||
|
||||
This feature extends the existing Ivanti Queue (QueuePanel) in the Reporting Page to allow users to submit False Positive (FP) workflows directly to the Ivanti/RiskSense API. The implementation adds a submission modal triggered from the queue panel, a backend API endpoint that proxies the workflow creation and attachment upload to Ivanti, and local tracking of submissions in SQLite.
|
||||
|
||||
The design follows existing codebase conventions: factory-pattern Express routes, inline React styles with the dark tactical theme, Multer for file uploads, and the `ivantiPost()` HTTP helper for Ivanti API calls.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as User (Browser)
|
||||
participant FE as React Frontend
|
||||
participant BE as Express Backend
|
||||
participant IV as Ivanti API
|
||||
participant DB as SQLite
|
||||
|
||||
U->>FE: Select FP queue items, click "Create FP Workflow"
|
||||
FE->>FE: Open FpWorkflowModal with selected items
|
||||
U->>FE: Fill form, attach files, click Submit
|
||||
FE->>BE: POST /api/ivanti/fp-workflow (multipart/form-data)
|
||||
BE->>BE: Validate input, check auth
|
||||
BE->>IV: POST /client/{clientId}/workflowBatch (create FP workflow)
|
||||
IV-->>BE: 200 + workflow batch response (id, generatedId)
|
||||
alt Attachments present
|
||||
loop For each attachment
|
||||
BE->>IV: POST /client/{clientId}/workflowBatch/{id}/attachment
|
||||
IV-->>BE: 200 OK
|
||||
end
|
||||
end
|
||||
BE->>DB: INSERT into ivanti_fp_submissions
|
||||
BE->>DB: INSERT audit log entry
|
||||
BE->>DB: UPDATE ivanti_todo_queue SET status='complete'
|
||||
BE-->>FE: 200 + { workflowBatchId, generatedId, status }
|
||||
FE->>FE: Show success, refresh queue panel
|
||||
```
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend
|
||||
|
||||
#### New Route Module: `backend/routes/ivantiFpWorkflow.js`
|
||||
|
||||
Exports `createIvantiFpWorkflowRouter(db, requireAuth)` following the existing factory pattern.
|
||||
|
||||
**Endpoint: `POST /api/ivanti/fp-workflow`**
|
||||
|
||||
- Auth: `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Content-Type: `multipart/form-data` (handled by Multer)
|
||||
- Request fields:
|
||||
- `name` (string, required) — workflow name, max 255 chars
|
||||
- `reason` (string, required) — justification text
|
||||
- `description` (string, optional) — additional details, max 2000 chars
|
||||
- `expirationDate` (string, required) — ISO date string, must be future
|
||||
- `scopeOverride` (string, optional) — "Authorized" (default) or "None"
|
||||
- `findingIds` (string, required) — JSON-encoded array of finding ID strings
|
||||
- `queueItemIds` (string, required) — JSON-encoded array of local queue item IDs
|
||||
- `attachments` (files, optional) — up to 10 files, 10MB each
|
||||
|
||||
- Response (success):
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"workflowBatchId": 12345,
|
||||
"generatedId": "FP#12345",
|
||||
"attachmentResults": [
|
||||
{ "filename": "evidence.pdf", "success": true },
|
||||
{ "filename": "screenshot.png", "success": true }
|
||||
],
|
||||
"queueItemsUpdated": 3
|
||||
}
|
||||
```
|
||||
|
||||
- Response (error):
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"error": "Ivanti API returned status 401",
|
||||
"step": "create_workflow",
|
||||
"details": "..."
|
||||
}
|
||||
```
|
||||
|
||||
**Internal flow:**
|
||||
|
||||
1. Parse and validate all form fields
|
||||
2. Verify all `queueItemIds` belong to the requesting user and are FP-type with pending status
|
||||
3. Call Ivanti API to create the workflow batch
|
||||
4. If attachments exist, upload each to the created workflow batch
|
||||
5. Insert a submission record into `ivanti_fp_submissions`
|
||||
6. Log audit entry via `logAudit()`
|
||||
7. Mark queue items as complete
|
||||
8. Return combined result
|
||||
|
||||
#### Ivanti API Calls
|
||||
|
||||
Reuses the existing `ivantiPost()` helper pattern from `ivantiWorkflows.js`. Adds a new `ivantiMultipartPost()` helper for attachment uploads that sends `multipart/form-data` instead of JSON.
|
||||
|
||||
**Create Workflow Batch:**
|
||||
```
|
||||
POST /client/{clientId}/workflowBatch
|
||||
```
|
||||
```json
|
||||
{
|
||||
"name": "FP - CVE-2024-1234 - Vendor X",
|
||||
"type": "FALSE_POSITIVE",
|
||||
"reason": "Scanner false positive confirmed by manual investigation",
|
||||
"description": "Additional context...",
|
||||
"expirationDate": "2025-12-31",
|
||||
"scopeOverrideAuthorization": "AUTHORIZED",
|
||||
"hostFindingIds": [123456, 789012],
|
||||
"subType": "FALSE_POSITIVE"
|
||||
}
|
||||
```
|
||||
|
||||
**Upload Attachment:**
|
||||
```
|
||||
POST /client/{clientId}/workflowBatch/{workflowBatchId}/attachment
|
||||
Content-Type: multipart/form-data
|
||||
```
|
||||
Form field: `file` — the binary file content.
|
||||
|
||||
#### Shared HTTP Helpers
|
||||
|
||||
The existing `ivantiPost()` function is duplicated across `ivantiWorkflows.js` and `ivantiFindings.js`. This design extracts it into a shared helper at `backend/helpers/ivantiApi.js` alongside the new multipart helper:
|
||||
|
||||
- `ivantiPost(urlPath, body, apiKey, skipTls)` — JSON POST (existing logic)
|
||||
- `ivantiMultipartPost(urlPath, fileBuffer, fileName, apiKey, skipTls)` — multipart file upload
|
||||
|
||||
### Frontend
|
||||
|
||||
#### New Component: `FpWorkflowModal`
|
||||
|
||||
Located in `frontend/src/components/pages/ReportingPage.js` (inline, following the existing pattern where QueuePanel and AddToQueuePopover are defined in the same file).
|
||||
|
||||
**Props:**
|
||||
- `open` (boolean) — controls visibility
|
||||
- `onClose` (function) — close handler
|
||||
- `selectedItems` (array) — FP queue items selected for submission
|
||||
- `onSuccess` (function) — callback after successful submission, triggers queue refresh
|
||||
|
||||
**State:**
|
||||
- `name`, `reason`, `description`, `expirationDate`, `scopeOverride` — form fields
|
||||
- `files` — array of File objects for upload
|
||||
- `submitting` — boolean, disables form during submission
|
||||
- `progress` — object tracking current step and attachment progress
|
||||
- `errors` — validation error map
|
||||
- `result` — submission result (success/failure details)
|
||||
|
||||
**UI Layout:**
|
||||
- Modal overlay with dark backdrop (matching existing modal patterns)
|
||||
- Header: "Create FP Workflow" with close button
|
||||
- Body sections:
|
||||
1. Selected findings summary (read-only list with finding_id, title, CVEs)
|
||||
2. Workflow configuration form (name, reason, description, expiration, scope override toggle)
|
||||
3. File upload area (drag-and-drop zone + file list)
|
||||
- Footer: Cancel and Submit buttons, progress indicator when submitting
|
||||
|
||||
#### QueuePanel Modifications
|
||||
|
||||
- Add a "Create FP Workflow" button in the footer, next to existing "Delete Selected" and "Clear Completed" buttons
|
||||
- Button enabled only when `selectedIds` contains at least one pending FP-type item
|
||||
- Clicking opens `FpWorkflowModal` with the filtered FP items
|
||||
- After successful submission, the `onSuccess` callback triggers queue refresh
|
||||
|
||||
## Data Models
|
||||
|
||||
### New Table: `ivanti_fp_submissions`
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS ivanti_fp_submissions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
ivanti_workflow_batch_id INTEGER,
|
||||
ivanti_generated_id TEXT,
|
||||
workflow_name TEXT NOT NULL,
|
||||
reason TEXT NOT NULL,
|
||||
description TEXT,
|
||||
expiration_date TEXT NOT NULL,
|
||||
scope_override TEXT NOT NULL DEFAULT 'Authorized',
|
||||
finding_ids_json TEXT NOT NULL,
|
||||
queue_item_ids_json TEXT NOT NULL,
|
||||
attachment_count INTEGER DEFAULT 0,
|
||||
attachment_results_json TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'success' CHECK(status IN ('success', 'partial', 'failed')),
|
||||
error_message TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fp_submissions_user ON ivanti_fp_submissions(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_fp_submissions_ivanti_id ON ivanti_fp_submissions(ivanti_generated_id);
|
||||
```
|
||||
|
||||
**Status values:**
|
||||
- `success` — workflow created and all attachments uploaded
|
||||
- `partial` — workflow created but one or more attachments failed
|
||||
- `failed` — workflow creation itself failed (record kept for audit)
|
||||
|
||||
### Migration Script: `backend/migrations/add_fp_submissions_table.js`
|
||||
|
||||
Standard migration script following the existing pattern (e.g., `add_ivanti_todo_queue_table.js`).
|
||||
|
||||
|
||||
## 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: FP Workflow Button Enabled State
|
||||
|
||||
*For any* set of queue items and any selection of item IDs, the "Create FP Workflow" button should be enabled if and only if the selection contains at least one queue item that has `workflow_type === 'FP'` and `status === 'pending'`.
|
||||
|
||||
**Validates: Requirements 1.1**
|
||||
|
||||
### Property 2: FP-Only Item Filtering
|
||||
|
||||
*For any* set of selected queue items containing a mix of workflow types (FP, Archer, CARD), the items passed to the FP workflow submission modal should contain only items where `workflow_type === 'FP'`, and the count of filtered items should be less than or equal to the count of selected items.
|
||||
|
||||
**Validates: Requirements 1.2**
|
||||
|
||||
### Property 3: Form Validation Correctness
|
||||
|
||||
*For any* form state (name, reason, description, expirationDate, scopeOverride), validation should pass if and only if: name is a non-empty string of at most 255 characters, reason is a non-empty string, description (if provided) is at most 2000 characters, and expirationDate is a valid date strictly after today. When validation fails, the returned error map should contain a key for each invalid field and no keys for valid fields.
|
||||
|
||||
**Validates: Requirements 2.4, 2.5**
|
||||
|
||||
### Property 4: File Extension Validation
|
||||
|
||||
*For any* filename string, the file acceptance function should return true if and only if the file's extension (case-insensitive) is one of: .pdf, .png, .jpg, .jpeg, .gif, .doc, .docx, .xlsx, .csv, .txt, .zip. Files with disallowed extensions should be rejected.
|
||||
|
||||
**Validates: Requirements 3.3**
|
||||
|
||||
### Property 5: API Payload Construction
|
||||
|
||||
*For any* valid form input (name, reason, description, expirationDate, scopeOverride, findingIds), the constructed Ivanti API request body should contain: `type` equal to "FALSE_POSITIVE", `name` equal to the input name, `reason` equal to the input reason, `expirationDate` equal to the input date, `scopeOverrideAuthorization` mapped from the input scopeOverride value, and `hostFindingIds` equal to the input finding IDs parsed as integers.
|
||||
|
||||
**Validates: Requirements 4.1**
|
||||
|
||||
### Property 6: Queue Items Marked Complete on Success
|
||||
|
||||
*For any* set of queue item IDs associated with a successful FP workflow submission, after the post-submission handler runs, all those queue items should have `status === 'complete'`.
|
||||
|
||||
**Validates: Requirements 5.1**
|
||||
|
||||
### Property 7: Post-Submission Persistence Completeness
|
||||
|
||||
*For any* successful FP workflow submission with a given workflow batch ID, name, user ID, and finding IDs, the resulting submission record should contain all of: ivanti_workflow_batch_id, workflow_name, user_id, finding_ids_json (parseable to the original finding IDs array), and a non-null created_at timestamp. Additionally, the audit log entry should have action "ivanti_fp_workflow_created", entity_type "ivanti_workflow", and details containing the workflow name and finding IDs.
|
||||
|
||||
**Validates: Requirements 6.1, 6.2**
|
||||
|
||||
### Property 8: Role-Based UI Visibility
|
||||
|
||||
*For any* user role, the "Create FP Workflow" button should be visible if and only if the user's role is "editor" or "admin". Users with the "viewer" role should not see the button.
|
||||
|
||||
**Validates: Requirements 7.2**
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Ivanti API Errors
|
||||
|
||||
| HTTP Status | Error Type | User-Facing Message | System Behavior |
|
||||
|-------------|-----------|---------------------|-----------------|
|
||||
| 401 | Auth failure | "Ivanti API key is invalid or missing. Contact your administrator." | Log error, preserve form state |
|
||||
| 419 | Insufficient privileges | "API key lacks workflow creation permissions." | Log error, preserve form state |
|
||||
| 429 | Rate limited | "Ivanti API rate limit reached. Please try again in a few minutes." | Log error, preserve form state |
|
||||
| 5xx | Server error | "Ivanti API is temporarily unavailable. Please try again later." | Log error, preserve form state |
|
||||
| Other | Unknown | "Workflow creation failed: {status} — {message}" | Log error with full response, preserve form state |
|
||||
|
||||
### Partial Failure (Attachment Upload)
|
||||
|
||||
When the workflow batch is created successfully but one or more attachment uploads fail:
|
||||
- The submission record is saved with `status = 'partial'`
|
||||
- The response includes the workflow batch ID and per-attachment success/failure details
|
||||
- The UI shows which attachments failed and allows retry
|
||||
- The queue items are still marked complete (the workflow itself was created)
|
||||
|
||||
### Local Database Errors
|
||||
|
||||
- If the submission record INSERT fails: log error, still return success to user (Ivanti workflow was created)
|
||||
- If queue item status UPDATE fails: return success with a warning that local queue state may be stale
|
||||
- If audit log INSERT fails: fire-and-forget (existing pattern from `logAudit()`)
|
||||
|
||||
### Input Validation Errors
|
||||
|
||||
- All validation errors return 400 with a structured error object mapping field names to error messages
|
||||
- Frontend validates before sending to prevent unnecessary API calls
|
||||
- Backend re-validates all inputs as a security measure
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Property-Based Testing
|
||||
|
||||
Use `fast-check` as the property-based testing library for JavaScript.
|
||||
|
||||
Each correctness property maps to a single property-based test with a minimum of 100 iterations. Tests are tagged with the format: **Feature: ivanti-fp-workflow-submission, Property {number}: {title}**.
|
||||
|
||||
Property tests focus on pure functions extracted from the implementation:
|
||||
- `isCreateFpButtonEnabled(items, selectedIds)` — Property 1
|
||||
- `filterFpItems(items)` — Property 2
|
||||
- `validateFpWorkflowForm(formData)` — Property 3
|
||||
- `isAllowedFileExtension(filename)` — Property 4
|
||||
- `buildIvantiPayload(formData, findingIds)` — Property 5
|
||||
- Queue item status update logic — Property 6
|
||||
- Submission record creation — Property 7
|
||||
- Role-based visibility check — Property 8
|
||||
|
||||
### Unit Testing
|
||||
|
||||
Unit tests complement property tests by covering:
|
||||
- Specific examples: known-good form submissions, known-bad inputs
|
||||
- Edge cases: empty finding lists, maximum file size boundary, expiration date exactly tomorrow
|
||||
- Error code mapping: verify each Ivanti HTTP status maps to the correct error message
|
||||
- Integration points: Multer file handling, multipart form construction
|
||||
- API response parsing: various Ivanti response formats
|
||||
|
||||
### Test File Locations
|
||||
|
||||
- `backend/__tests__/ivantiFpWorkflow.test.js` — backend route handler tests, validation, payload construction
|
||||
- `backend/__tests__/ivantiFpWorkflow.property.test.js` — property-based tests for backend logic
|
||||
- `frontend/src/__tests__/fpWorkflowModal.test.js` — frontend component and validation tests
|
||||
99
.kiro/specs/ivanti-fp-workflow-submission/requirements.md
Normal file
99
.kiro/specs/ivanti-fp-workflow-submission/requirements.md
Normal file
@@ -0,0 +1,99 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
This feature adds the ability for users to select items from the Ivanti Queue (QueuePanel) and submit False Positive (FP) workflows directly to the Ivanti/RiskSense API. Users can configure the FP workflow with a name, reason, description, expiration date, and the "Authorized" scope override option. Supporting documentation and artifacts can be uploaded and attached to the workflow via the API. Successful submissions mark the corresponding queue items as complete and are tracked locally with full audit logging.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Dashboard**: The STEAM Security Dashboard application
|
||||
- **Queue_Panel**: The slide-out panel in the Reporting Page that displays the user's Ivanti todo queue items grouped by vendor/CARD
|
||||
- **Queue_Item**: A single entry in the ivanti_todo_queue table representing a host finding staged for workflow processing, with fields including finding_id, finding_title, cves_json, ip_address, vendor, workflow_type, and status
|
||||
- **FP_Workflow**: A False Positive workflow batch created in the Ivanti/RiskSense platform to mark host findings as false positives, removing them from risk calculations
|
||||
- **Ivanti_API**: The Ivanti/RiskSense REST API at https://platform4.risksense.com/api/v1, authenticated via x-api-key header
|
||||
- **Workflow_Batch**: An Ivanti API resource representing a group of findings submitted together under a single workflow request
|
||||
- **Scope_Override_Authorization**: An Ivanti workflow property that controls whether additional findings can be added to or removed from the workflow after creation; values are "None" or "Authorized"
|
||||
- **Submission_Record**: A local database record tracking the details and outcome of an FP workflow submission made through the Dashboard
|
||||
- **Attachment**: A supporting document or artifact (PDF, screenshot, etc.) uploaded alongside an FP workflow submission as evidence or justification
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Select FP Queue Items for Workflow Submission
|
||||
|
||||
**User Story:** As an editor or admin, I want to select one or more FP-type items from the Ivanti Queue, so that I can batch them into a single False Positive workflow submission.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Queue_Panel is open and contains FP-type Queue_Items, THE Dashboard SHALL display a "Create FP Workflow" action button that is enabled only when at least one pending FP-type Queue_Item is selected
|
||||
2. WHEN a user selects Queue_Items of mixed workflow_type (FP and non-FP), THE Dashboard SHALL only include FP-type Queue_Items in the FP workflow submission and SHALL visually indicate which items are eligible
|
||||
3. IF no pending FP-type Queue_Items are selected, THEN THE Dashboard SHALL disable the "Create FP Workflow" action button and display a tooltip explaining the requirement
|
||||
4. WHEN the "Create FP Workflow" button is clicked, THE Dashboard SHALL open the FP Workflow Submission modal pre-populated with the selected finding IDs
|
||||
|
||||
### Requirement 2: Configure FP Workflow Details
|
||||
|
||||
**User Story:** As an editor or admin, I want to configure the FP workflow properties before submission, so that I can provide the required justification and metadata for the false positive request.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE FP_Workflow submission modal SHALL present input fields for: workflow name (required, max 255 characters), reason/justification (required), description (optional, max 2000 characters), and expiration date (required, must be a future date)
|
||||
2. THE FP_Workflow submission modal SHALL include a Scope_Override_Authorization toggle defaulting to "Authorized"
|
||||
3. THE FP_Workflow submission modal SHALL display a summary list of the selected Queue_Items including finding_id, finding_title, and associated CVEs
|
||||
4. WHEN a user attempts to submit with missing required fields, THE Dashboard SHALL display inline validation errors for each invalid field and prevent submission
|
||||
5. IF the expiration date is set to a date in the past or today, THEN THE Dashboard SHALL reject the value and display a validation message indicating the date must be in the future
|
||||
|
||||
### Requirement 3: Upload Supporting Documentation
|
||||
|
||||
**User Story:** As an editor or admin, I want to upload supporting documents and artifacts with my FP workflow submission, so that reviewers have the evidence needed to approve the false positive request.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE FP_Workflow submission modal SHALL include a file upload area that accepts multiple files with a maximum size of 10 MB per file
|
||||
2. WHEN files are added to the upload area, THE Dashboard SHALL display each file name, size, and a remove button
|
||||
3. THE Dashboard SHALL accept files with extensions: .pdf, .png, .jpg, .jpeg, .gif, .doc, .docx, .xlsx, .csv, .txt, .zip
|
||||
4. IF a user attempts to upload a file exceeding 10 MB, THEN THE Dashboard SHALL reject the file and display an error message stating the size limit
|
||||
5. IF a user attempts to upload a file with a disallowed extension, THEN THE Dashboard SHALL reject the file and display an error message listing the allowed file types
|
||||
|
||||
### Requirement 4: Submit FP Workflow to Ivanti API
|
||||
|
||||
**User Story:** As an editor or admin, I want to submit the configured FP workflow to the Ivanti API, so that the false positive request is created in the Ivanti/RiskSense platform with all associated findings and attachments.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the user clicks Submit, THE Dashboard SHALL send a POST request to the Ivanti_API to create a Workflow_Batch of type "False Positive" with the configured name, reason, description, expiration date, Scope_Override_Authorization setting, and the list of host finding IDs
|
||||
2. WHEN the Workflow_Batch is created successfully and attachments are present, THE Dashboard SHALL upload each Attachment to the Ivanti_API associated with the created Workflow_Batch
|
||||
3. WHEN the submission is in progress, THE Dashboard SHALL display a progress indicator showing the current step (creating workflow, uploading attachment 1 of N, etc.) and disable the Submit button to prevent duplicate submissions
|
||||
4. WHEN the entire submission completes successfully, THE Dashboard SHALL display a success message including the Ivanti-generated workflow batch ID (e.g., "FP#12345")
|
||||
5. IF the Ivanti_API returns a 401 status, THEN THE Dashboard SHALL display an error message indicating the API key is invalid or missing
|
||||
6. IF the Ivanti_API returns a 429 status, THEN THE Dashboard SHALL display an error message indicating rate limiting and suggest retrying later
|
||||
7. IF the Ivanti_API returns any other error status during workflow creation, THEN THE Dashboard SHALL display the error details and preserve the user's form input so they can retry without re-entering data
|
||||
8. IF an attachment upload fails after the workflow is created, THEN THE Dashboard SHALL report which attachments failed, display the workflow batch ID for the successfully created workflow, and allow the user to retry the failed uploads
|
||||
|
||||
### Requirement 5: Post-Submission Queue Item Updates
|
||||
|
||||
**User Story:** As an editor or admin, I want queue items to be automatically marked complete after a successful FP workflow submission, so that my queue reflects the current processing state.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN an FP workflow submission completes successfully, THE Dashboard SHALL mark all associated Queue_Items as "complete" status
|
||||
2. WHEN Queue_Items are marked complete after submission, THE Dashboard SHALL refresh the Queue_Panel to reflect the updated statuses
|
||||
3. IF marking a Queue_Item as complete fails locally, THEN THE Dashboard SHALL display a warning that the workflow was submitted successfully but the local queue status could not be updated
|
||||
|
||||
### Requirement 6: Local Submission Tracking
|
||||
|
||||
**User Story:** As an editor or admin, I want FP workflow submissions to be tracked locally, so that I can review submission history and audit past actions.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN an FP workflow submission completes successfully, THE Dashboard SHALL create a Submission_Record in the local database containing: the Ivanti workflow batch ID, workflow name, submitting user ID, list of finding IDs, submission timestamp, and status
|
||||
2. WHEN an FP workflow submission completes successfully, THE Dashboard SHALL log an audit entry with action "ivanti_fp_workflow_created", entity type "ivanti_workflow", the workflow batch ID as entity ID, and details including the finding IDs and workflow name
|
||||
3. IF an FP workflow submission fails, THEN THE Dashboard SHALL log an audit entry with action "ivanti_fp_workflow_failed" including the error details
|
||||
|
||||
### Requirement 7: Authorization and Access Control
|
||||
|
||||
**User Story:** As a system administrator, I want FP workflow submission restricted to authorized users, so that only editors and admins can create workflows in the Ivanti platform.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Dashboard SHALL restrict the FP workflow submission API endpoint to users with the "Admin" or "Standard_User" group membership
|
||||
2. THE Dashboard SHALL restrict the FP workflow submission UI controls to users with editor or admin roles
|
||||
3. WHILE a user has the viewer role, THE Dashboard SHALL hide the "Create FP Workflow" button from the Queue_Panel
|
||||
109
.kiro/specs/ivanti-fp-workflow-submission/tasks.md
Normal file
109
.kiro/specs/ivanti-fp-workflow-submission/tasks.md
Normal file
@@ -0,0 +1,109 @@
|
||||
# Implementation Plan: Ivanti FP Workflow Submission
|
||||
|
||||
## Overview
|
||||
|
||||
Implement the ability to select FP-type items from the Ivanti Queue and submit False Positive workflows to the Ivanti/RiskSense API, with file attachment support, local submission tracking, and audit logging. The implementation follows existing codebase conventions: factory-pattern Express routes, Multer for file uploads, inline React component styles with the dark tactical theme, and the `ivantiPost()` HTTP helper for Ivanti API calls.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Database migration and shared helpers
|
||||
- [x] 1.1 Create migration script `backend/migrations/add_fp_submissions_table.js`
|
||||
- Create `ivanti_fp_submissions` table with columns: id, user_id, username, ivanti_workflow_batch_id, ivanti_generated_id, workflow_name, reason, description, expiration_date, scope_override, finding_ids_json, queue_item_ids_json, attachment_count, attachment_results_json, status (success/partial/failed), error_message, created_at
|
||||
- Add indexes on user_id and ivanti_generated_id
|
||||
- Follow existing migration pattern from `add_ivanti_todo_queue_table.js`
|
||||
- _Requirements: 6.1_
|
||||
|
||||
- [x] 1.2 Extract shared Ivanti API helpers into `backend/helpers/ivantiApi.js`
|
||||
- Move the `ivantiPost()` function from `ivantiWorkflows.js` into a shared module
|
||||
- Add `ivantiMultipartPost(urlPath, fileBuffer, fileName, apiKey, skipTls)` for attachment uploads using Node.js `https` module with multipart/form-data boundary construction
|
||||
- Export both functions; update `ivantiWorkflows.js` and `ivantiFindings.js` to import from the shared module
|
||||
- _Requirements: 4.1, 4.2_
|
||||
|
||||
- [x] 2. Backend route — validation and payload construction
|
||||
- [x] 2.1 Create `backend/routes/ivantiFpWorkflow.js` with validation and payload builder
|
||||
- Export `createIvantiFpWorkflowRouter(db, requireAuth)` factory function
|
||||
- Implement `POST /` route with `requireAuth(db)` and `requireGroup('Admin', 'Standard_User')` middleware
|
||||
- Configure Multer for up to 10 file uploads, 10MB each, with allowed extensions: .pdf, .png, .jpg, .jpeg, .gif, .doc, .docx, .xlsx, .csv, .txt, .zip
|
||||
- Implement `validateFpWorkflowForm(body)` — returns error map for invalid fields (name required max 255, reason required, description max 2000, expirationDate required and must be future date)
|
||||
- Implement `buildIvantiPayload(formData, findingIds)` — constructs the Ivanti API request body with type "FALSE_POSITIVE", scopeOverrideAuthorization mapping, and hostFindingIds as integers
|
||||
- Implement `isAllowedFileExtension(filename)` — checks against the allowed extensions list (case-insensitive)
|
||||
- Verify all queueItemIds belong to the requesting user, are FP-type, and have pending status
|
||||
- _Requirements: 2.4, 2.5, 3.3, 3.4, 3.5, 4.1, 7.1_
|
||||
|
||||
- [ ]* 2.2 Write property tests for validation and payload construction
|
||||
- **Property 3: Form Validation Correctness** — For any form state, validation passes iff all required fields present and expiration date is future; error map keys match invalid fields only
|
||||
- **Property 4: File Extension Validation** — For any filename, acceptance returns true iff extension is in the allowed set (case-insensitive)
|
||||
- **Property 5: API Payload Construction** — For any valid form input, the constructed payload contains correct type, name, reason, expirationDate, scopeOverrideAuthorization, and hostFindingIds as integers
|
||||
- Use `fast-check` library with minimum 100 iterations per property
|
||||
- **Validates: Requirements 2.4, 2.5, 3.3, 4.1**
|
||||
|
||||
- [x] 3. Backend route — Ivanti API submission and local persistence
|
||||
- [x] 3.1 Implement the submission flow in `ivantiFpWorkflow.js`
|
||||
- Call Ivanti API `POST /client/{clientId}/workflowBatch` to create the FP workflow batch
|
||||
- If attachments present, upload each via `ivantiMultipartPost()` to `/client/{clientId}/workflowBatch/{id}/attachment`
|
||||
- Handle Ivanti API error responses: 401 (invalid key), 419 (insufficient privileges), 429 (rate limited), other errors
|
||||
- On success: insert submission record into `ivanti_fp_submissions`, call `logAudit()` with action "ivanti_fp_workflow_created"
|
||||
- On failure: call `logAudit()` with action "ivanti_fp_workflow_failed"
|
||||
- Mark associated queue items as complete via `UPDATE ivanti_todo_queue SET status='complete'`
|
||||
- Handle partial failures (workflow created but attachment upload failed) — save with status "partial"
|
||||
- Return structured response with workflowBatchId, generatedId, attachmentResults, queueItemsUpdated
|
||||
- _Requirements: 4.1, 4.2, 4.5, 4.6, 4.7, 4.8, 5.1, 6.1, 6.2, 6.3_
|
||||
|
||||
- [ ]* 3.2 Write property tests for queue item completion and submission persistence
|
||||
- **Property 6: Queue Items Marked Complete on Success** — For any set of queue item IDs after successful submission, all items have status "complete"
|
||||
- **Property 7: Post-Submission Persistence Completeness** — For any successful submission, the record contains all required fields (ivanti_workflow_batch_id, workflow_name, user_id, finding_ids_json, created_at) and audit entry has correct action/entity_type/details
|
||||
- Use in-memory SQLite for test isolation
|
||||
- **Validates: Requirements 5.1, 6.1, 6.2**
|
||||
|
||||
- [x] 4. Wire backend route into server.js
|
||||
- [x] 4.1 Register the new route in `backend/server.js`
|
||||
- Add `const createIvantiFpWorkflowRouter = require('./routes/ivantiFpWorkflow');`
|
||||
- Mount at `app.use('/api/ivanti/fp-workflow', createIvantiFpWorkflowRouter(db, requireAuth));`
|
||||
- Place near the existing Ivanti route registrations
|
||||
- _Requirements: 7.1_
|
||||
|
||||
- [x] 5. Checkpoint — Backend complete
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 6. Frontend — FP Workflow Modal component
|
||||
- [x] 6.1 Implement `FpWorkflowModal` in `frontend/src/components/pages/ReportingPage.js`
|
||||
- Add the modal component inline in ReportingPage.js following the existing pattern (QueuePanel, AddToQueuePopover are in the same file)
|
||||
- Props: open, onClose, selectedItems (FP queue items), onSuccess
|
||||
- Form fields: workflow name (text input, required), reason (textarea, required), description (textarea, optional), expiration date (date input, required), scope override toggle (Authorized/None, default Authorized)
|
||||
- Display selected findings summary: finding_id, finding_title, CVEs for each item
|
||||
- File upload area: drag-and-drop zone, file list with name/size/remove button, validate extensions and 10MB limit client-side
|
||||
- Submit button with progress indicator (creating workflow → uploading attachment N of M)
|
||||
- Error display: inline validation errors, API error messages with form state preservation
|
||||
- Success display: workflow batch ID (e.g., "FP#12345") with close/done action
|
||||
- Style with inline style objects matching the dark tactical theme from DESIGN_SYSTEM.md
|
||||
- Icons from lucide-react (Upload, FileText, X, Check, AlertTriangle, Loader)
|
||||
- _Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2, 3.3, 3.4, 3.5, 4.3, 4.4, 4.7, 4.8_
|
||||
|
||||
- [ ]* 6.2 Write property tests for frontend validation helpers
|
||||
- **Property 1: FP Workflow Button Enabled State** — For any set of queue items and selection, button enabled iff selection contains at least one pending FP item
|
||||
- **Property 2: FP-Only Item Filtering** — For any mixed-type selection, filtered result contains only FP items
|
||||
- **Property 8: Role-Based UI Visibility** — For any user role, button visible iff role is editor or admin
|
||||
- Extract `isCreateFpButtonEnabled`, `filterFpItems`, `shouldShowFpButton` as testable pure functions
|
||||
- Use `fast-check` with minimum 100 iterations
|
||||
- **Validates: Requirements 1.1, 1.2, 7.2**
|
||||
|
||||
- [x] 7. Frontend — QueuePanel integration
|
||||
- [x] 7.1 Add "Create FP Workflow" button and modal wiring in QueuePanel
|
||||
- Add "Create FP Workflow" button in QueuePanel footer, styled with amber/FP accent color
|
||||
- Button enabled only when selectedIds contains at least one pending FP-type item
|
||||
- Disabled state shows tooltip: "Select pending FP items to create a workflow"
|
||||
- Hide button entirely for viewer role users (check via useAuth context)
|
||||
- On click: filter selected items to FP-only, open FpWorkflowModal with filtered items
|
||||
- Wire onSuccess callback to trigger queue refresh (call existing fetch function from parent)
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 5.2, 7.2, 7.3_
|
||||
|
||||
- [x] 8. Final checkpoint — Full integration
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Property tests use `fast-check` library — install via `npm install --save-dev fast-check` in both backend and frontend
|
||||
- The shared Ivanti API helper (task 1.2) updates existing imports in ivantiWorkflows.js and ivantiFindings.js — test those routes still work after the refactor
|
||||
- Multer is already a project dependency (used for document uploads in server.js)
|
||||
1
.kiro/specs/ivanti-queue-redirect/.config.kiro
Normal file
1
.kiro/specs/ivanti-queue-redirect/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "b8855eb4-3949-426e-86ac-36fe069a6bb1", "workflowType": "requirements-first", "specType": "feature"}
|
||||
362
.kiro/specs/ivanti-queue-redirect/design.md
Normal file
362
.kiro/specs/ivanti-queue-redirect/design.md
Normal file
@@ -0,0 +1,362 @@
|
||||
# Design Document: Ivanti Queue Redirect
|
||||
|
||||
## Overview
|
||||
|
||||
The Ivanti Queue Redirect feature adds an optional redirect action to completed queue items, allowing users to create a new pending queue item under a different workflow type from an existing completed item. This supports the common scenario where a CARD inventory fix is done but the finding still needs FP or Archer processing, where an item was assigned to the wrong workflow initially, or where a CARD item with a high asset score (90+) needs to go through the GRANITE program for reassignment or deletion.
|
||||
|
||||
The feature consists of five parts:
|
||||
1. A new backend API endpoint (`POST /api/ivanti/todo-queue/:id/redirect`) added to the existing `ivantiTodoQueue.js` route module
|
||||
2. GRANITE added as a fourth valid workflow type across all backend endpoints (`VALID_WORKFLOW_TYPES` constant)
|
||||
3. A redirect modal component in the frontend for collecting target workflow type and vendor
|
||||
4. A redirect button on completed queue items in the existing QueuePanel
|
||||
5. Updated QueuePanel grouping: CARD and GRANITE items grouped under an "Inventory" section, with GRANITE also available in the AddToQueue popover
|
||||
|
||||
There are four workflow types: FP, Archer, CARD, and GRANITE. FP and Archer require a vendor string; CARD and GRANITE do not. Any completed item can redirect to any other workflow type — there is no fixed ordering between types.
|
||||
|
||||
The redirect operation creates a new row in `ivanti_todo_queue` — it does not modify or delete the original completed item. This preserves the audit trail and allows the original item to remain visible as completed.
|
||||
|
||||
## Architecture
|
||||
|
||||
The feature follows the existing patterns in the codebase:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as User
|
||||
participant QP as QueuePanel
|
||||
participant RM as RedirectModal
|
||||
participant API as POST /todo-queue/:id/redirect
|
||||
participant DB as SQLite (ivanti_todo_queue)
|
||||
participant AL as Audit Log
|
||||
|
||||
U->>QP: Clicks redirect button on completed item
|
||||
QP->>RM: Opens modal with item context
|
||||
U->>RM: Selects target workflow type + vendor
|
||||
RM->>API: POST /api/ivanti/todo-queue/:id/redirect
|
||||
API->>DB: SELECT original item (verify ownership + complete status)
|
||||
API->>DB: INSERT new pending item with target workflow_type
|
||||
API->>AL: logAudit (fire-and-forget)
|
||||
API-->>RM: 201 + new item JSON
|
||||
RM->>QP: Adds new item to list, closes modal, shows success
|
||||
```
|
||||
|
||||
No new database tables or schema changes are required. The redirect creates a standard `ivanti_todo_queue` row using the existing schema. Backend changes outside the new endpoint include: adding GRANITE to `VALID_WORKFLOW_TYPES`, updating all error messages to list four valid types, and treating GRANITE like CARD for vendor validation (no vendor required).
|
||||
|
||||
### QueuePanel Grouping (Layout)
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph QueuePanel
|
||||
subgraph Inventory Section
|
||||
A[CARD items]
|
||||
B[Sub-divider - only when both exist]
|
||||
C[GRANITE items]
|
||||
end
|
||||
subgraph Vendor Groups
|
||||
D[Vendor A - FP/Archer items]
|
||||
E[Vendor B - FP/Archer items]
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
The QueuePanel groups items into two categories:
|
||||
- **Inventory section** (top): Contains both CARD and GRANITE items under a single "Inventory" heading. CARD items appear first, followed by a subtle sub-divider (only shown when both types are present), then GRANITE items. Each item retains its workflow type badge (CARD in green, GRANITE in warm slate).
|
||||
- **Vendor groups** (below): FP and Archer items grouped by vendor, same as current behavior.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend: VALID_WORKFLOW_TYPES Constant
|
||||
|
||||
Updated from `['FP', 'Archer', 'CARD']` to `['FP', 'Archer', 'CARD', 'GRANITE']`.
|
||||
|
||||
All endpoints that reference this constant (batch add, single add, PUT, redirect) automatically accept GRANITE. The vendor validation condition changes from `workflow_type !== 'CARD'` to `workflow_type !== 'CARD' && workflow_type !== 'GRANITE'` (or equivalently, checking if the type is FP or Archer). The `vendorVal` assignment similarly treats GRANITE like CARD: `vendorVal = (workflow_type === 'CARD' || workflow_type === 'GRANITE') ? '' : vendor.trim()`.
|
||||
|
||||
All error messages for invalid workflow_type are updated to: `"workflow_type must be FP, Archer, CARD, or GRANITE."`.
|
||||
|
||||
### Backend: Redirect Endpoint
|
||||
|
||||
Added to `backend/routes/ivantiTodoQueue.js` inside the existing `createIvantiTodoQueueRouter` factory function.
|
||||
|
||||
```
|
||||
POST /api/ivanti/todo-queue/:id/redirect
|
||||
```
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{
|
||||
"workflow_type": "FP" | "Archer" | "CARD" | "GRANITE",
|
||||
"vendor": "string (required for FP/Archer, omitted for CARD/GRANITE)"
|
||||
}
|
||||
```
|
||||
|
||||
**Success response (201):**
|
||||
```json
|
||||
{
|
||||
"id": 42,
|
||||
"user_id": 1,
|
||||
"finding_id": "12345",
|
||||
"finding_title": "...",
|
||||
"cves_json": "[...]",
|
||||
"ip_address": "10.0.0.1",
|
||||
"hostname": "host.example.com",
|
||||
"vendor": "Cisco",
|
||||
"workflow_type": "FP",
|
||||
"status": "pending",
|
||||
"created_at": "...",
|
||||
"updated_at": "...",
|
||||
"cves": ["CVE-2024-1234"]
|
||||
}
|
||||
```
|
||||
|
||||
**Error responses:**
|
||||
| Status | Condition |
|
||||
|--------|-----------|
|
||||
| 400 | Item not in "complete" status |
|
||||
| 400 | Invalid workflow_type |
|
||||
| 400 | Missing/invalid vendor for FP/Archer |
|
||||
| 404 | Item not found or belongs to different user |
|
||||
| 500 | Database error |
|
||||
|
||||
**Auth:** `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
|
||||
### Backend: Vendor Validation Logic
|
||||
|
||||
The vendor requirement is conditional on workflow type across all endpoints:
|
||||
|
||||
| Workflow Type | Vendor Required | vendorVal |
|
||||
|---------------|----------------|-----------|
|
||||
| FP | Yes — non-empty, ≤ 200 chars | `vendor.trim()` |
|
||||
| Archer | Yes — non-empty, ≤ 200 chars | `vendor.trim()` |
|
||||
| CARD | No | `''` (empty string) |
|
||||
| GRANITE | No | `''` (empty string) |
|
||||
|
||||
The condition for requiring vendor changes from `workflow_type !== 'CARD'` to `workflow_type === 'FP' || workflow_type === 'Archer'` (or equivalently `!['CARD', 'GRANITE'].includes(workflow_type)`).
|
||||
|
||||
### Backend: PUT Validation Fix
|
||||
|
||||
In the existing PUT `/:id` handler, the error message for invalid `workflow_type` is updated to `"workflow_type must be FP, Archer, CARD, or GRANITE."`. The same update applies to the batch add, single add, and redirect endpoints.
|
||||
|
||||
### Frontend: RedirectModal Component
|
||||
|
||||
A modal component rendered inside the QueuePanel. It receives the item being redirected and collects:
|
||||
- Target workflow type (radio buttons: FP, Archer, CARD, GRANITE)
|
||||
- Vendor (text input, shown only when FP or Archer is selected)
|
||||
|
||||
The modal displays read-only context: finding title, finding ID, and current workflow type.
|
||||
|
||||
**WORKFLOW_OPTIONS constant** (updated to include GRANITE):
|
||||
```js
|
||||
const WORKFLOW_OPTIONS = [
|
||||
{ key: 'FP', label: 'FP', col: '#F59E0B', rgb: '245,158,11' },
|
||||
{ key: 'Archer', label: 'Archer', col: '#0EA5E9', rgb: '14,165,233' },
|
||||
{ key: 'CARD', label: 'CARD', col: '#10B981', rgb: '16,185,129' },
|
||||
{ key: 'GRANITE', label: 'GRANITE', col: '#A1887F', rgb: '161,136,127' },
|
||||
];
|
||||
```
|
||||
|
||||
The `needsVendor` condition changes from `workflowType === 'FP' || workflowType === 'Archer'` — this remains the same since GRANITE, like CARD, does not need vendor.
|
||||
|
||||
Props:
|
||||
```js
|
||||
{
|
||||
item: Object, // The completed queue item being redirected
|
||||
onClose: Function, // Close the modal
|
||||
onRedirect: Function // Callback with the new item after successful redirect
|
||||
}
|
||||
```
|
||||
|
||||
### Frontend: QueuePanel Changes
|
||||
|
||||
#### Grouping Logic
|
||||
|
||||
The current grouping logic filters `workflow_type === 'CARD'` into a separate top section. This changes to group both CARD and GRANITE into an "Inventory" section:
|
||||
|
||||
```js
|
||||
const grouped = useMemo(() => {
|
||||
const inventoryItems = items.filter((i) => i.workflow_type === 'CARD' || i.workflow_type === 'GRANITE');
|
||||
const cardItems = inventoryItems.filter((i) => i.workflow_type === 'CARD');
|
||||
const graniteItems = inventoryItems.filter((i) => i.workflow_type === 'GRANITE');
|
||||
const otherItems = items.filter((i) => i.workflow_type !== 'CARD' && i.workflow_type !== 'GRANITE');
|
||||
|
||||
// Vendor groups for FP/Archer items
|
||||
const map = {};
|
||||
otherItems.forEach((item) => {
|
||||
const v = item.vendor || 'Unknown';
|
||||
if (!map[v]) map[v] = [];
|
||||
map[v].push(item);
|
||||
});
|
||||
const vendorGroups = Object.keys(map).sort().map((vendor) => ({
|
||||
key: vendor, label: vendor, items: map[vendor], isInventory: false,
|
||||
}));
|
||||
|
||||
return inventoryItems.length > 0
|
||||
? [{ key: '__INVENTORY__', label: 'Inventory', cardItems, graniteItems, items: inventoryItems, isInventory: true }, ...vendorGroups]
|
||||
: vendorGroups;
|
||||
}, [items]);
|
||||
```
|
||||
|
||||
#### Inventory Section Rendering
|
||||
|
||||
The Inventory section header uses the existing accent color for the section label. Within the section:
|
||||
1. CARD items render first
|
||||
2. A subtle sub-divider appears only when both CARD and GRANITE items exist
|
||||
3. GRANITE items render below the sub-divider
|
||||
|
||||
Each item retains its individual workflow type badge with distinct colors.
|
||||
|
||||
#### Workflow Type Color Mapping
|
||||
|
||||
Updated to include GRANITE:
|
||||
|
||||
```js
|
||||
const wfColor = item.workflow_type === 'FP' ? { col: '#F59E0B', rgb: '245,158,11' }
|
||||
: item.workflow_type === 'Archer' ? { col: '#0EA5E9', rgb: '14,165,233' }
|
||||
: item.workflow_type === 'GRANITE' ? { col: '#A1887F', rgb: '161,136,127' }
|
||||
: { col: '#10B981', rgb: '16,185,129' };
|
||||
```
|
||||
|
||||
#### GRANITE Item Rendering
|
||||
|
||||
GRANITE items render identically to CARD items — showing hostname and ip_address fields (not CVEs), since GRANITE is also an inventory-category workflow. The condition changes from `isCardItem` to `isInventoryItem`:
|
||||
|
||||
```js
|
||||
const isInventoryItem = item.workflow_type === 'CARD' || item.workflow_type === 'GRANITE';
|
||||
```
|
||||
|
||||
#### Redirect Button
|
||||
|
||||
A redirect icon button (`CornerUpRight` from lucide-react) on each completed queue item row, next to the existing delete button. Visible only when `item.status === 'complete'` and `canWrite` is true.
|
||||
|
||||
### Frontend: AddToQueue Popover
|
||||
|
||||
The AddToQueue popover (defined inline in `ReportingPage.js`) adds GRANITE as a fourth workflow type button:
|
||||
|
||||
```js
|
||||
const QUEUE_WORKFLOW_OPTIONS = [
|
||||
{ key: 'FP', label: 'FP', col: '#F59E0B', rgb: '245,158,11' },
|
||||
{ key: 'Archer', label: 'Archer', col: '#0EA5E9', rgb: '14,165,233' },
|
||||
{ key: 'CARD', label: 'CARD', col: '#10B981', rgb: '16,185,129' },
|
||||
{ key: 'GRANITE', label: 'GRANITE', col: '#A1887F', rgb: '161,136,127' },
|
||||
];
|
||||
```
|
||||
|
||||
When GRANITE is selected, no vendor field is required — same behavior as CARD. The submit logic uses the same condition: `workflow_type === 'FP' || workflow_type === 'Archer'` to determine if vendor is needed.
|
||||
|
||||
### Frontend: API Call
|
||||
|
||||
```js
|
||||
const res = await fetch(`${API_BASE}/ivanti/todo-queue/${itemId}/redirect`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ workflow_type, vendor })
|
||||
});
|
||||
```
|
||||
|
||||
## Data Models
|
||||
|
||||
No schema changes. The redirect creates a standard `ivanti_todo_queue` row:
|
||||
|
||||
| Column | Source |
|
||||
|--------|--------|
|
||||
| user_id | `req.user.id` (current user) |
|
||||
| finding_id | Copied from original item |
|
||||
| finding_title | Copied from original item |
|
||||
| cves_json | Copied from original item |
|
||||
| ip_address | Copied from original item |
|
||||
| hostname | Copied from original item |
|
||||
| vendor | From request body (FP/Archer) or empty string (CARD/GRANITE) |
|
||||
| workflow_type | From request body (FP, Archer, CARD, or GRANITE) |
|
||||
| status | `'pending'` (always) |
|
||||
|
||||
The original completed item remains unchanged.
|
||||
|
||||
|
||||
## 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: Redirect preserves finding data
|
||||
|
||||
*For any* completed queue item with arbitrary finding_id, finding_title, cves_json, ip_address, and hostname values, and *for any* valid target workflow type (FP, Archer, CARD, or GRANITE), redirecting that item SHALL produce a new queue item where finding_id, finding_title, cves_json, ip_address, and hostname are identical to the original, status is "pending", and workflow_type matches the requested target.
|
||||
|
||||
**Validates: Requirements 1.1, 1.7**
|
||||
|
||||
### Property 2: Vendor requirement is conditional on workflow type
|
||||
|
||||
*For any* redirect request, if the target workflow_type is "FP" or "Archer", the request SHALL be accepted if and only if vendor is a non-empty string of 200 characters or fewer. If the target workflow_type is "CARD" or "GRANITE", the request SHALL be accepted regardless of whether vendor is provided.
|
||||
|
||||
**Validates: Requirements 1.2, 1.3, 6.2**
|
||||
|
||||
### Property 3: Successful redirect produces correct audit entry
|
||||
|
||||
*For any* successful redirect operation, the audit log entry SHALL contain action "queue_item_redirected", entityType "ivanti_todo_queue", the original item's ID as entityId, and details including the original workflow_type, the target workflow_type, the new item's ID, and the vendor.
|
||||
|
||||
**Validates: Requirements 2.1, 2.2**
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | HTTP Status | Error Message | Behavior |
|
||||
|----------|-------------|---------------|----------|
|
||||
| Item not found or belongs to another user | 404 | "Queue item not found." | Consistent with existing DELETE/PUT pattern |
|
||||
| Item status is not "complete" | 400 | "Only completed queue items can be redirected." | Prevents redirecting pending items |
|
||||
| Invalid workflow_type | 400 | "workflow_type must be FP, Archer, CARD, or GRANITE." | Same message across all endpoints |
|
||||
| Missing/invalid vendor for FP/Archer | 400 | "vendor is required for FP and Archer workflows." | Same message as existing endpoints |
|
||||
| Vendor exceeds 200 chars | 400 | "vendor must be under 200 chars." | Same message as existing endpoints |
|
||||
| Database insert failure | 500 | "Internal server error." | Consistent with existing error pattern |
|
||||
| Frontend API error | — | Display error message from API in modal | Modal stays open so user can retry or cancel |
|
||||
|
||||
The redirect endpoint reuses the existing `isValidVendor()` helper and `VALID_WORKFLOW_TYPES` constant from `ivantiTodoQueue.js` for consistent validation. All error messages for invalid workflow_type now list all four valid options: FP, Archer, CARD, and GRANITE.
|
||||
|
||||
Audit logging uses the existing fire-and-forget pattern — a failed audit log write does not block or fail the redirect response.
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (Example-Based)
|
||||
|
||||
Backend:
|
||||
- Redirect a completed CARD item to FP with vendor → 201, new item returned
|
||||
- Redirect a completed FP item to CARD without vendor → 201, new item returned
|
||||
- Redirect a completed FP item to GRANITE without vendor → 201, new item returned
|
||||
- Redirect a completed GRANITE item to Archer with vendor → 201, new item returned
|
||||
- Redirect a pending item → 400
|
||||
- Redirect another user's item → 404
|
||||
- Redirect with invalid workflow_type → 400 with message listing FP, Archer, CARD, GRANITE
|
||||
- Redirect to FP without vendor → 400
|
||||
- Redirect to FP with vendor > 200 chars → 400
|
||||
- Redirect non-existent item → 404
|
||||
- PUT with invalid workflow_type returns error message "workflow_type must be FP, Archer, CARD, or GRANITE."
|
||||
- Batch add with workflow_type GRANITE and no vendor → 201
|
||||
- Single add with workflow_type GRANITE and no vendor → 201
|
||||
- Verify audit log is called with correct fields on successful redirect
|
||||
- Verify VALID_WORKFLOW_TYPES includes all four types
|
||||
|
||||
Frontend:
|
||||
- Redirect button visible on completed items, hidden on pending items
|
||||
- Clicking redirect button opens modal with correct item context
|
||||
- Modal shows all four workflow type options (FP, Archer, CARD, GRANITE)
|
||||
- Modal shows vendor field for FP/Archer, hides for CARD and GRANITE
|
||||
- Modal displays finding title, finding ID, current workflow type
|
||||
- Successful redirect closes modal, adds new item to list, shows notification
|
||||
- Failed redirect shows error message, modal stays open
|
||||
- QueuePanel groups CARD and GRANITE items under "Inventory" section
|
||||
- Sub-divider shown only when both CARD and GRANITE items exist in Inventory section
|
||||
- "Inventory" heading shown even when only one sub-type present
|
||||
- GRANITE badge uses warm slate color (#A1887F)
|
||||
- CARD badge uses green color (#10B981)
|
||||
- AddToQueue popover shows GRANITE as fourth option with warm slate color
|
||||
- Selecting GRANITE in AddToQueue popover does not require vendor
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Library: `fast-check` (JavaScript property-based testing library)
|
||||
|
||||
Each property test runs a minimum of 100 iterations.
|
||||
|
||||
- **Property 1**: Generate random queue item data (finding_id, finding_title, cves_json, ip_address, hostname with varying lengths, special characters, null optionals) and random valid workflow_type from all four types (FP, Archer, CARD, GRANITE). Mock the database layer. Verify the INSERT parameters preserve all finding fields and set status to "pending".
|
||||
- Tag: `Feature: ivanti-queue-redirect, Property 1: Redirect preserves finding data`
|
||||
|
||||
- **Property 2**: Generate random (workflow_type, vendor) pairs where workflow_type is drawn from all four valid types and vendor is drawn from a mix of valid strings, empty strings, whitespace, strings of length 200, and strings of length 201. Verify that the validation logic accepts/rejects correctly: FP/Archer require non-empty vendor ≤ 200 chars; CARD/GRANITE accept without vendor.
|
||||
- Tag: `Feature: ivanti-queue-redirect, Property 2: Vendor requirement is conditional on workflow type`
|
||||
|
||||
- **Property 3**: Generate random successful redirect scenarios with varying item data and all four workflow types. Mock logAudit. Verify the audit call contains the correct action, entityType, entityId, and all required detail fields.
|
||||
- Tag: `Feature: ivanti-queue-redirect, Property 3: Successful redirect produces correct audit entry`
|
||||
107
.kiro/specs/ivanti-queue-redirect/requirements.md
Normal file
107
.kiro/specs/ivanti-queue-redirect/requirements.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The Ivanti Queue Redirect feature gives users the option to redirect any completed queue item to a different workflow type. Not every completed item needs a redirect — many items are fully resolved once their workflow completes. However, some findings require further action under a different workflow. The primary use case is CARD items where the inventory fix is done but the finding still needs an FP or Archer workflow. It also supports correcting items that were assigned to the wrong team by redirecting them after a CARD fix. Additionally, CARD items with high asset scores (90+) that cannot be edited in CARD need to go through the GRANITE program for reassignment or deletion — GRANITE is a first-class workflow type alongside FP, Archer, and CARD. Redirecting is always a user-initiated, optional action that creates a new pending queue item with the target workflow type, preserving the original finding data. Any completed item can redirect to GRANITE, and any completed GRANITE item can redirect to any other type — there is no fixed ordering between workflow types.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Queue_Panel**: The slide-out panel in the frontend that displays the user's Ivanti todo queue items. Items are grouped into an Inventory section (containing CARD and GRANITE sub-groups) at the top, followed by vendor-grouped sections for FP and Archer items.
|
||||
- **Queue_Item**: A row in the `ivanti_todo_queue` table representing a finding assigned to a workflow type (FP, Archer, CARD, or GRANITE) with a status of pending or complete.
|
||||
- **Redirect**: The action of creating a new pending Queue_Item from an existing completed Queue_Item, changing the workflow type and optionally setting a vendor.
|
||||
- **Workflow_Type**: One of four processing tracks for a finding: FP (False Positive), Archer (risk acceptance), CARD (inventory correction), or GRANITE (high-asset-score reassignment/deletion).
|
||||
- **GRANITE**: A workflow type for findings with high asset scores (90+) that cannot be edited in CARD and require reassignment or deletion through the GRANITE program. GRANITE behaves like CARD for validation — no vendor is required.
|
||||
- **Vendor**: The vendor string associated with a Queue_Item. Required for FP and Archer workflow types, not required for CARD or GRANITE.
|
||||
- **Redirect_API**: The backend endpoint `POST /api/ivanti/todo-queue/:id/redirect` that performs the redirect operation.
|
||||
- **Redirect_Modal**: The frontend dialog that collects the target workflow type and vendor from the user before executing a redirect.
|
||||
- **Inventory_Section**: The top section of the Queue_Panel that groups both CARD and GRANITE items under the heading "Inventory", with a sub-divider separating CARD items (first) from GRANITE items (below).
|
||||
- **AddToQueue_Popover**: The frontend popover that allows users to add findings to the queue by selecting a workflow type.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Redirect a Completed Queue Item via API
|
||||
|
||||
**User Story:** As an editor or admin, I want to redirect a completed queue item to a different workflow type, so that I can continue processing a finding under the correct workflow after initial work is done.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a user submits a redirect request for a completed Queue_Item, THE Redirect_API SHALL create a new Queue_Item with status "pending", the specified target Workflow_Type, and the same finding_id, finding_title, cves_json, ip_address, and hostname as the original Queue_Item.
|
||||
2. WHEN a user submits a redirect request with a target Workflow_Type of "FP" or "Archer", THE Redirect_API SHALL require a non-empty vendor string of 200 characters or fewer.
|
||||
3. WHEN a user submits a redirect request with a target Workflow_Type of "CARD" or "GRANITE", THE Redirect_API SHALL accept the request without requiring a vendor.
|
||||
4. IF a user submits a redirect request for a Queue_Item that is not in "complete" status, THEN THE Redirect_API SHALL return a 400 error with a descriptive message.
|
||||
5. IF a user submits a redirect request for a Queue_Item that belongs to a different user, THEN THE Redirect_API SHALL return a 404 error.
|
||||
6. IF a user submits a redirect request with an invalid Workflow_Type, THEN THE Redirect_API SHALL return a 400 error indicating valid options are FP, Archer, CARD, or GRANITE.
|
||||
7. WHEN a redirect is successfully completed, THE Redirect_API SHALL return the newly created Queue_Item with a 201 status code.
|
||||
|
||||
### Requirement 2: Audit Logging for Redirects
|
||||
|
||||
**User Story:** As an admin, I want redirect actions to be recorded in the audit log, so that I can track workflow changes for compliance and accountability.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a redirect is successfully completed, THE Redirect_API SHALL log an audit entry with action "queue_item_redirected", the user's ID and username, the original Queue_Item ID as entityId, and details including the original Workflow_Type, the target Workflow_Type, the new Queue_Item ID, and the vendor.
|
||||
2. THE Redirect_API SHALL use entityType "ivanti_todo_queue" for all redirect audit entries.
|
||||
|
||||
### Requirement 3: Redirect UI in the Queue Panel
|
||||
|
||||
**User Story:** As a user, I want a redirect button on completed queue items, so that I can easily initiate a redirect without leaving the Queue_Panel.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHILE a Queue_Item has status "complete", THE Queue_Panel SHALL display a redirect button on that item.
|
||||
2. WHILE a Queue_Item has status "pending", THE Queue_Panel SHALL hide the redirect button on that item.
|
||||
3. WHEN the user clicks the redirect button on a completed Queue_Item, THE Queue_Panel SHALL open the Redirect_Modal pre-populated with the finding details from the selected item.
|
||||
|
||||
### Requirement 4: Redirect Modal Workflow
|
||||
|
||||
**User Story:** As a user, I want a modal dialog to select the target workflow type and vendor when redirecting, so that I can confirm the redirect details before submitting.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Redirect_Modal SHALL display a workflow type selector with options FP, Archer, CARD, and GRANITE.
|
||||
2. WHEN the user selects FP or Archer as the target Workflow_Type, THE Redirect_Modal SHALL display a required vendor input field.
|
||||
3. WHEN the user selects CARD or GRANITE as the target Workflow_Type, THE Redirect_Modal SHALL hide the vendor input field.
|
||||
4. THE Redirect_Modal SHALL display the finding title, finding ID, and current Workflow_Type of the item being redirected as read-only context.
|
||||
5. WHEN the user confirms the redirect in the Redirect_Modal, THE Queue_Panel SHALL call the Redirect_API and add the newly created Queue_Item to the displayed list without requiring a full page refresh.
|
||||
6. IF the Redirect_API returns an error, THEN THE Redirect_Modal SHALL display the error message to the user and remain open.
|
||||
7. WHEN the redirect succeeds, THE Redirect_Modal SHALL close and THE Queue_Panel SHALL display a success notification.
|
||||
|
||||
### Requirement 5: Fix PUT Endpoint Validation Message
|
||||
|
||||
**User Story:** As a developer, I want the PUT endpoint validation message to accurately list all valid workflow types, so that API consumers receive correct error guidance.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a user submits an invalid workflow_type to the PUT /api/ivanti/todo-queue/:id endpoint, THE Redirect_API SHALL return an error message stating "workflow_type must be FP, Archer, CARD, or GRANITE".
|
||||
|
||||
### Requirement 6: GRANITE Backend Validation Support
|
||||
|
||||
**User Story:** As a developer, I want GRANITE recognized as a valid workflow type across all backend endpoints, so that users can add, update, and redirect GRANITE items through the existing API.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Redirect_API SHALL include "GRANITE" in the VALID_WORKFLOW_TYPES constant alongside "FP", "Archer", and "CARD".
|
||||
2. WHEN a user submits a request with Workflow_Type "GRANITE" to the batch add, single add, PUT, or redirect endpoints, THE Redirect_API SHALL accept the request without requiring a vendor, using the same validation rules as "CARD".
|
||||
3. WHEN any endpoint returns an error for an invalid Workflow_Type, THE Redirect_API SHALL list all four valid options: FP, Archer, CARD, and GRANITE.
|
||||
|
||||
### Requirement 7: Inventory Section Grouping in Queue Panel
|
||||
|
||||
**User Story:** As a user, I want CARD and GRANITE items grouped together under an "Inventory" heading in the Queue_Panel, so that I can see all inventory-category work in one place while distinguishing between the two sub-types.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Queue_Panel SHALL display a top section labeled "Inventory" that contains both CARD and GRANITE Queue_Items.
|
||||
2. WHILE the Inventory_Section contains both CARD and GRANITE items, THE Queue_Panel SHALL display a subtle sub-divider separating CARD items (listed first) from GRANITE items (listed below).
|
||||
3. THE Queue_Panel SHALL display a workflow type badge on each item showing "CARD" or "GRANITE" with distinct badge colors.
|
||||
4. THE Queue_Panel SHALL use a warm slate color (#A1887F or #8D6E63) for the GRANITE badge, distinct from the CARD green (#10B981).
|
||||
5. WHILE the Inventory_Section contains only CARD items or only GRANITE items, THE Queue_Panel SHALL still display the "Inventory" section heading without a sub-divider.
|
||||
|
||||
### Requirement 8: GRANITE Support in AddToQueue Popover
|
||||
|
||||
**User Story:** As a user, I want to add findings to the queue as GRANITE items directly from the AddToQueue_Popover, so that I can assign high-asset-score findings to the GRANITE workflow without needing to redirect from another type.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE AddToQueue_Popover SHALL display GRANITE as a fourth workflow type button alongside FP, Archer, and CARD.
|
||||
2. WHEN the user selects GRANITE in the AddToQueue_Popover, THE AddToQueue_Popover SHALL submit the request without requiring a vendor field, using the same behavior as CARD.
|
||||
3. THE AddToQueue_Popover SHALL use the warm slate color (#A1887F or #8D6E63) for the GRANITE button, consistent with the GRANITE badge color in the Queue_Panel.
|
||||
143
.kiro/specs/ivanti-queue-redirect/tasks.md
Normal file
143
.kiro/specs/ivanti-queue-redirect/tasks.md
Normal file
@@ -0,0 +1,143 @@
|
||||
# Implementation Plan: Ivanti Queue Redirect
|
||||
|
||||
## Overview
|
||||
|
||||
Implement a redirect action for completed Ivanti queue items. The feature adds a `POST /api/ivanti/todo-queue/:id/redirect` endpoint to the existing route module, fixes the PUT validation message, creates a RedirectModal frontend component, and wires a redirect button into the QueuePanel for completed items. Tasks are ordered: backend bug fix, backend endpoint, frontend modal, frontend integration, with property tests alongside each layer.
|
||||
|
||||
Additionally, GRANITE is added as a fourth workflow type across the entire stack — backend validation, RedirectModal, QueuePanel grouping (Inventory section), and AddToQueue popover.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Fix PUT endpoint validation message
|
||||
- [x] 1.1 Update PUT `/:id` workflow_type error message in `backend/routes/ivantiTodoQueue.js`
|
||||
- Change `"workflow_type must be FP or Archer."` to `"workflow_type must be FP, Archer, or CARD."`
|
||||
- _Requirements: 5.1_
|
||||
|
||||
- [x] 2. Add redirect endpoint to backend
|
||||
- [x] 2.1 Add `POST /:id/redirect` route in `backend/routes/ivantiTodoQueue.js`
|
||||
- Place inside the existing `createIvantiTodoQueueRouter` factory, before the DELETE routes
|
||||
- Auth: `requireAuth(db)`, `requireGroup('Admin', 'Standard_User')`
|
||||
- Validate `workflow_type` against existing `VALID_WORKFLOW_TYPES` constant
|
||||
- For FP/Archer: validate vendor using existing `isValidVendor()` helper; also check length ≤ 200
|
||||
- For CARD: accept without vendor
|
||||
- Fetch original item with `db.get()` scoped to `req.user.id`; return 404 if not found
|
||||
- Return 400 if original item status is not `"complete"`
|
||||
- INSERT new row copying finding_id, finding_title, cves_json, ip_address, hostname from original; set status `"pending"`, workflow_type and vendor from request body
|
||||
- Fetch the inserted row, parse cves_json, return 201 with the new item
|
||||
- Call `logAudit(db, ...)` fire-and-forget with action `"queue_item_redirected"`, entityType `"ivanti_todo_queue"`, entityId = original item ID, details: `{ original_workflow_type, target_workflow_type, new_item_id, vendor }`
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 2.1, 2.2_
|
||||
|
||||
- [x] 3. Checkpoint — Verify backend changes
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 4. Create RedirectModal frontend component
|
||||
- [x] 4.1 Create `frontend/src/components/RedirectModal.js`
|
||||
- Props: `item` (the completed queue item), `onClose` (function), `onRedirect` (function called with new item)
|
||||
- Display read-only context: finding title, finding ID, current workflow type
|
||||
- Workflow type selector (radio buttons or select) with options FP, Archer, CARD
|
||||
- Vendor text input shown only when FP or Archer is selected; required for those types
|
||||
- Submit button calls `POST /api/ivanti/todo-queue/${item.id}/redirect` with `credentials: 'include'`
|
||||
- On success: call `onRedirect(newItem)`, close modal
|
||||
- On error: display error message from API response, keep modal open
|
||||
- Loading state on submit button to prevent double-clicks
|
||||
- Style with inline style objects following DESIGN_SYSTEM.md (dark theme, accent borders, gradient backgrounds)
|
||||
- Use lucide-react icons (e.g., `CornerUpRight` or `ArrowRightLeft`)
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7_
|
||||
|
||||
- [x] 5. Integrate redirect button and modal into QueuePanel
|
||||
- [x] 5.1 Add redirect button to completed items in QueuePanel (inside `frontend/src/components/pages/ReportingPage.js`)
|
||||
- Add a redirect icon button (lucide-react) on each completed queue item row, next to the existing delete button
|
||||
- Button visible only when `item.status === 'complete'`; hidden for pending items
|
||||
- _Requirements: 3.1, 3.2_
|
||||
|
||||
- [x] 5.2 Wire RedirectModal state and rendering in QueuePanel
|
||||
- Add `redirectItem` state (null or the item being redirected)
|
||||
- Clicking the redirect button sets `redirectItem` to that item, opening the modal
|
||||
- On successful redirect (`onRedirect` callback): append the new item to the queue items list, show a success notification, clear `redirectItem`
|
||||
- On close: clear `redirectItem`
|
||||
- Import and render `<RedirectModal>` conditionally when `redirectItem` is set
|
||||
- _Requirements: 3.3, 4.5, 4.7_
|
||||
|
||||
- [x] 6. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [ ] 7. Add GRANITE to backend validation
|
||||
- [ ] 7.1 Update `VALID_WORKFLOW_TYPES` constant in `backend/routes/ivantiTodoQueue.js`
|
||||
- Change from `['FP', 'Archer', 'CARD']` to `['FP', 'Archer', 'CARD', 'GRANITE']`
|
||||
- _Requirements: 6.1_
|
||||
|
||||
- [ ] 7.2 Update vendor validation condition in POST `/` (single add) endpoint
|
||||
- Change `workflow_type !== 'CARD'` to `workflow_type === 'FP' || workflow_type === 'Archer'` (or `!['CARD', 'GRANITE'].includes(workflow_type)`) for the vendor-required check
|
||||
- Change `workflow_type === 'CARD' ? '' : vendor.trim()` to `(workflow_type === 'CARD' || workflow_type === 'GRANITE') ? '' : vendor.trim()` for vendorVal assignment
|
||||
- _Requirements: 6.2_
|
||||
|
||||
- [ ] 7.3 Update vendor validation condition in POST `/batch` endpoint
|
||||
- Change `workflow_type !== 'CARD'` to `workflow_type === 'FP' || workflow_type === 'Archer'` for the vendor-required check
|
||||
- Change `workflow_type === 'CARD' ? '' : vendor.trim()` to `(workflow_type === 'CARD' || workflow_type === 'GRANITE') ? '' : vendor.trim()` for vendorVal assignment
|
||||
- _Requirements: 6.2_
|
||||
|
||||
- [ ] 7.4 Update vendor validation condition in POST `/:id/redirect` endpoint
|
||||
- Change `workflow_type !== 'CARD'` to `workflow_type === 'FP' || workflow_type === 'Archer'` for the vendor-required check
|
||||
- Change `workflow_type === 'CARD' ? '' : vendor.trim()` to `(workflow_type === 'CARD' || workflow_type === 'GRANITE') ? '' : vendor.trim()` for vendorVal assignment
|
||||
- _Requirements: 6.2_
|
||||
|
||||
- [ ] 7.5 Update all error messages across all endpoints
|
||||
- Change `"workflow_type must be FP, Archer, or CARD."` to `"workflow_type must be FP, Archer, CARD, or GRANITE."` in POST `/`, POST `/batch`, PUT `/:id`, and POST `/:id/redirect`
|
||||
- _Requirements: 5.1, 6.3_
|
||||
|
||||
- [ ] 8. Add GRANITE to RedirectModal
|
||||
- [ ] 8.1 Update `WORKFLOW_OPTIONS` in `frontend/src/components/RedirectModal.js`
|
||||
- Add `{ key: 'GRANITE', label: 'GRANITE', col: '#A1887F', rgb: '161,136,127' }` as the fourth option
|
||||
- Vendor field already hidden for non-FP/Archer types via `needsVendor` check — no change needed there
|
||||
- _Requirements: 4.1, 4.3_
|
||||
|
||||
- [ ] 9. Update QueuePanel grouping for Inventory section
|
||||
- [ ] 9.1 Update the `grouped` useMemo in QueuePanel (`frontend/src/components/pages/ReportingPage.js`)
|
||||
- Change `items.filter((i) => i.workflow_type === 'CARD')` to filter both CARD and GRANITE into inventory items
|
||||
- Split inventory items into `cardItems` and `graniteItems` sub-arrays
|
||||
- Change `otherItems` filter from `i.workflow_type !== 'CARD'` to exclude both CARD and GRANITE
|
||||
- Rename group key from `__CARD__` to `__INVENTORY__`, label from `'CARD'` to `'Inventory'`, and `isCard` to `isInventory`
|
||||
- Include `cardItems` and `graniteItems` as separate properties on the inventory group object
|
||||
- _Requirements: 7.1, 7.5_
|
||||
|
||||
- [ ] 9.2 Update the QueuePanel rendering to handle the Inventory section
|
||||
- Update the `.map()` destructuring from `isCard` to `isInventory`
|
||||
- Update group header border and label color to use `isInventory` instead of `isCard`
|
||||
- For the Inventory group, render CARD items first, then a subtle sub-divider (only when both `cardItems.length > 0` and `graniteItems.length > 0`), then GRANITE items
|
||||
- _Requirements: 7.1, 7.2, 7.5_
|
||||
|
||||
- [ ] 9.3 Update the workflow type color mapping in QueuePanel item rendering
|
||||
- Add GRANITE to the `wfColor` ternary: `item.workflow_type === 'GRANITE' ? { col: '#A1887F', rgb: '161,136,127' }` before the default CARD fallback
|
||||
- _Requirements: 7.3, 7.4_
|
||||
|
||||
- [ ] 9.4 Update `isCardItem` to `isInventoryItem` in QueuePanel item rendering
|
||||
- Change `const isCardItem = item.workflow_type === 'CARD'` to `const isInventoryItem = item.workflow_type === 'CARD' || item.workflow_type === 'GRANITE'`
|
||||
- Update the conditional rendering that uses `isCardItem` to use `isInventoryItem` (hostname/ip_address display vs CVE display)
|
||||
- _Requirements: 7.1_
|
||||
|
||||
- [ ] 10. Add GRANITE to AddToQueuePopover
|
||||
- [ ] 10.1 Update workflow type buttons in `AddToQueuePopover` (`frontend/src/components/pages/ReportingPage.js`)
|
||||
- Add `{ key: 'GRANITE', col: '#A1887F', rgb: '161,136,127' }` as the fourth button in the workflow type toggle array
|
||||
- _Requirements: 8.1, 8.3_
|
||||
|
||||
- [ ] 10.2 Update `isCard` condition in `AddToQueuePopover` to include GRANITE
|
||||
- Change `const isCard = queueForm.workflowType === 'CARD'` to `const isCard = queueForm.workflowType === 'CARD' || queueForm.workflowType === 'GRANITE'` (or rename to `isInventory`)
|
||||
- This controls the "No vendor required" message and hides the vendor input for GRANITE
|
||||
- _Requirements: 8.2_
|
||||
|
||||
- [ ] 10.3 Update `SelectionToolbar` component to include GRANITE
|
||||
- Add `{ type: 'GRANITE', color: '#A1887F', rgb: '161,136,127' }` as the fourth button in the workflow type toggles array
|
||||
- Change `const isCard = workflowType === 'CARD'` to include GRANITE: `const isCard = workflowType === 'CARD' || workflowType === 'GRANITE'`
|
||||
- _Requirements: 8.1, 8.2, 8.3_
|
||||
|
||||
- [ ] 11. Final checkpoint — Verify all GRANITE changes
|
||||
- Ensure all changes compile and render correctly, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks 1–6 are the original redirect feature tasks, all completed
|
||||
- Tasks 7–11 are the new GRANITE workflow type additions
|
||||
- No test tasks included per user request — testing will be done manually on the dev server
|
||||
- Each task references specific requirements for traceability
|
||||
- The QueuePanel component is defined inside `ReportingPage.js`, not a separate file
|
||||
- The project uses plain JavaScript (no TypeScript)
|
||||
1
.kiro/specs/queue-hostname-ip-display/.config.kiro
Normal file
1
.kiro/specs/queue-hostname-ip-display/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "b8855eb4-3949-426e-86ac-36fe069a6bb1", "workflowType": "requirements-first", "specType": "feature"}
|
||||
175
.kiro/specs/queue-hostname-ip-display/design.md
Normal file
175
.kiro/specs/queue-hostname-ip-display/design.md
Normal file
@@ -0,0 +1,175 @@
|
||||
# Design Document: Queue Hostname & IP Display
|
||||
|
||||
## Overview
|
||||
|
||||
This feature adds hostname tracking to the Ivanti todo queue. Currently the queue stores `ip_address` but not `hostname`. The change spans three layers:
|
||||
|
||||
1. **Database** — A migration adds a `hostname TEXT` column to `ivanti_todo_queue`.
|
||||
2. **Backend API** — The POST (single + batch) endpoints accept and store an optional `hostname` field. The GET endpoint already uses `SELECT *`, so hostname is returned automatically once the column exists.
|
||||
3. **Frontend** — The `addToQueue` and `submitBatch` functions pass `finding.hostName` as `hostname`. The QueuePanel renders hostname and IP address for both CARD and vendor-grouped (FP/Archer) sections.
|
||||
|
||||
The change is additive and backward-compatible. Existing rows get `NULL` for hostname. No existing behavior changes unless both hostname and ip_address are present.
|
||||
|
||||
## Architecture
|
||||
|
||||
The data flows through three layers in a straight pipeline:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[Ivanti Finding<br/>hostName, ipAddress] -->|POST /todo-queue| B[Express Route<br/>ivantiTodoQueue.js]
|
||||
B -->|INSERT hostname, ip_address| C[SQLite<br/>ivanti_todo_queue]
|
||||
C -->|SELECT *| B
|
||||
B -->|GET response| D[QueuePanel<br/>ReportingPage.js]
|
||||
```
|
||||
|
||||
No new services, tables, or route modules are introduced. The migration script is a standalone Node.js file following the existing pattern in `backend/migrations/`.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Migration Script: `backend/migrations/add_todo_queue_hostname.js`
|
||||
|
||||
Follows the exact pattern of `add_todo_queue_ip_address.js`:
|
||||
|
||||
- Opens `cve_database.db` via `sqlite3`
|
||||
- Runs `ALTER TABLE ivanti_todo_queue ADD COLUMN hostname TEXT`
|
||||
- Catches `duplicate column name` error to make it idempotent
|
||||
- Closes the database connection
|
||||
|
||||
### Backend Route: `backend/routes/ivantiTodoQueue.js`
|
||||
|
||||
Changes to two endpoints:
|
||||
|
||||
**POST `/` (single-item)**
|
||||
- Extract `hostname` from `req.body`
|
||||
- Sanitize: if present and a string, trim and slice to 255 chars; otherwise `null`
|
||||
- Add to the INSERT column list and parameter array
|
||||
|
||||
**POST `/batch`**
|
||||
- For each finding in the `findings` array, extract `hostname` from `f.hostname`
|
||||
- Same sanitization as single-item
|
||||
- Add to the per-row INSERT column list and parameter array
|
||||
|
||||
**GET `/`** — No code change needed. `SELECT *` already returns all columns.
|
||||
|
||||
**PUT `/:id`** — No change. Hostname is set at insert time and not editable.
|
||||
|
||||
### Frontend: `ReportingPage.js`
|
||||
|
||||
**`addToQueue` function**
|
||||
- Add `hostname: finding.hostName || null` to the POST body
|
||||
|
||||
**`submitBatch` function**
|
||||
- Add `hostname: f.hostName || null` to each finding object in `findingsPayload`
|
||||
|
||||
**QueuePanel rendering (per item)**
|
||||
|
||||
For CARD items, the content `<div>` currently shows:
|
||||
1. `finding_id`
|
||||
2. `ip_address` (if present)
|
||||
|
||||
New rendering for CARD items:
|
||||
1. `finding_id`
|
||||
2. `hostname` (if present)
|
||||
3. `ip_address` (if present)
|
||||
|
||||
For vendor-grouped items (FP/Archer), the content `<div>` currently shows:
|
||||
1. `finding_id`
|
||||
2. CVE list (if present)
|
||||
|
||||
New rendering for vendor-grouped items:
|
||||
1. `finding_id`
|
||||
2. CVE list (if present)
|
||||
3. `hostname` (if present)
|
||||
4. `ip_address` (if present)
|
||||
|
||||
Both hostname and IP use the same monospace styling at `0.68rem` / `0.62rem` with muted colors consistent with the existing design system.
|
||||
|
||||
## Data Models
|
||||
|
||||
### `ivanti_todo_queue` table (after migration)
|
||||
|
||||
| Column | Type | Nullable | Notes |
|
||||
|--------|------|----------|-------|
|
||||
| id | INTEGER | NO | PRIMARY KEY AUTOINCREMENT |
|
||||
| user_id | INTEGER | NO | FK → users(id) |
|
||||
| finding_id | TEXT | NO | |
|
||||
| finding_title | TEXT | YES | max 500 chars |
|
||||
| cves_json | TEXT | YES | JSON array string |
|
||||
| ip_address | TEXT | YES | max 64 chars |
|
||||
| **hostname** | **TEXT** | **YES** | **max 255 chars (new)** |
|
||||
| vendor | TEXT | NO | |
|
||||
| workflow_type | TEXT | NO | FP, Archer, or CARD |
|
||||
| status | TEXT | NO | pending or complete |
|
||||
| created_at | DATETIME | NO | DEFAULT CURRENT_TIMESTAMP |
|
||||
| updated_at | DATETIME | NO | DEFAULT CURRENT_TIMESTAMP |
|
||||
|
||||
### API Request/Response Changes
|
||||
|
||||
**POST `/api/ivanti/todo-queue` body** — adds optional field:
|
||||
```json
|
||||
{
|
||||
"finding_id": "...",
|
||||
"finding_title": "...",
|
||||
"cves": [],
|
||||
"ip_address": "...",
|
||||
"hostname": "server01.example.com",
|
||||
"vendor": "...",
|
||||
"workflow_type": "CARD"
|
||||
}
|
||||
```
|
||||
|
||||
**POST `/api/ivanti/todo-queue/batch` body** — adds optional field per finding:
|
||||
```json
|
||||
{
|
||||
"findings": [
|
||||
{ "finding_id": "...", "ip_address": "...", "hostname": "server01.example.com" }
|
||||
],
|
||||
"workflow_type": "FP",
|
||||
"vendor": "VendorName"
|
||||
}
|
||||
```
|
||||
|
||||
**GET response** — `hostname` field included automatically via `SELECT *`:
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"finding_id": "...",
|
||||
"hostname": "server01.example.com",
|
||||
"ip_address": "10.0.0.1",
|
||||
"..."
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 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: Hostname storage round-trip
|
||||
|
||||
*For any* valid hostname string (up to 255 characters), storing it via the queue API (single or batch endpoint) and then retrieving it via GET should return the exact same trimmed string. When the hostname is omitted, null, or empty, the stored and returned value should be null.
|
||||
|
||||
**Validates: Requirements 2.1, 2.2, 2.3, 2.4**
|
||||
|
||||
### Property 2: Hostname display presence
|
||||
|
||||
*For any* queue item with a non-null hostname value, the rendered QueuePanel output should contain the hostname text, regardless of whether the item is a CARD item or a vendor-grouped (FP/Archer) item.
|
||||
|
||||
**Validates: Requirements 4.1, 5.1**
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| Migration run when column already exists | Catch `duplicate column name` SQLite error, log skip message, exit cleanly |
|
||||
| `hostname` field is not a string | Treat as null — store NULL in database |
|
||||
| `hostname` exceeds 255 characters | Truncate to 255 characters via `.slice(0, 255)` |
|
||||
| `hostname` is undefined/null/empty string | Store NULL in database |
|
||||
| GET returns item with null hostname | Frontend conditionally renders — no hostname line shown |
|
||||
| GET returns item with null ip_address and null hostname | CARD: show only finding_id. Vendor: show finding_id + CVEs only |
|
||||
|
||||
No new error codes or HTTP status changes are introduced. The hostname field is optional and its absence is a normal case, not an error.
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
Testing is out of scope for this feature. Manual verification will be performed after implementation.
|
||||
70
.kiro/specs/queue-hostname-ip-display/requirements.md
Normal file
70
.kiro/specs/queue-hostname-ip-display/requirements.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The Ivanti Queue (todo queue) in the STEAM Security Dashboard currently stores and displays `ip_address` for CARD workflow items but omits hostname entirely. Vendor-grouped sections (FP/Archer) display only `finding_id` and CVEs, hiding the `ip_address` that is already stored. This feature adds a `hostname` column to the database, passes hostname through the backend API, and displays both hostname and IP address across all queue sections (CARD, FP, Archer).
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Queue_Panel**: The slide-out side panel (`QueuePanel` component) that displays the user's staged Ivanti findings grouped by workflow type and vendor.
|
||||
- **Queue_API**: The Express route module (`ivantiTodoQueue.js`) that handles CRUD operations on the `ivanti_todo_queue` table.
|
||||
- **Queue_Table**: The SQLite table `ivanti_todo_queue` that persists per-user queue items.
|
||||
- **CARD_Section**: The top group in the Queue_Panel that displays items with `workflow_type = 'CARD'`.
|
||||
- **Vendor_Section**: Groups in the Queue_Panel for FP and Archer workflow items, organized by vendor name.
|
||||
- **Finding**: An Ivanti host finding record containing fields such as `id`, `title`, `hostName`, `ipAddress`, `cves`, and `severity`.
|
||||
- **Migration_Script**: A standalone Node.js script in `backend/migrations/` that alters the SQLite schema.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Add hostname column to the queue database table
|
||||
|
||||
**User Story:** As a developer, I want the queue table to have a `hostname` column, so that hostname data can be persisted alongside each queued finding.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Migration_Script SHALL add a `hostname` TEXT column to the Queue_Table.
|
||||
2. WHEN the `hostname` column already exists, THE Migration_Script SHALL skip the alteration and log a message indicating the column already exists.
|
||||
3. THE Migration_Script SHALL preserve all existing rows and column data in the Queue_Table.
|
||||
|
||||
### Requirement 2: Accept and store hostname in queue API endpoints
|
||||
|
||||
**User Story:** As a developer, I want the queue API to accept a `hostname` field, so that hostname data is stored when findings are added to the queue.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a POST request is received at the single-item endpoint, THE Queue_API SHALL accept an optional `hostname` string field (max 255 characters) and store it in the Queue_Table.
|
||||
2. WHEN a POST request is received at the batch endpoint, THE Queue_API SHALL accept an optional `hostname` string field on each finding object (max 255 characters) and store it in the Queue_Table.
|
||||
3. WHEN the `hostname` field is omitted or empty, THE Queue_API SHALL store NULL for the `hostname` column.
|
||||
4. WHEN a GET request is received, THE Queue_API SHALL return the `hostname` field for each queue item in the response.
|
||||
|
||||
### Requirement 3: Pass hostname from the frontend to the queue API
|
||||
|
||||
**User Story:** As a developer, I want the frontend to send hostname data when adding findings to the queue, so that hostname is captured from the Ivanti findings data.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a single finding is added to the queue, THE ReportingPage SHALL include the finding's `hostName` value in the `hostname` field of the POST request body.
|
||||
2. WHEN findings are added via batch submission, THE ReportingPage SHALL include each finding's `hostName` value in the `hostname` field of the corresponding finding object in the POST request body.
|
||||
|
||||
### Requirement 4: Display hostname and IP address in the CARD section
|
||||
|
||||
**User Story:** As a security analyst, I want to see both hostname and IP address for CARD items in the queue, so that I can identify the affected host at a glance.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a CARD item has a `hostname` value, THE CARD_Section SHALL display the hostname below the finding ID.
|
||||
2. WHEN a CARD item has an `ip_address` value, THE CARD_Section SHALL display the IP address below the hostname.
|
||||
3. WHEN a CARD item has both `hostname` and `ip_address`, THE CARD_Section SHALL display hostname on one line and IP address on the next line.
|
||||
4. WHEN a CARD item has only `ip_address` and no `hostname`, THE CARD_Section SHALL display the IP address (preserving current behavior).
|
||||
5. WHEN a CARD item has only `hostname` and no `ip_address`, THE CARD_Section SHALL display the hostname.
|
||||
|
||||
### Requirement 5: Display hostname and IP address in vendor sections (FP/Archer)
|
||||
|
||||
**User Story:** As a security analyst, I want to see hostname and IP address for FP and Archer items in the queue, so that I can identify affected hosts without leaving the queue panel.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a vendor-grouped item has a `hostname` value, THE Vendor_Section SHALL display the hostname below the CVE list.
|
||||
2. WHEN a vendor-grouped item has an `ip_address` value, THE Vendor_Section SHALL display the IP address below the hostname (or below the CVE list if no hostname exists).
|
||||
3. WHEN a vendor-grouped item has both `hostname` and `ip_address`, THE Vendor_Section SHALL display hostname on one line and IP address on the next line, both below the CVE list.
|
||||
4. WHEN a vendor-grouped item has neither `hostname` nor `ip_address`, THE Vendor_Section SHALL display only the finding ID and CVE list (preserving current behavior).
|
||||
56
.kiro/specs/queue-hostname-ip-display/tasks.md
Normal file
56
.kiro/specs/queue-hostname-ip-display/tasks.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# Implementation Plan: Queue Hostname & IP Display
|
||||
|
||||
## Overview
|
||||
|
||||
Add hostname tracking to the Ivanti todo queue across database, backend API, and frontend display layers. All changes are additive and backward-compatible.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Create database migration to add hostname column
|
||||
- Create `backend/migrations/add_todo_queue_hostname.js` following the exact pattern of `add_todo_queue_ip_address.js`
|
||||
- Use `ALTER TABLE ivanti_todo_queue ADD COLUMN hostname TEXT`
|
||||
- Handle `duplicate column name` error for idempotency
|
||||
- Log appropriate messages for success and skip scenarios
|
||||
- _Requirements: 1.1, 1.2, 1.3_
|
||||
|
||||
- [x] 2. Update backend API endpoints to accept and store hostname
|
||||
- [x] 2.1 Update POST `/` (single-item) endpoint in `backend/routes/ivantiTodoQueue.js`
|
||||
- Extract `hostname` from `req.body`
|
||||
- Sanitize: if present and a string, trim and slice to 255 chars; otherwise `null`
|
||||
- Add `hostname` to the INSERT column list and parameter array
|
||||
- _Requirements: 2.1, 2.3_
|
||||
|
||||
- [x] 2.2 Update POST `/batch` endpoint in `backend/routes/ivantiTodoQueue.js`
|
||||
- For each finding, extract `hostname` from `f.hostname`
|
||||
- Apply same sanitization as single-item (trim, slice to 255, or null)
|
||||
- Add `hostname` to the per-row INSERT column list and parameter array
|
||||
- _Requirements: 2.2, 2.3_
|
||||
|
||||
- [x] 3. Checkpoint
|
||||
- Ensure all backend changes are consistent, ask the user if questions arise.
|
||||
|
||||
- [x] 4. Update frontend to pass hostname and display it in the queue panel
|
||||
- [x] 4.1 Update `addToQueue` function in `ReportingPage.js`
|
||||
- Add `hostname: finding.hostName || null` to the POST request body
|
||||
- _Requirements: 3.1_
|
||||
|
||||
- [x] 4.2 Update `submitBatch` function in `ReportingPage.js`
|
||||
- Add `hostname: f.hostName || null` to each finding object in the payload
|
||||
- _Requirements: 3.2_
|
||||
|
||||
- [x] 4.3 Update CARD section rendering in QueuePanel (`ReportingPage.js`)
|
||||
- Display `hostname` below finding_id (when present)
|
||||
- Display `ip_address` below hostname (when present)
|
||||
- Handle all combinations: both present, only hostname, only ip_address, neither
|
||||
- Use monospace styling at `0.68rem` consistent with existing ip_address display
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5_
|
||||
|
||||
- [x] 4.4 Update vendor section (FP/Archer) rendering in QueuePanel (`ReportingPage.js`)
|
||||
- Display `hostname` below the CVE list (when present)
|
||||
- Display `ip_address` below hostname or below CVE list if no hostname
|
||||
- Handle all combinations: both present, only one, neither
|
||||
- Use monospace styling at `0.62rem` / `0.68rem` with muted colors matching existing design
|
||||
- _Requirements: 5.1, 5.2, 5.3, 5.4_
|
||||
|
||||
- [x] 5. Final checkpoint
|
||||
- Ensure all changes are wired together end-to-end, ask the user if questions arise.
|
||||
1
.kiro/specs/reporting-row-visibility/.config.kiro
Normal file
1
.kiro/specs/reporting-row-visibility/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "acff93bd-0045-4fcd-b948-cc52c7cc5ec6", "workflowType": "requirements-first", "specType": "feature"}
|
||||
400
.kiro/specs/reporting-row-visibility/design.md
Normal file
400
.kiro/specs/reporting-row-visibility/design.md
Normal file
@@ -0,0 +1,400 @@
|
||||
# Design Document: Reporting Row Visibility
|
||||
|
||||
## Overview
|
||||
|
||||
This feature adds row-level visibility controls to the Reporting page's findings table, allowing security analysts to temporarily hide specific rows from view. Hidden rows are excluded from the visible table, the Action Coverage donut chart, and CSV/XLSX exports. The feature is entirely frontend — no backend changes are needed. All state is persisted in browser localStorage.
|
||||
|
||||
The feature consists of five interconnected pieces:
|
||||
|
||||
1. **Per-row hide button** — An `EyeOff` icon button on each table row that hides that finding
|
||||
2. **Bulk select and hide** — Checkboxes on each row, a select-all checkbox, and a bulk action toolbar for hiding multiple rows at once
|
||||
3. **Row Visibility Manager** — A toolbar popover (modeled after the existing `ColumnManager`) for viewing and restoring hidden rows
|
||||
4. **Chart integration** — The Action Coverage donut chart recalculates using only visible (non-hidden) findings
|
||||
5. **Export integration** — CSV and XLSX exports include only visible rows
|
||||
|
||||
### Design Decisions
|
||||
|
||||
- **localStorage over backend storage**: Row visibility is a personal view preference, not shared team state. Storing it in localStorage keeps the feature zero-cost on the backend and avoids auth/permission complexity. This mirrors how column visibility is already handled via `STORAGE_KEY`.
|
||||
- **Hide-before-filter pipeline**: Hidden rows are removed from the dataset before column filters, action coverage filters, and EXC filters are applied. This ensures hidden rows never appear in filter dropdowns or affect filter counts.
|
||||
- **Stale IDs are retained silently**: If a hidden Finding_ID no longer exists after an Ivanti sync, the ID stays in localStorage. This avoids the need for cleanup logic and ensures the finding is re-hidden if it reappears in a future sync.
|
||||
- **Selection state is transient**: The checkbox selection state (`Row_Selection_State`) is not persisted. It resets on page reload and clears after a bulk hide operation.
|
||||
|
||||
## Architecture
|
||||
|
||||
The feature is contained entirely within `frontend/src/components/pages/ReportingPage.js`. No new files are created. The changes integrate into the existing component hierarchy and data flow.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph ReportingPage State
|
||||
A[findings - raw from API] --> B[hiddenRowIds - from localStorage]
|
||||
B --> C[visibleFindings = findings minus hiddenRowIds]
|
||||
C --> D[filtered - column/action/EXC filters applied]
|
||||
D --> E[sorted - sort order applied]
|
||||
E --> F[Table rows rendered]
|
||||
C --> G[ActionCoverageDonut receives visibleFindings]
|
||||
E --> H[Export functions use sorted visible rows]
|
||||
end
|
||||
|
||||
subgraph New Components
|
||||
I[RowVisibilityManager popover]
|
||||
J[BulkActionToolbar]
|
||||
K[Selection checkboxes]
|
||||
L[Per-row hide button]
|
||||
end
|
||||
|
||||
I -->|restore| B
|
||||
J -->|bulk hide| B
|
||||
L -->|single hide| B
|
||||
K -->|toggle selection| M[selectedRowIds - transient state]
|
||||
M --> J
|
||||
```
|
||||
|
||||
### Data Flow Pipeline
|
||||
|
||||
The existing filtering pipeline in `VulnerabilityTriagePage` is:
|
||||
|
||||
```
|
||||
findings → columnFilters → actionFilter → excFilter → sorted → rendered/exported
|
||||
```
|
||||
|
||||
The new pipeline inserts row hiding as the first step:
|
||||
|
||||
```
|
||||
findings → HIDE (remove hiddenRowIds) → columnFilters → actionFilter → excFilter → sorted → rendered/exported
|
||||
```
|
||||
|
||||
This ensures hidden rows are excluded before any other filtering logic runs.
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### 1. Hidden Row State Management
|
||||
|
||||
New state and helpers added to `VulnerabilityTriagePage`:
|
||||
|
||||
```javascript
|
||||
const HIDDEN_ROWS_KEY = 'steam_findings_hidden_rows';
|
||||
|
||||
// Load hidden row IDs from localStorage
|
||||
function loadHiddenRows() {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(HIDDEN_ROWS_KEY) || 'null');
|
||||
if (saved && Array.isArray(saved)) return new Set(saved);
|
||||
} catch { /* corrupted — treat as empty */ }
|
||||
return new Set();
|
||||
}
|
||||
|
||||
// Persist hidden row IDs to localStorage
|
||||
function saveHiddenRows(hiddenSet) {
|
||||
try {
|
||||
localStorage.setItem(HIDDEN_ROWS_KEY, JSON.stringify([...hiddenSet]));
|
||||
} catch { /* localStorage unavailable — degrade silently */ }
|
||||
}
|
||||
```
|
||||
|
||||
**State declarations:**
|
||||
|
||||
```javascript
|
||||
const [hiddenRowIds, setHiddenRowIds] = useState(loadHiddenRows);
|
||||
const [selectedRowIds, setSelectedRowIds] = useState(new Set());
|
||||
```
|
||||
|
||||
**Hide/restore operations:**
|
||||
|
||||
```javascript
|
||||
// Hide a single row
|
||||
const hideRow = useCallback((findingId) => {
|
||||
setHiddenRowIds(prev => {
|
||||
const next = new Set(prev);
|
||||
next.add(String(findingId));
|
||||
saveHiddenRows(next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Restore a single row
|
||||
const restoreRow = useCallback((findingId) => {
|
||||
setHiddenRowIds(prev => {
|
||||
const next = new Set(prev);
|
||||
next.delete(String(findingId));
|
||||
saveHiddenRows(next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Restore all hidden rows
|
||||
const restoreAllRows = useCallback(() => {
|
||||
setHiddenRowIds(new Set());
|
||||
saveHiddenRows(new Set());
|
||||
}, []);
|
||||
|
||||
// Bulk hide selected rows
|
||||
const hideSelectedRows = useCallback(() => {
|
||||
setHiddenRowIds(prev => {
|
||||
const next = new Set(prev);
|
||||
selectedRowIds.forEach(id => next.add(String(id)));
|
||||
saveHiddenRows(next);
|
||||
return next;
|
||||
});
|
||||
setSelectedRowIds(new Set());
|
||||
}, [selectedRowIds]);
|
||||
```
|
||||
|
||||
### 2. Modified Filtering Pipeline
|
||||
|
||||
The existing `filtered` useMemo is modified to exclude hidden rows first:
|
||||
|
||||
```javascript
|
||||
// New: visible findings (hidden rows removed) — fed to ActionCoverageDonut
|
||||
const visibleFindings = useMemo(() => {
|
||||
if (hiddenRowIds.size === 0) return findings;
|
||||
return findings.filter(f => !hiddenRowIds.has(String(f.id)));
|
||||
}, [findings, hiddenRowIds]);
|
||||
|
||||
// Modified: filtered now starts from visibleFindings instead of findings
|
||||
const filtered = useMemo(() => {
|
||||
let result = visibleFindings;
|
||||
// ... existing column filter, action filter, EXC filter logic unchanged
|
||||
}, [visibleFindings, columnFilters, actionFilter, excFilter]);
|
||||
```
|
||||
|
||||
The `ActionCoverageDonut` receives `visibleFindings` instead of `findings`:
|
||||
|
||||
```jsx
|
||||
<ActionCoverageDonut
|
||||
findings={visibleFindings} // was: findings
|
||||
activeSegment={actionFilter}
|
||||
onSegmentClick={...}
|
||||
/>
|
||||
```
|
||||
|
||||
### 3. Selection State Management
|
||||
|
||||
```javascript
|
||||
// Clear selection when visible rows change (filter changes)
|
||||
useEffect(() => {
|
||||
setSelectedRowIds(prev => {
|
||||
const visibleIds = new Set(sorted.map(f => String(f.id)));
|
||||
const next = new Set([...prev].filter(id => visibleIds.has(id)));
|
||||
return next.size === prev.size ? prev : next;
|
||||
});
|
||||
}, [sorted]);
|
||||
|
||||
// Toggle a single row's selection
|
||||
const toggleRowSelection = useCallback((findingId) => {
|
||||
setSelectedRowIds(prev => {
|
||||
const next = new Set(prev);
|
||||
const id = String(findingId);
|
||||
if (next.has(id)) next.delete(id); else next.add(id);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Select/deselect all visible rows
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
const allVisibleIds = sorted.map(f => String(f.id));
|
||||
setSelectedRowIds(prev => {
|
||||
if (prev.size === allVisibleIds.length) return new Set(); // deselect all
|
||||
return new Set(allVisibleIds); // select all
|
||||
});
|
||||
}, [sorted]);
|
||||
```
|
||||
|
||||
### 4. RowVisibilityManager Component
|
||||
|
||||
A new component following the same pattern as `ColumnManager`:
|
||||
|
||||
```javascript
|
||||
function RowVisibilityManager({ hiddenRowIds, findings, onRestore, onRestoreAll }) {
|
||||
// Props:
|
||||
// hiddenRowIds: Set<string> — currently hidden finding IDs
|
||||
// findings: Array — full findings array (to look up titles for hidden IDs)
|
||||
// onRestore: (findingId: string) => void
|
||||
// onRestoreAll: () => void
|
||||
//
|
||||
// State:
|
||||
// open: boolean — popover visibility
|
||||
//
|
||||
// Behavior:
|
||||
// - Button shows EyeOff icon + "Hidden (N)" count
|
||||
// - Popover lists hidden findings by ID and title
|
||||
// - Each entry has an Eye icon restore button
|
||||
// - "Restore All" button at the bottom
|
||||
// - When hiddenRowIds.size === 0, popover shows "No rows hidden" message
|
||||
// - Closes on outside click (same pattern as ColumnManager)
|
||||
}
|
||||
```
|
||||
|
||||
**Placement:** Rendered in the toolbar `div` adjacent to the `ColumnManager` button, between the ColumnManager and the Sync button.
|
||||
|
||||
### 5. BulkActionToolbar Component
|
||||
|
||||
Rendered above the table when `selectedRowIds.size > 0`:
|
||||
|
||||
```javascript
|
||||
function BulkHideToolbar({ count, onHide, onClear }) {
|
||||
// Props:
|
||||
// count: number — selected row count
|
||||
// onHide: () => void — hide all selected rows
|
||||
// onClear: () => void — clear selection
|
||||
//
|
||||
// Renders:
|
||||
// "{count} rows selected" label
|
||||
// "Hide Selected" button with EyeOff icon
|
||||
// "Clear" button to deselect all
|
||||
}
|
||||
```
|
||||
|
||||
**Placement:** Rendered inside the table scroll container, above the `<table>` element, in the same position as the existing `SelectionToolbar` for batch FP submissions. The bulk hide toolbar appears alongside (or replaces) the existing selection toolbar depending on context.
|
||||
|
||||
### 6. Per-Row Hide Button and Selection Checkbox
|
||||
|
||||
Two new fixed columns are added to the table, before the existing checkbox column:
|
||||
|
||||
| Column | Width | Content | Position |
|
||||
|--------|-------|---------|----------|
|
||||
| Selection checkbox | 36px | `Square` / `CheckSquare` icon (lucide-react) | First column |
|
||||
| Hide button | 36px | `EyeOff` icon button | Second column |
|
||||
|
||||
Both columns are fixed (not managed by `ColumnManager`) and use sticky positioning in the header.
|
||||
|
||||
### 7. Select All Checkbox
|
||||
|
||||
Rendered in the table header for the selection column:
|
||||
|
||||
- **Unchecked** (`Square` icon): No rows selected
|
||||
- **Checked** (`CheckSquare` icon): All visible rows selected
|
||||
- **Indeterminate** (`MinusSquare` icon): Some but not all visible rows selected
|
||||
|
||||
## Data Models
|
||||
|
||||
### localStorage Schema
|
||||
|
||||
**Key:** `steam_findings_hidden_rows`
|
||||
|
||||
**Value:** JSON array of Finding ID strings
|
||||
|
||||
```json
|
||||
["12345", "67890", "11111"]
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
- Finding IDs are stored as strings for consistent comparison
|
||||
- The array may contain IDs that no longer exist in the current findings dataset (stale IDs are retained)
|
||||
- An empty array `[]` or missing key both mean "no rows hidden"
|
||||
- If the stored value fails JSON parsing, it is treated as empty (all rows visible)
|
||||
|
||||
### Component State
|
||||
|
||||
| State Variable | Type | Persisted | Description |
|
||||
|---------------|------|-----------|-------------|
|
||||
| `hiddenRowIds` | `Set<string>` | Yes (localStorage) | Finding IDs currently hidden |
|
||||
| `selectedRowIds` | `Set<string>` | No (transient) | Finding IDs currently selected via checkboxes |
|
||||
|
||||
### Derived Data
|
||||
|
||||
| Variable | Derivation | Used By |
|
||||
|----------|-----------|---------|
|
||||
| `visibleFindings` | `findings.filter(f => !hiddenRowIds.has(f.id))` | ActionCoverageDonut, filter pipeline |
|
||||
| `filtered` | `visibleFindings` → column filters → action filter → EXC filter | Sort, table render |
|
||||
| `sorted` | `filtered` → sort comparator | Table render, export |
|
||||
|
||||
|
||||
## 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: Hidden row filtering invariant
|
||||
|
||||
*For any* array of findings and *any* set of hidden Finding_IDs, the `visibleFindings` array SHALL never contain a finding whose ID is in the hidden set.
|
||||
|
||||
**Validates: Requirements 1.1, 1.2, 4.1, 4.3, 5.1, 5.2, 6.1, 6.2**
|
||||
|
||||
### Property 2: localStorage round-trip preserves hidden row state
|
||||
|
||||
*For any* set of valid Finding_ID strings, calling `saveHiddenRows(set)` followed by `loadHiddenRows()` SHALL return a set containing exactly the same elements.
|
||||
|
||||
**Validates: Requirements 2.1, 2.2**
|
||||
|
||||
### Property 3: Corrupted localStorage produces empty set
|
||||
|
||||
*For any* string that is not a valid JSON array of strings, `loadHiddenRows()` SHALL return an empty set, and no error SHALL be thrown.
|
||||
|
||||
**Validates: Requirements 2.4**
|
||||
|
||||
### Property 4: Restore removes exactly the specified ID
|
||||
|
||||
*For any* non-empty set of hidden Finding_IDs and *any* ID in that set, calling `restoreRow(id)` SHALL produce a new hidden set that is equal to the original set minus that single ID.
|
||||
|
||||
**Validates: Requirements 3.3**
|
||||
|
||||
### Property 5: Bulk hide produces the union of hidden and selected sets
|
||||
|
||||
*For any* set of currently hidden Finding_IDs and *any* set of selected Finding_IDs, calling `hideSelectedRows()` SHALL produce a hidden set equal to the union of both sets, and the selection set SHALL be empty afterward.
|
||||
|
||||
**Validates: Requirements 8.5, 8.6**
|
||||
|
||||
### Property 6: Selection is always a subset of visible rows
|
||||
|
||||
*For any* set of selected Finding_IDs and *any* change to the visible row set (via filter changes or row hiding), the resulting selection set SHALL be a subset of the current visible row IDs.
|
||||
|
||||
**Validates: Requirements 8.8**
|
||||
|
||||
### Property 7: Select all produces exactly the visible row ID set
|
||||
|
||||
*For any* array of currently visible (sorted) findings, calling `toggleSelectAll` when no rows are selected SHALL produce a selection set equal to the set of all visible Finding_IDs. Calling `toggleSelectAll` when all rows are selected SHALL produce an empty selection set.
|
||||
|
||||
**Validates: Requirements 8.2, 8.3**
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| localStorage unavailable (private browsing, quota exceeded) | `saveHiddenRows` fails silently via try/catch. `loadHiddenRows` returns empty set. All rows remain visible. Feature degrades to session-only (hidden state lost on reload). |
|
||||
| Corrupted localStorage value | `loadHiddenRows` catches JSON parse error and returns empty set. No error shown to user. |
|
||||
| Stale Finding_ID in hidden set (ID no longer in findings after sync) | ID is retained in localStorage. The `filter()` call simply doesn't match any finding, so no visible effect. If the finding reappears in a future sync, it will be hidden again automatically. |
|
||||
| Empty findings array | `visibleFindings` is empty. `selectedRowIds` is empty. Charts show "No data" state. Export produces headers only. All controls render but have no actionable items. |
|
||||
| Bulk hide with empty selection | The "Hide Selected" button is only shown when `selectedRowIds.size > 0`, so this state is unreachable via the UI. If called programmatically, `hideSelectedRows` is a no-op (union with empty set). |
|
||||
| Select all with no visible rows | `toggleSelectAll` produces an empty set (no rows to select). |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
The feature's core logic — set operations, filtering, localStorage serialization — is well-suited for property-based testing. The functions under test are pure or near-pure (localStorage can be mocked), and the input space (sets of string IDs, arrays of finding objects) is large.
|
||||
|
||||
**Library:** [fast-check](https://github.com/dubzzz/fast-check) — the standard PBT library for JavaScript/React projects.
|
||||
|
||||
**Configuration:** Each property test runs a minimum of 100 iterations.
|
||||
|
||||
**Tag format:** Each test is tagged with a comment: `// Feature: reporting-row-visibility, Property N: <property text>`
|
||||
|
||||
**Properties to implement:**
|
||||
|
||||
| Property | Test Description | Key Generators |
|
||||
|----------|-----------------|----------------|
|
||||
| 1 | Filter findings by hidden set, verify no hidden ID in output | `fc.array(findingArb)`, `fc.uniqueArray(fc.string())` |
|
||||
| 2 | Save then load hidden rows, verify round-trip equality | `fc.uniqueArray(fc.stringOf(fc.constantFrom(...digits), {minLength: 1}))` |
|
||||
| 3 | Set corrupted string in localStorage, verify loadHiddenRows returns empty set | `fc.string()` filtered to exclude valid JSON arrays |
|
||||
| 4 | Remove one ID from hidden set, verify set difference | `fc.uniqueArray(fc.string(), {minLength: 1})`, pick random element |
|
||||
| 5 | Union hidden + selected sets, verify result and empty selection | `fc.uniqueArray(fc.string())` × 2 |
|
||||
| 6 | Generate selection + filter change, verify selection ⊆ visible | `fc.uniqueArray(fc.string())` for selection and visible sets |
|
||||
| 7 | Select all from visible set, verify equality; toggle again, verify empty | `fc.array(findingArb)` |
|
||||
|
||||
### Unit Tests (Example-Based)
|
||||
|
||||
Unit tests cover specific scenarios, UI rendering, and edge cases that don't benefit from randomized input:
|
||||
|
||||
- **Hide button renders on each row** (Req 1.3) — verify EyeOff icon in fixed column
|
||||
- **Hide button visible for viewer role** (Req 1.4) — render with read-only auth context
|
||||
- **localStorage write on hide/restore** (Req 2.3) — mock localStorage, verify setItem called
|
||||
- **Row Visibility Manager button shows count** (Req 3.1) — verify "Hidden (N)" text
|
||||
- **Row Visibility Manager popover lists hidden findings** (Req 3.2) — click button, verify list
|
||||
- **Restore All clears all hidden rows** (Req 3.4) — verify empty set after restoreAll
|
||||
- **"Hidden (0)" when no rows hidden** (Req 3.5) — verify button text and empty message
|
||||
- **Chart re-renders after hide** (Req 4.2) — verify ActionCoverageDonut receives updated findings
|
||||
- **Hidden state preserved across sync** (Req 5.3) — simulate sync, verify hiddenRowIds unchanged
|
||||
- **Stale IDs retained silently** (Req 5.4) — hide ID, remove from findings, verify no error
|
||||
- **Bulk action toolbar appears with count** (Req 8.4) — select rows, verify toolbar renders
|
||||
- **Indeterminate checkbox state** (Req 8.9) — partial selection, verify MinusSquare icon
|
||||
- **Toolbar hidden when no selection** (Req 8.10) — empty selection, verify no toolbar
|
||||
- **Styling consistency** (Req 7.1, 7.2, 7.3, 8.11) — snapshot tests for visual consistency
|
||||
115
.kiro/specs/reporting-row-visibility/requirements.md
Normal file
115
.kiro/specs/reporting-row-visibility/requirements.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The Reporting page in the STEAM Security Dashboard displays a table of Ivanti host findings with columns for finding ID, severity, title, CVEs, hostname, IP address, DNS, due date, SLA status, BU ownership, workflow, last found date, and notes. Some findings have manually entered notes such as "NOT STEAM/ACCESS", "MongoDB Update", or other free-text annotations indicating that work is being done outside of the automated FP or Archer exception workflows. These manually-noted findings are classified as "pending" in the Action Coverage donut chart, inflating the pending count even though they represent active remediation efforts.
|
||||
|
||||
Users need the ability to temporarily hide specific rows from the table view — similar to how columns can already be hidden via the ColumnManager popover. Hidden rows should be excluded from the visible table and from the Action Coverage chart calculations, but the underlying data must remain intact. The feature should persist across page reloads and provide a clear mechanism to reveal hidden rows or restore them individually.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Reporting_Table**: The findings data table rendered on the Reporting page, displaying one row per Ivanti host finding with sortable, filterable columns.
|
||||
- **Row_Visibility_State**: A client-side record of which finding IDs have been hidden by the user. Stored in browser localStorage for persistence across sessions.
|
||||
- **Hidden_Row**: A finding whose ID is present in the Row_Visibility_State hidden set. Hidden rows are excluded from the visible table and from chart metric calculations.
|
||||
- **ColumnManager**: The existing popover component on the Reporting page that allows users to show/hide columns and reorder them via drag-and-drop. The row-hiding feature follows a similar UX pattern.
|
||||
- **Action_Coverage_Chart**: The donut chart on the Reporting page that classifies open findings into three categories — FP Request, Archer Exception, and Pending — based on workflow status and note content.
|
||||
- **Row_Visibility_Manager**: A new UI component that provides controls for viewing and restoring hidden rows, analogous to the ColumnManager for columns.
|
||||
- **Finding_ID**: The unique Ivanti-assigned identifier for each host finding, used as the key for tracking hidden rows.
|
||||
- **Row_Selection_State**: A transient client-side record of which Finding_IDs are currently selected via checkboxes. This state is not persisted and resets on page reload or after a bulk action completes.
|
||||
- **Selection_Checkbox**: A checkbox control rendered in a fixed column on each visible row, used to toggle that row's inclusion in the Row_Selection_State.
|
||||
- **Select_All_Checkbox**: A checkbox control rendered in the table header that toggles selection of all currently visible (non-hidden, post-filter) rows.
|
||||
- **Bulk_Action_Toolbar**: A contextual toolbar that appears above the Reporting_Table when one or more rows are selected, displaying the count of selected rows and bulk action controls.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Hide Individual Rows from the Reporting Table
|
||||
|
||||
**User Story:** As a security analyst, I want to hide specific rows in the Reporting table by clicking a hide control on each row, so that I can remove manually-handled findings from view without deleting them.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Reporting_Table SHALL display a hide button on each row that, when clicked, adds the row's Finding_ID to the Row_Visibility_State hidden set.
|
||||
2. WHEN a row's Finding_ID is added to the Row_Visibility_State hidden set, THE Reporting_Table SHALL immediately remove that row from the visible table without a page reload.
|
||||
3. THE hide button SHALL be rendered as an icon button (using the `EyeOff` icon from lucide-react) in a fixed column that is not managed by the ColumnManager.
|
||||
4. WHEN the user has no write permissions (viewer role), THE Reporting_Table SHALL still display the hide button, as row visibility is a personal view preference and not a data modification.
|
||||
|
||||
### Requirement 2: Persist Hidden Row State Across Sessions
|
||||
|
||||
**User Story:** As a security analyst, I want my hidden row selections to persist when I navigate away and return to the Reporting page, so that I do not have to re-hide the same rows every session.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Row_Visibility_State SHALL be stored in browser localStorage under a dedicated key (e.g., `steam_findings_hidden_rows`).
|
||||
2. WHEN the Reporting page loads, THE Reporting_Table SHALL read the Row_Visibility_State from localStorage and exclude hidden Finding_IDs from the visible table.
|
||||
3. WHEN the Row_Visibility_State changes (row hidden or restored), THE Reporting_Table SHALL write the updated state to localStorage immediately.
|
||||
4. IF localStorage is unavailable or the stored value is corrupted, THEN THE Reporting_Table SHALL treat all rows as visible and continue operating without error.
|
||||
|
||||
### Requirement 3: Row Visibility Manager Panel
|
||||
|
||||
**User Story:** As a security analyst, I want a panel that shows me which rows are currently hidden and lets me restore them, so that I can manage my hidden rows and bring back findings I no longer want to hide.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Row_Visibility_Manager SHALL be accessible via a toolbar button placed adjacent to the existing ColumnManager button, using the `EyeOff` icon and displaying a count of currently hidden rows (e.g., "Hidden (3)").
|
||||
2. WHEN the Row_Visibility_Manager button is clicked, THE Row_Visibility_Manager SHALL open a popover panel listing all currently hidden findings by Finding_ID and title.
|
||||
3. THE Row_Visibility_Manager panel SHALL provide a restore button (using the `Eye` icon) next to each hidden finding entry that, when clicked, removes that Finding_ID from the Row_Visibility_State and returns the row to the visible table.
|
||||
4. THE Row_Visibility_Manager panel SHALL provide a "Restore All" button that clears the entire Row_Visibility_State and returns all hidden rows to the visible table.
|
||||
5. WHEN no rows are hidden, THE Row_Visibility_Manager button SHALL display "Hidden (0)" and the popover panel SHALL display a message indicating no rows are hidden.
|
||||
|
||||
### Requirement 4: Exclude Hidden Rows from Action Coverage Metrics
|
||||
|
||||
**User Story:** As a security analyst, I want hidden rows to be excluded from the Action Coverage donut chart, so that manually-handled findings I have hidden do not inflate the "Pending" count.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Action_Coverage_Chart SHALL compute its FP Request, Archer Exception, and Pending counts using only visible (non-hidden) findings.
|
||||
2. WHEN a row is hidden or restored, THE Action_Coverage_Chart SHALL recalculate and re-render immediately to reflect the updated visible finding set.
|
||||
3. THE Action_Coverage_Chart segment click filtering SHALL operate only on visible findings, so clicking a segment filters within the non-hidden set.
|
||||
|
||||
### Requirement 5: Hidden Row Interaction with Existing Filters
|
||||
|
||||
**User Story:** As a security analyst, I want row hiding to work correctly alongside column filters, sort order, and the action coverage chart filter, so that hiding rows does not interfere with other table controls.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Reporting_Table SHALL apply row hiding before column filters, so that hidden rows are excluded from the dataset before any column filter, sort, or action coverage filter is applied.
|
||||
2. WHEN a finding is hidden and a column filter is active, THE Reporting_Table SHALL not include the hidden finding in filter value dropdowns or filter counts.
|
||||
3. WHEN findings are synced from Ivanti (Sync button), THE Row_Visibility_State SHALL be preserved — previously hidden Finding_IDs remain hidden if they still exist in the refreshed dataset.
|
||||
4. IF a hidden Finding_ID no longer exists in the synced findings data, THEN THE Row_Visibility_State SHALL retain the ID silently (no error) so that it is automatically re-hidden if the finding reappears in a future sync.
|
||||
|
||||
### Requirement 6: Export Behavior for Hidden Rows
|
||||
|
||||
**User Story:** As a security analyst, I want CSV and XLSX exports to include only visible rows by default, so that my exports reflect the same filtered view I see on screen.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the user exports data via CSV or XLSX, THE Reporting_Table SHALL export only the currently visible (non-hidden, post-filter) rows.
|
||||
2. THE export SHALL respect all active filters (column filters, action coverage filter, EXC filter) in addition to row hiding, exporting only the intersection of all active view constraints.
|
||||
|
||||
### Requirement 7: Visual Styling Consistency
|
||||
|
||||
**User Story:** As a security analyst, I want the row-hiding controls to match the existing dashboard aesthetic, so that the feature feels native to the application.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE hide button on each row SHALL use the same icon size (13px), color palette (muted slate for default, accent blue on hover), and monospace font styling as existing toolbar controls.
|
||||
2. THE Row_Visibility_Manager popover SHALL use the same panel styling (dark gradient background, accent border, box shadow) as the existing ColumnManager popover.
|
||||
3. THE Row_Visibility_Manager toolbar button SHALL use the same button styling (padding, border radius, font size, uppercase text) as the existing ColumnManager and Queue toolbar buttons.
|
||||
|
||||
### Requirement 8: Bulk Hide Rows via Multi-Select
|
||||
|
||||
**User Story:** As a security analyst, I want to select multiple rows and hide them all at once, so that I can quickly clear out batches of manually-handled findings without clicking hide on each row individually.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Reporting_Table SHALL display a Selection_Checkbox on each visible row in a fixed column that is not managed by the ColumnManager, positioned before the hide button column.
|
||||
2. THE Reporting_Table SHALL display a Select_All_Checkbox in the table header of the selection column that, when checked, adds all currently visible (non-hidden, post-filter) Finding_IDs to the Row_Selection_State.
|
||||
3. WHEN the Select_All_Checkbox is unchecked, THE Reporting_Table SHALL remove all Finding_IDs from the Row_Selection_State.
|
||||
4. WHEN one or more Finding_IDs are present in the Row_Selection_State, THE Bulk_Action_Toolbar SHALL appear above the Reporting_Table displaying the count of selected rows (e.g., "3 rows selected") and a "Hide Selected" button using the `EyeOff` icon.
|
||||
5. WHEN the "Hide Selected" button is clicked, THE Reporting_Table SHALL add all Finding_IDs in the Row_Selection_State to the Row_Visibility_State hidden set in a single operation.
|
||||
6. WHEN a bulk hide operation completes, THE Reporting_Table SHALL clear the Row_Selection_State so that no rows remain selected.
|
||||
7. WHEN a bulk hide operation completes, THE Action_Coverage_Chart SHALL recalculate and re-render immediately to reflect the updated visible finding set.
|
||||
8. WHEN column filters or the action coverage filter change the set of visible rows, THE Row_Selection_State SHALL remove any Finding_IDs that are no longer visible, so that the selection always reflects the current filtered view.
|
||||
9. THE Select_All_Checkbox SHALL display an indeterminate state when some but not all visible rows are selected.
|
||||
10. WHEN no rows are selected, THE Bulk_Action_Toolbar SHALL not be displayed.
|
||||
11. THE Selection_Checkbox, Select_All_Checkbox, and Bulk_Action_Toolbar SHALL use the same color palette (muted slate for default, accent blue for checked/active state), monospace font styling, and dark gradient background as existing toolbar controls defined in the design system.
|
||||
127
.kiro/specs/reporting-row-visibility/tasks.md
Normal file
127
.kiro/specs/reporting-row-visibility/tasks.md
Normal file
@@ -0,0 +1,127 @@
|
||||
# Implementation Plan: Reporting Row Visibility
|
||||
|
||||
## Overview
|
||||
|
||||
This plan implements row-level visibility controls for the Reporting page's findings table. All changes are contained within `frontend/src/components/pages/ReportingPage.js` — no new files, no backend changes. The implementation adds hidden row state management (localStorage-persisted), a visibility filtering step in the data pipeline, selection checkboxes with bulk hide, a Row Visibility Manager popover, chart/export integration, and per-row hide buttons. Each task builds incrementally on the previous one, wiring everything together by the final step.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Add hidden row state management and localStorage helpers
|
||||
- Add the `HIDDEN_ROWS_KEY` constant (`'steam_findings_hidden_rows'`)
|
||||
- Implement `loadHiddenRows()` function that reads from localStorage, parses JSON, returns a `Set<string>` (empty set on parse failure or missing key)
|
||||
- Implement `saveHiddenRows(hiddenSet)` function that serializes the set to a JSON array and writes to localStorage (silent catch on failure)
|
||||
- Add `hiddenRowIds` state initialized via `useState(loadHiddenRows)`
|
||||
- Implement `hideRow(findingId)` callback that adds a string ID to the set and persists
|
||||
- Implement `restoreRow(findingId)` callback that removes a string ID from the set and persists
|
||||
- Implement `restoreAllRows()` callback that clears the set and persists an empty set
|
||||
- _Requirements: 1.1, 2.1, 2.2, 2.3, 2.4_
|
||||
|
||||
- [ ]* 1.1 Write property test: localStorage round-trip preserves hidden row state
|
||||
- **Property 2: localStorage round-trip preserves hidden row state**
|
||||
- Generate arbitrary sets of valid Finding_ID strings, call `saveHiddenRows` then `loadHiddenRows`, assert the returned set contains exactly the same elements
|
||||
- **Validates: Requirements 2.1, 2.2**
|
||||
|
||||
- [ ]* 1.2 Write property test: corrupted localStorage produces empty set
|
||||
- **Property 3: Corrupted localStorage produces empty set**
|
||||
- Generate arbitrary strings that are not valid JSON arrays of strings, set them in localStorage under the hidden rows key, call `loadHiddenRows`, assert the result is an empty set and no error is thrown
|
||||
- **Validates: Requirements 2.4**
|
||||
|
||||
- [x] 2. Insert visibility filtering into the data pipeline
|
||||
- Add `visibleFindings` useMemo that filters `findings` by excluding any finding whose `String(f.id)` is in `hiddenRowIds` (short-circuit when set is empty)
|
||||
- Modify the existing `filtered` useMemo to start from `visibleFindings` instead of `findings`
|
||||
- Ensure column filter dropdowns, action filter, and EXC filter all operate on the post-hide dataset
|
||||
- _Requirements: 1.2, 5.1, 5.2_
|
||||
|
||||
- [ ]* 2.1 Write property test: hidden row filtering invariant
|
||||
- **Property 1: Hidden row filtering invariant**
|
||||
- Generate arbitrary arrays of finding objects and arbitrary sets of hidden Finding_IDs, compute `visibleFindings`, assert no finding in the output has an ID present in the hidden set
|
||||
- **Validates: Requirements 1.1, 1.2, 4.1, 4.3, 5.1, 5.2, 6.1, 6.2**
|
||||
|
||||
- [x] 3. Integrate hidden rows with chart and export
|
||||
- Pass `visibleFindings` (instead of `findings`) to the `ActionCoverageDonut` component's `findings` prop
|
||||
- Modify the CSV export function to use the sorted/filtered visible rows (already derived from `visibleFindings` via the pipeline)
|
||||
- Modify the XLSX export function to use the sorted/filtered visible rows
|
||||
- Verify that chart segment click filtering operates on the visible set
|
||||
- _Requirements: 4.1, 4.2, 4.3, 6.1, 6.2_
|
||||
|
||||
- [x] 4. Checkpoint — Verify core hide/restore pipeline
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 5. Add selection state and bulk hide logic
|
||||
- Add `selectedRowIds` state as `useState(new Set())`
|
||||
- Implement `toggleRowSelection(findingId)` callback that adds/removes a string ID from the selection set
|
||||
- Implement `toggleSelectAll()` callback that selects all visible sorted row IDs when not all are selected, or clears selection when all are selected
|
||||
- Implement `hideSelectedRows()` callback that unions `selectedRowIds` into `hiddenRowIds`, persists, and clears the selection set
|
||||
- Add a `useEffect` that prunes `selectedRowIds` to only include IDs present in the current `sorted` array whenever `sorted` changes
|
||||
- _Requirements: 8.1, 8.2, 8.3, 8.5, 8.6, 8.8_
|
||||
|
||||
- [ ]* 5.1 Write property test: bulk hide produces union of hidden and selected sets
|
||||
- **Property 5: Bulk hide produces the union of hidden and selected sets**
|
||||
- Generate two arbitrary sets of Finding_ID strings (hidden and selected), simulate `hideSelectedRows`, assert the resulting hidden set equals the union and the selection set is empty
|
||||
- **Validates: Requirements 8.5, 8.6**
|
||||
|
||||
- [ ]* 5.2 Write property test: selection is always a subset of visible rows
|
||||
- **Property 6: Selection is always a subset of visible rows**
|
||||
- Generate arbitrary selection and visible row sets, simulate the pruning effect, assert the resulting selection is a subset of visible row IDs
|
||||
- **Validates: Requirements 8.8**
|
||||
|
||||
- [ ]* 5.3 Write property test: select all produces exactly the visible row ID set
|
||||
- **Property 7: Select all produces exactly the visible row ID set**
|
||||
- Generate an arbitrary array of finding objects representing sorted visible rows, simulate `toggleSelectAll` from empty selection, assert the selection equals the full visible ID set; toggle again, assert empty
|
||||
- **Validates: Requirements 8.2, 8.3**
|
||||
|
||||
- [ ]* 5.4 Write property test: restore removes exactly the specified ID
|
||||
- **Property 4: Restore removes exactly the specified ID**
|
||||
- Generate a non-empty set of hidden Finding_IDs, pick a random element, simulate `restoreRow`, assert the result equals the original set minus that single ID
|
||||
- **Validates: Requirements 3.3**
|
||||
|
||||
- [x] 6. Add selection checkbox column and select-all checkbox to the table
|
||||
- Import `Square`, `CheckSquare`, and `MinusSquare` icons from lucide-react
|
||||
- Add a fixed 36px selection checkbox column as the first column in the table header and body
|
||||
- Render `Select_All_Checkbox` in the header: `CheckSquare` when all selected, `MinusSquare` when partially selected, `Square` when none selected; onClick calls `toggleSelectAll`
|
||||
- Render `Selection_Checkbox` on each row: `CheckSquare` when selected, `Square` when not; onClick calls `toggleRowSelection(finding.id)`
|
||||
- Style checkboxes with muted slate default color, accent blue when checked/active, matching existing icon sizing
|
||||
- _Requirements: 8.1, 8.2, 8.3, 8.9, 8.11_
|
||||
|
||||
- [x] 7. Add per-row hide button column
|
||||
- Add a fixed 36px hide button column as the second column (after selection checkbox) in the table header and body
|
||||
- Render an `EyeOff` icon button on each row; onClick calls `hideRow(finding.id)`
|
||||
- Style the button with 13px icon size, muted slate default color, accent blue on hover, matching existing toolbar icon patterns
|
||||
- The column header cell is empty (no label)
|
||||
- _Requirements: 1.1, 1.3, 1.4, 7.1_
|
||||
|
||||
- [x] 8. Implement BulkHideToolbar component
|
||||
- Create inline `BulkHideToolbar` component accepting `count`, `onHide`, and `onClear` props
|
||||
- Render "{count} rows selected" label, "Hide Selected" button with `EyeOff` icon, and "Clear" button
|
||||
- Style with dark gradient background, accent border, monospace font, matching existing toolbar patterns
|
||||
- Render the toolbar above the table inside the scroll container, only when `selectedRowIds.size > 0`
|
||||
- Wire `onHide` to `hideSelectedRows` and `onClear` to clearing the selection set
|
||||
- _Requirements: 8.4, 8.5, 8.6, 8.7, 8.10, 8.11_
|
||||
|
||||
- [x] 9. Checkpoint — Verify selection and bulk hide UI
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 10. Implement RowVisibilityManager popover component
|
||||
- Create inline `RowVisibilityManager` component accepting `hiddenRowIds`, `findings`, `onRestore`, and `onRestoreAll` props
|
||||
- Add `open` state for popover visibility, with outside-click-to-close behavior (same pattern as existing `ColumnManager`)
|
||||
- Render a toolbar button with `EyeOff` icon and "Hidden (N)" count text, styled to match the existing ColumnManager and Queue toolbar buttons (same padding, border radius, font size, uppercase text)
|
||||
- When open, render a popover panel listing hidden findings by Finding_ID and title (looked up from the full `findings` array)
|
||||
- Each entry has an `Eye` icon restore button that calls `onRestore(findingId)`
|
||||
- Include a "Restore All" button at the bottom that calls `onRestoreAll`
|
||||
- When `hiddenRowIds.size === 0`, show "No rows hidden" message in the popover
|
||||
- Use dark gradient background, accent border, and box shadow matching the ColumnManager popover
|
||||
- Place the button in the toolbar div adjacent to the ColumnManager button
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.4, 3.5, 7.2, 7.3_
|
||||
|
||||
- [x] 11. Final checkpoint — Verify complete feature integration
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- All changes are contained within `frontend/src/components/pages/ReportingPage.js` — no new files needed
|
||||
- The design uses JavaScript throughout; fast-check is the PBT library
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests validate the 7 correctness properties defined in the design document
|
||||
- Unit tests validate specific UI rendering scenarios and edge cases
|
||||
1
.kiro/specs/sync-anomaly-detection/.config.kiro
Normal file
1
.kiro/specs/sync-anomaly-detection/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "a3e7c1d2-8f4b-4e9a-b6d1-2c5f8a9e3b7d", "workflowType": "requirements-first", "specType": "feature"}
|
||||
454
.kiro/specs/sync-anomaly-detection/design.md
Normal file
454
.kiro/specs/sync-anomaly-detection/design.md
Normal file
@@ -0,0 +1,454 @@
|
||||
# Design Document: Sync Anomaly Detection and BU Drift Monitoring
|
||||
|
||||
## Overview
|
||||
|
||||
This feature extends the Ivanti sync pipeline to automatically classify why findings disappear from filtered sync results. The current archive system detects disappearances but labels them all as `severity_score_drift` — a default that proved incorrect during the April 2026 incident where 109 findings silently disappeared due to a bulk BU reassignment.
|
||||
|
||||
The design adds three capabilities to the existing `ivantiFindings.js` sync pipeline:
|
||||
|
||||
1. **BU Drift Checker** — a post-sync step that queries the Ivanti API without BU/severity filters for newly archived finding IDs, classifying each disappearance as `bu_reassignment`, `severity_drift`, `closed_on_platform`, or `decommissioned`.
|
||||
2. **Sync Anomaly Summary** — a structured report computed after each sync that breaks down count changes by cause and stores the result in a new `ivanti_sync_anomaly_log` table.
|
||||
3. **Finding-Level BU Tracking** — per-finding BU comparison during `syncFindings()` that detects BU changes across syncs and records them in a new `ivanti_finding_bu_history` table.
|
||||
|
||||
The approach formalizes the ad-hoc diagnostic patterns from `drift-check.js` and `bu-reassignment-check.js` into the automated sync pipeline, with results surfaced through new API endpoints and an anomaly banner on the Vulnerability Triage page.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
The feature integrates into the existing sync pipeline as post-sync steps, keeping the core sync logic unchanged. No new route modules are created — all new endpoints and logic live within the existing `ivantiFindings.js` module and its factory-pattern router.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[syncFindings - fetch all pages] --> B[Compare previous vs current findings]
|
||||
B --> C[detectArchiveChanges - existing]
|
||||
B --> D[BU comparison - new]
|
||||
D --> E[Insert BU changes into ivanti_finding_bu_history]
|
||||
C --> F[syncClosedCount - existing]
|
||||
F --> G[detectClosedFindings - existing]
|
||||
G --> H[detectClosedGoneFindings - existing]
|
||||
H --> I[runBUDriftChecker - new]
|
||||
I --> J[Batch unfiltered queries for newly archived IDs]
|
||||
J --> K[Classify each: bu_reassignment / severity_drift / closed_on_platform / decommissioned]
|
||||
K --> L[Update archive transition reasons]
|
||||
L --> M[computeAnomalySummary - new]
|
||||
M --> N[Insert row into ivanti_sync_anomaly_log]
|
||||
|
||||
style I fill:#F59E0B,color:#000
|
||||
style D fill:#F59E0B,color:#000
|
||||
style M fill:#F59E0B,color:#000
|
||||
```
|
||||
|
||||
**Key design decisions:**
|
||||
|
||||
- **Post-sync, not inline**: The BU drift checker runs after all existing sync steps complete. This means a sync failure does not block drift checking of previously archived findings, and drift checking failures do not block the sync.
|
||||
- **Same module, no new route file**: The anomaly and BU history endpoints are added to the existing `createIvantiFindingsRouter`. This keeps the Ivanti findings API surface in one place and avoids a new factory-pattern module for four endpoints.
|
||||
- **Batched unfiltered queries**: Finding IDs are chunked into groups of 50 for the unfiltered Ivanti API call, matching the pattern proven in `bu-reassignment-check.js`. This stays within API limits while keeping the number of HTTP calls manageable.
|
||||
- **BU comparison in syncFindings**: The per-finding BU comparison happens during the existing previous-vs-current comparison in `syncFindings()`, before the cache is overwritten. This is the only point where both the old and new BU values are available in memory.
|
||||
|
||||
---
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### 1. BU Drift Checker (`runBUDriftChecker`)
|
||||
|
||||
A new async function added to `ivantiFindings.js` that runs after `detectClosedGoneFindings()` in the sync pipeline.
|
||||
|
||||
**Signature:**
|
||||
```javascript
|
||||
async function runBUDriftChecker(db, newlyArchivedIds, apiKey, clientId, skipTls)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `db` — SQLite database instance
|
||||
- `newlyArchivedIds` — array of finding ID strings that were newly archived in this sync cycle (from `detectArchiveChanges`)
|
||||
- `apiKey`, `clientId`, `skipTls` — Ivanti API credentials (same as existing sync functions)
|
||||
|
||||
**Behavior:**
|
||||
1. If `newlyArchivedIds` is empty, return immediately (no API calls).
|
||||
2. Chunk the IDs into batches of 50.
|
||||
3. For each batch, call `ivantiPost()` with a filter on `id` field only (no BU, severity, or state filters) — the same unfiltered query pattern used in `bu-reassignment-check.js`.
|
||||
4. For each finding ID, classify the result:
|
||||
- **Found, BU differs from expected** → `bu_reassignment`
|
||||
- **Found, BU matches, severity < 8.5** → `severity_drift`
|
||||
- **Found, BU matches, state is Closed** → `closed_on_platform`
|
||||
- **Not found** → `decommissioned`
|
||||
5. Update the corresponding `ivanti_archive_transitions` row's `reason` field with the classification.
|
||||
6. Return a classification summary object: `{ bu_reassignment: N, severity_drift: N, closed_on_platform: N, decommissioned: N }`.
|
||||
|
||||
**Expected BUs** are the same values used in `FINDINGS_FILTERS`: `NTS-AEO-ACCESS-ENG` and `NTS-AEO-STEAM`.
|
||||
|
||||
**Error handling:** If an individual batch API call fails, log the error and skip that batch. The findings in the failed batch retain their default `severity_score_drift` reason. The function never throws — it returns whatever partial results it collected.
|
||||
|
||||
### 2. Anomaly Summary Computation (`computeAnomalySummary`)
|
||||
|
||||
A new async function that runs after the BU drift checker completes.
|
||||
|
||||
**Signature:**
|
||||
```javascript
|
||||
async function computeAnomalySummary(db, openCountDelta, closedCountDelta, newlyArchivedCount, returnedCount, classificationBreakdown)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `db` — SQLite database instance
|
||||
- `openCountDelta` — integer, current open count minus previous open count
|
||||
- `closedCountDelta` — integer, current closed count minus previous closed count
|
||||
- `newlyArchivedCount` — integer, number of findings archived in this sync
|
||||
- `returnedCount` — integer, number of findings that returned in this sync
|
||||
- `classificationBreakdown` — object from `runBUDriftChecker`, e.g. `{ bu_reassignment: 38, severity_drift: 5, ... }`
|
||||
|
||||
**Behavior:**
|
||||
1. Determine `is_significant`: true if `newlyArchivedCount > 5`.
|
||||
2. Insert a row into `ivanti_sync_anomaly_log` with all fields.
|
||||
3. Log the summary to console.
|
||||
|
||||
### 3. Finding-Level BU Comparison
|
||||
|
||||
Integrated into `syncFindings()` between reading previous findings and writing the new cache. Uses the existing `previousFindings` and `allFindings` arrays.
|
||||
|
||||
**Logic:**
|
||||
```
|
||||
for each finding in allFindings:
|
||||
previousFinding = previousMap.get(finding.id)
|
||||
if previousFinding exists AND previousFinding.buOwnership !== finding.buOwnership
|
||||
AND both values are non-empty:
|
||||
INSERT into ivanti_finding_bu_history
|
||||
```
|
||||
|
||||
The `buOwnership` field is already extracted by `extractFinding()` from `assetCustomAttributes['1550_host_1']`. No changes to `extractFinding()` are needed — it already stores `buOwnership` on each finding object.
|
||||
|
||||
### 4. New API Endpoints
|
||||
|
||||
All endpoints are added to the existing `createIvantiFindingsRouter` and require authentication via `requireAuth(db)`.
|
||||
|
||||
| Method | Path | Description |
|
||||
|---|---|---|
|
||||
| GET | `/api/ivanti/findings/anomaly/latest` | Returns the most recent anomaly summary row |
|
||||
| GET | `/api/ivanti/findings/anomaly/history` | Returns anomaly history (last 30 or date-filtered) |
|
||||
| GET | `/api/ivanti/findings/bu-changes` | Returns all BU change events, newest first |
|
||||
| GET | `/api/ivanti/findings/:findingId/bu-history` | Returns BU change history for a specific finding |
|
||||
|
||||
**GET /anomaly/latest response:**
|
||||
```json
|
||||
{
|
||||
"anomaly": {
|
||||
"id": 1,
|
||||
"sync_timestamp": "2026-04-24T12:00:00",
|
||||
"open_count_delta": -45,
|
||||
"closed_count_delta": -94,
|
||||
"newly_archived_count": 45,
|
||||
"returned_count": 0,
|
||||
"classification": {
|
||||
"bu_reassignment": 38,
|
||||
"severity_drift": 1,
|
||||
"closed_on_platform": 4,
|
||||
"decommissioned": 2
|
||||
},
|
||||
"is_significant": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Returns `{ anomaly: null }` if no anomaly records exist.
|
||||
|
||||
**GET /anomaly/history query parameters:**
|
||||
- `from` (optional) — ISO date string, inclusive start
|
||||
- `to` (optional) — ISO date string, inclusive end
|
||||
- If neither provided, returns last 30 rows
|
||||
|
||||
**GET /bu-changes response:**
|
||||
```json
|
||||
{
|
||||
"changes": [
|
||||
{
|
||||
"id": 1,
|
||||
"finding_id": "2687687777",
|
||||
"finding_title": "OpenSSH regreSSHion",
|
||||
"host_name": "syn-098-120-000-078",
|
||||
"previous_bu": "NTS-AEO-STEAM",
|
||||
"new_bu": "SDIT-CSD-ITLS-PIES",
|
||||
"detected_at": "2026-04-24T12:00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**GET /:findingId/bu-history response:**
|
||||
```json
|
||||
{
|
||||
"finding_id": "2687687777",
|
||||
"history": [
|
||||
{
|
||||
"previous_bu": "NTS-AEO-STEAM",
|
||||
"new_bu": "SDIT-CSD-ITLS-PIES",
|
||||
"detected_at": "2026-04-24T12:00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Anomaly Banner Component (`AnomalyBanner.js`)
|
||||
|
||||
A new React component placed in `frontend/src/components/pages/AnomalyBanner.js`, rendered on the Vulnerability Triage page above the `IvantiCountsChart`.
|
||||
|
||||
**Props:** None — fetches its own data from `/api/ivanti/findings/anomaly/latest`.
|
||||
|
||||
**Behavior:**
|
||||
1. On mount, fetch the latest anomaly summary.
|
||||
2. If `is_significant` is false or no anomaly exists, render nothing.
|
||||
3. If `is_significant` is true, render a warning banner with:
|
||||
- Amber background tint (`rgba(245, 158, 11, 0.15)`) with amber border (`rgba(245, 158, 11, 0.3)`)
|
||||
- `AlertTriangle` icon from lucide-react
|
||||
- Summary text: "45 findings archived — 38 BU reassignment, 5 severity drift, 2 decommissioned"
|
||||
- Expandable detail section (click to toggle) showing affected findings grouped by classification
|
||||
- Dismiss button (X icon) that hides the banner for the current session via `useState`
|
||||
4. Uses monospace typography and dark theme colors per `DESIGN_SYSTEM.md`.
|
||||
|
||||
**Session dismiss:** Uses React state only — no localStorage. The banner reappears on page reload, which is appropriate since the anomaly data persists until the next sync produces a non-significant result.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> Loading: Component mounts
|
||||
Loading --> Hidden: No anomaly or not significant
|
||||
Loading --> Visible: Significant anomaly
|
||||
Visible --> Expanded: Click breakdown text
|
||||
Expanded --> Visible: Click breakdown text
|
||||
Visible --> Dismissed: Click dismiss
|
||||
Expanded --> Dismissed: Click dismiss
|
||||
Dismissed --> [*]
|
||||
```
|
||||
|
||||
### 6. Migration Script
|
||||
|
||||
Located at `backend/migrations/add_sync_anomaly_tables.js`. Uses the same pattern as existing migrations (`add_closed_gone_state.js`): standalone Node script, opens the database directly, uses `CREATE TABLE IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS` for idempotency.
|
||||
|
||||
---
|
||||
|
||||
## Data Models
|
||||
|
||||
### New Table: `ivanti_sync_anomaly_log`
|
||||
|
||||
Stores one row per sync cycle with the anomaly summary.
|
||||
|
||||
| Column | Type | Constraints | Description |
|
||||
|---|---|---|---|
|
||||
| `id` | INTEGER | PRIMARY KEY AUTOINCREMENT | Unique row identifier |
|
||||
| `sync_timestamp` | DATETIME | NOT NULL DEFAULT CURRENT_TIMESTAMP | When the sync completed |
|
||||
| `open_count_delta` | INTEGER | NOT NULL DEFAULT 0 | Current open count minus previous open count |
|
||||
| `closed_count_delta` | INTEGER | NOT NULL DEFAULT 0 | Current closed count minus previous closed count |
|
||||
| `newly_archived_count` | INTEGER | NOT NULL DEFAULT 0 | Number of findings archived in this sync |
|
||||
| `returned_count` | INTEGER | NOT NULL DEFAULT 0 | Number of findings that returned in this sync |
|
||||
| `classification_json` | TEXT | NOT NULL DEFAULT '{}' | JSON object: `{ bu_reassignment, severity_drift, closed_on_platform, decommissioned }` |
|
||||
| `is_significant` | INTEGER | NOT NULL DEFAULT 0 | 1 if `newly_archived_count > 5`, else 0 |
|
||||
| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Row creation timestamp |
|
||||
|
||||
**Indexes:**
|
||||
- `idx_anomaly_sync_timestamp` on `sync_timestamp` — for efficient latest-record and date-range queries
|
||||
|
||||
### New Table: `ivanti_finding_bu_history`
|
||||
|
||||
Stores BU change events detected during sync.
|
||||
|
||||
| Column | Type | Constraints | Description |
|
||||
|---|---|---|---|
|
||||
| `id` | INTEGER | PRIMARY KEY AUTOINCREMENT | Unique row identifier |
|
||||
| `finding_id` | TEXT | NOT NULL | Ivanti finding identifier |
|
||||
| `finding_title` | TEXT | NOT NULL DEFAULT '' | Finding title at time of detection |
|
||||
| `host_name` | TEXT | NOT NULL DEFAULT '' | Host name at time of detection |
|
||||
| `previous_bu` | TEXT | NOT NULL | BU value from previous sync |
|
||||
| `new_bu` | TEXT | NOT NULL | BU value from current sync |
|
||||
| `detected_at` | DATETIME | NOT NULL DEFAULT CURRENT_TIMESTAMP | When the change was detected |
|
||||
| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Row creation timestamp |
|
||||
|
||||
**Indexes:**
|
||||
- `idx_bu_history_finding_id` on `finding_id` — for per-finding history lookups
|
||||
- `idx_bu_history_detected_at` on `detected_at` — for chronological queries
|
||||
|
||||
### Modified: `ivanti_archive_transitions.reason` field
|
||||
|
||||
No schema change needed — the `reason` column is already `TEXT NOT NULL DEFAULT ''`. The change is in the values written:
|
||||
|
||||
| Previous values | New values |
|
||||
|---|---|
|
||||
| `severity_score_drift` | `bu_reassignment:<new_bu>` |
|
||||
| `reappeared_in_sync` | `severity_drift:<new_severity>` |
|
||||
| `remediated_in_ivanti` | `closed_on_platform` |
|
||||
| `disappeared_from_closed_set` | `decommissioned` |
|
||||
|
||||
Existing rows with `severity_score_drift` are not modified — the enhanced reasons apply only to transitions created after deployment.
|
||||
|
||||
### Existing: `ivanti_findings_cache.findings_json`
|
||||
|
||||
No schema change. The `buOwnership` field is already present in each finding object within the JSON array, extracted by `extractFinding()` from `assetCustomAttributes['1550_host_1']`.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 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: Classification correctness
|
||||
|
||||
*For any* finding returned by an unfiltered Ivanti API query, the BU drift classifier SHALL produce the correct classification based on the combination of BU value, severity, and state:
|
||||
- BU not in {NTS-AEO-ACCESS-ENG, NTS-AEO-STEAM} → `bu_reassignment`
|
||||
- BU matches expected, severity < 8.5 → `severity_drift`
|
||||
- BU matches expected, severity >= 8.5, state is Closed → `closed_on_platform`
|
||||
- Finding not returned by API → `decommissioned`
|
||||
|
||||
**Validates: Requirements 1.2, 1.3, 1.4, 1.5**
|
||||
|
||||
### Property 2: Archive transition reason formatting
|
||||
|
||||
*For any* classification result, the archive transition reason field SHALL be formatted correctly:
|
||||
- `bu_reassignment` classification with BU value B → reason is `bu_reassignment:B`
|
||||
- `severity_drift` classification with severity S → reason is `severity_drift:S`
|
||||
- `closed_on_platform` → reason is `closed_on_platform`
|
||||
- `decommissioned` → reason is `decommissioned`
|
||||
|
||||
**Validates: Requirements 6.1, 6.2, 6.3, 6.4**
|
||||
|
||||
### Property 3: Batch size constraint
|
||||
|
||||
*For any* list of finding IDs of length N, the BU drift checker SHALL partition them into ceil(N/50) batches where each batch contains at most 50 IDs and the union of all batches equals the original list.
|
||||
|
||||
**Validates: Requirements 1.7**
|
||||
|
||||
### Property 4: Significance threshold
|
||||
|
||||
*For any* non-negative integer `newly_archived_count`, the anomaly summary's `is_significant` flag SHALL be true if and only if `newly_archived_count > 5`.
|
||||
|
||||
**Validates: Requirements 2.7**
|
||||
|
||||
### Property 5: Count delta computation
|
||||
|
||||
*For any* pair of non-negative integers (previous_count, current_count), the anomaly summary SHALL compute the delta as `current_count - previous_count` for both open and closed counts.
|
||||
|
||||
**Validates: Requirements 2.1**
|
||||
|
||||
### Property 6: BU extraction preservation
|
||||
|
||||
*For any* raw Ivanti finding object with a non-empty `assetCustomAttributes['1550_host_1']` array, `extractFinding` SHALL produce a finding object whose `buOwnership` field equals the first element of that array.
|
||||
|
||||
**Validates: Requirements 3.1**
|
||||
|
||||
### Property 7: BU change detection and recording
|
||||
|
||||
*For any* finding that appears in both the previous and current sync results with different non-empty `buOwnership` values, the sync pipeline SHALL insert exactly one row into `ivanti_finding_bu_history` with the correct `finding_id`, `previous_bu`, and `new_bu`. *For any* finding that appears for the first time (no previous entry) or has the same BU value, no history row SHALL be inserted.
|
||||
|
||||
**Validates: Requirements 3.2, 3.3, 3.6**
|
||||
|
||||
### Property 8: Latest anomaly returns most recent
|
||||
|
||||
*For any* non-empty sequence of anomaly summary rows with distinct timestamps, the `/anomaly/latest` endpoint SHALL return the row with the maximum `sync_timestamp`.
|
||||
|
||||
**Validates: Requirements 2.5**
|
||||
|
||||
### Property 9: Anomaly history ordering and limit
|
||||
|
||||
*For any* set of N anomaly summary rows, the `/anomaly/history` endpoint (without date parameters) SHALL return min(N, 30) rows ordered by `sync_timestamp` descending.
|
||||
|
||||
**Validates: Requirements 2.6, 7.2**
|
||||
|
||||
### Property 10: Date-range filtering with complete response shape
|
||||
|
||||
*For any* date range [from, to] and set of anomaly summary rows, the `/anomaly/history` endpoint SHALL return only rows whose `sync_timestamp` falls within the range (inclusive), ordered by `sync_timestamp` descending. Each returned row SHALL include `sync_timestamp`, `open_count_delta`, `closed_count_delta`, `newly_archived_count`, `returned_count`, `classification` (parsed as an object from `classification_json`), and `is_significant`.
|
||||
|
||||
**Validates: Requirements 7.1, 7.4**
|
||||
|
||||
### Property 11: BU changes endpoint ordering
|
||||
|
||||
*For any* set of BU change history rows, the `/bu-changes` endpoint SHALL return all rows ordered by `detected_at` descending.
|
||||
|
||||
**Validates: Requirements 3.4**
|
||||
|
||||
### Property 12: Per-finding BU history filtering
|
||||
|
||||
*For any* finding ID F and set of BU history rows across multiple findings, the `/:findingId/bu-history` endpoint SHALL return only rows where `finding_id = F`, ordered by `detected_at` descending.
|
||||
|
||||
**Validates: Requirements 3.5**
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
### BU Drift Checker Errors
|
||||
|
||||
- **Individual batch API failure**: Log the error with the batch range, skip the batch, continue with remaining batches. Findings in the failed batch retain the default `severity_score_drift` reason. The function returns partial results.
|
||||
- **All batches fail**: The classification breakdown will be all zeros. The anomaly summary is still written with `newly_archived_count` reflecting the archive detection results (which don't depend on the drift checker).
|
||||
- **API timeout**: The existing 15-second timeout in `ivantiPost()` applies. Timed-out batches are treated as failed batches.
|
||||
- **Malformed API response**: If `JSON.parse` fails on the response body, treat the batch as failed. Log the raw response length for debugging.
|
||||
|
||||
### Anomaly Summary Errors
|
||||
|
||||
- **Database write failure**: Log the error. The sync itself has already completed successfully — the anomaly summary is informational. Do not retry.
|
||||
- **Missing previous counts**: If no previous anomaly row exists (first sync after deployment), use 0 for previous counts. The first anomaly row will have deltas equal to the current counts.
|
||||
|
||||
### BU Comparison Errors
|
||||
|
||||
- **Database insert failure**: Log the error for the specific finding, continue processing remaining findings. BU comparison failures are non-fatal.
|
||||
- **Missing buOwnership field**: If either the previous or current finding has an empty/undefined `buOwnership`, skip the comparison for that finding (per requirement 3.6).
|
||||
|
||||
### API Endpoint Errors
|
||||
|
||||
- **Database read failure**: Return 500 with a generic error message. Do not expose internal error details.
|
||||
- **Invalid date parameters**: If `from` or `to` are not valid ISO date strings, ignore them and fall back to the default last-30 behavior. Log a warning.
|
||||
- **Authentication failure**: Handled by existing `requireAuth(db)` middleware — returns 401.
|
||||
|
||||
### Migration Errors
|
||||
|
||||
- **Table already exists**: `CREATE TABLE IF NOT EXISTS` handles this silently.
|
||||
- **Index already exists**: `CREATE INDEX IF NOT EXISTS` handles this silently.
|
||||
- **Database locked**: The migration script opens its own connection. If the server is running, SQLite's WAL mode allows concurrent reads. If a write lock conflict occurs, the migration will fail with a clear error message and can be retried.
|
||||
|
||||
---
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
Property-based testing is appropriate for this feature because the core logic involves classification functions, data transformations, and query behaviors that have clear input/output relationships and universal properties.
|
||||
|
||||
**Library:** [fast-check](https://github.com/dubzzz/fast-check) — the standard PBT library for JavaScript/Node.js.
|
||||
|
||||
**Configuration:**
|
||||
- Minimum 100 iterations per property test
|
||||
- Each test tagged with: `Feature: sync-anomaly-detection, Property {N}: {title}`
|
||||
|
||||
**Properties to implement:**
|
||||
|
||||
| Property | Test approach |
|
||||
|---|---|
|
||||
| 1: Classification correctness | Generate random {bu, severity, state, found} tuples, verify classifier output |
|
||||
| 2: Reason formatting | Generate random classification results, verify reason string format |
|
||||
| 3: Batch size constraint | Generate random-length ID arrays, verify chunking |
|
||||
| 4: Significance threshold | Generate random integers, verify is_significant flag |
|
||||
| 5: Delta computation | Generate random count pairs, verify subtraction |
|
||||
| 6: BU extraction | Generate random raw finding objects, verify buOwnership extraction |
|
||||
| 7: BU change detection | Generate random previous/current finding pairs, verify history insertion |
|
||||
| 8–12: API query properties | Generate random DB state, verify endpoint responses |
|
||||
|
||||
### Unit Tests (Example-Based)
|
||||
|
||||
Unit tests cover specific scenarios, edge cases, and integration points not suited for PBT:
|
||||
|
||||
- **Migration idempotency**: Run migration twice, verify no errors on second run (Req 4.6)
|
||||
- **API error resilience**: Mock `ivantiPost` to return errors, verify drift checker doesn't throw (Req 1.6)
|
||||
- **Anomaly banner rendering**: Mock API response, verify banner shows/hides based on `is_significant` (Req 5.2, 5.3)
|
||||
- **Banner dismiss**: Click dismiss button, verify banner hidden (Req 5.4)
|
||||
- **Banner expand/collapse**: Click breakdown text, verify detail section toggles (Req 5.7)
|
||||
- **Authentication enforcement**: Unauthenticated requests return 401 (Req 7.3)
|
||||
- **Fixed reason strings**: Verify `decommissioned` and `closed_on_platform` are exact strings (Req 6.3, 6.4)
|
||||
- **Backward compatibility**: Existing `severity_score_drift` rows are not modified (Req 6.5)
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- **End-to-end sync with drift checker**: Mock Ivanti API, run full sync pipeline, verify anomaly log and BU history tables are populated correctly
|
||||
- **API endpoint responses**: Seed database, call each endpoint, verify response shape and content
|
||||
|
||||
### Test File Locations
|
||||
|
||||
- `backend/__tests__/bu-drift-classification.property.test.js` — Properties 1–6
|
||||
- `backend/__tests__/anomaly-api.property.test.js` — Properties 7–12
|
||||
- `backend/__tests__/sync-anomaly-detection.test.js` — Unit and integration tests
|
||||
- `frontend/src/components/pages/__tests__/AnomalyBanner.test.js` — UI component tests
|
||||
112
.kiro/specs/sync-anomaly-detection/requirements.md
Normal file
112
.kiro/specs/sync-anomaly-detection/requirements.md
Normal file
@@ -0,0 +1,112 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The Sync Anomaly Detection and BU Drift Monitoring feature extends the Ivanti sync pipeline to automatically classify why findings disappear from sync results. The current archive system detects disappearances but cannot distinguish between BU reassignment, severity score drift, and host decommission. This feature adds three capabilities: post-sync BU drift spot-checks against the unfiltered Ivanti API, a structured sync anomaly summary that breaks down count changes by cause, and per-finding BU tracking that records the business unit on each cached finding and detects BU changes across syncs. Together, these close the visibility gap exposed by the April 2026 incident where 109 findings silently disappeared due to a bulk BU reassignment from NTS-AEO-STEAM to SDIT-CSD-ITLS-PIES.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Sync_Pipeline**: The existing Ivanti/RiskSense host finding sync process in `backend/routes/ivantiFindings.js` that fetches open and closed findings matching BU and severity filters on a daily schedule.
|
||||
- **Finding**: A single host-level vulnerability record identified by a unique `finding_id` from Ivanti/RiskSense, cached in `ivanti_findings_cache`.
|
||||
- **Archive_Detector**: The existing logic within the Sync_Pipeline that compares previous sync results against current results to identify disappeared and returned findings, writing to `ivanti_finding_archives` and `ivanti_archive_transitions`.
|
||||
- **BU_Drift_Checker**: New post-sync logic that queries the Ivanti API without BU filters for a sample of archived findings to determine whether they were reassigned to a different business unit.
|
||||
- **Anomaly_Summary**: A structured report generated after each sync that categorizes finding count changes by cause (BU reassignment, severity drift, closure, decommission) and stores the results for API retrieval and UI display.
|
||||
- **Sync_Anomaly_Log**: A new database table (`ivanti_sync_anomaly_log`) that stores one row per sync cycle containing the anomaly summary breakdown and metadata.
|
||||
- **Finding_BU_History**: A new database table (`ivanti_finding_bu_history`) that records BU changes detected on individual findings across syncs.
|
||||
- **BU_Field**: The `assetCustomAttributes.1550_host_1` attribute on an Ivanti host finding that identifies the owning business unit (e.g., `NTS-AEO-STEAM`, `NTS-AEO-ACCESS-ENG`).
|
||||
- **Anomaly_Banner**: A React UI component displayed on the Vulnerability Triage page that surfaces the most recent sync anomaly summary when significant count changes are detected.
|
||||
- **Unfiltered_Query**: An Ivanti API call that searches by finding ID only, without BU or severity filters, used to determine the current BU and severity of a finding that disappeared from filtered results.
|
||||
- **Spot_Check**: A targeted Unfiltered_Query for a batch of recently archived findings, performed after each sync to classify disappearance causes without querying every archived finding.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: BU Drift Detection on Sync
|
||||
|
||||
**User Story:** As a security analyst, I want the system to automatically check whether archived findings were reassigned to a different BU, so that I can distinguish BU reassignment from score drift or decommission without running manual diagnostic scripts.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Sync_Pipeline completes a successful sync and new findings have been archived, THE BU_Drift_Checker SHALL query the Ivanti API using an Unfiltered_Query for the finding IDs of all newly archived findings from that sync cycle.
|
||||
2. WHEN the Unfiltered_Query returns a finding with a BU_Field value different from `NTS-AEO-ACCESS-ENG` or `NTS-AEO-STEAM`, THE BU_Drift_Checker SHALL classify that finding as `bu_reassignment` and record the new BU value in the archive transition reason.
|
||||
3. WHEN the Unfiltered_Query returns a finding with a severity below 8.5 and the BU_Field still matches `NTS-AEO-ACCESS-ENG` or `NTS-AEO-STEAM`, THE BU_Drift_Checker SHALL classify that finding as `severity_drift` and record the new severity in the archive transition.
|
||||
4. WHEN the Unfiltered_Query does not return a finding at all, THE BU_Drift_Checker SHALL classify that finding as `decommissioned`.
|
||||
5. WHEN the Unfiltered_Query returns a finding with a state of `Closed` and the BU_Field still matches the expected BUs, THE BU_Drift_Checker SHALL classify that finding as `closed_on_platform`.
|
||||
6. IF the Unfiltered_Query fails due to an API error, THEN THE BU_Drift_Checker SHALL log the error and leave the archive transition reason as the existing default (`severity_score_drift`) without blocking the sync completion.
|
||||
7. THE BU_Drift_Checker SHALL batch finding IDs into groups of 50 for the Unfiltered_Query to stay within Ivanti API limits.
|
||||
|
||||
### Requirement 2: Sync Anomaly Summary
|
||||
|
||||
**User Story:** As a security analyst, I want a post-sync summary that explains significant count changes, so that I have immediate visibility into what happened without manual investigation.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Sync_Pipeline completes a successful sync, THE Anomaly_Summary SHALL compute the difference between the current open count and the previous open count, and between the current closed count and the previous closed count.
|
||||
2. WHEN findings have been newly archived during the sync, THE Anomaly_Summary SHALL include a breakdown by classification: count of `bu_reassignment`, count of `severity_drift`, count of `closed_on_platform`, and count of `decommissioned`.
|
||||
3. WHEN findings have transitioned from ARCHIVED to RETURNED during the sync, THE Anomaly_Summary SHALL include the count of returned findings.
|
||||
4. THE Anomaly_Summary SHALL be stored as a row in the Sync_Anomaly_Log table with the sync timestamp, open count delta, closed count delta, classification breakdown as a JSON object, and the total number of newly archived findings.
|
||||
5. WHEN a GET request is made to `/api/ivanti/findings/anomaly/latest`, THE Sync_Pipeline SHALL return the most recent Anomaly_Summary row.
|
||||
6. WHEN a GET request is made to `/api/ivanti/findings/anomaly/history`, THE Sync_Pipeline SHALL return the last 30 Anomaly_Summary rows ordered by sync timestamp descending.
|
||||
7. WHEN the total number of newly archived findings in a single sync exceeds 5, THE Anomaly_Summary SHALL flag the sync as `significant` in the stored record.
|
||||
|
||||
### Requirement 3: Finding-Level BU Tracking
|
||||
|
||||
**User Story:** As a security analyst, I want the system to store the BU on each cached finding and detect when a finding's BU changes across syncs, so that BU reassignment is tracked as a distinct event from disappearance.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Sync_Pipeline SHALL store the BU_Field value (`buOwnership`) on each finding in the `ivanti_findings_cache` JSON payload, preserving the value extracted from `assetCustomAttributes.1550_host_1`.
|
||||
2. WHEN the Sync_Pipeline processes a sync result, THE Sync_Pipeline SHALL compare each finding's current BU_Field value against the previously cached BU_Field value for the same finding ID.
|
||||
3. WHEN a finding's BU_Field value differs from the previously cached value and both values are non-empty, THE Sync_Pipeline SHALL insert a row into the Finding_BU_History table recording the finding_id, previous BU, new BU, and detection timestamp.
|
||||
4. WHEN a GET request is made to `/api/ivanti/findings/bu-changes`, THE Sync_Pipeline SHALL return all Finding_BU_History rows ordered by detected_at descending.
|
||||
5. WHEN a GET request is made to `/api/ivanti/findings/:findingId/bu-history`, THE Sync_Pipeline SHALL return the Finding_BU_History rows for the specified finding ordered by detected_at descending.
|
||||
6. IF a finding appears in the sync results for the first time with no previously cached BU_Field value, THEN THE Sync_Pipeline SHALL store the BU_Field value without recording a BU change event.
|
||||
|
||||
### Requirement 4: Database Schema for Anomaly and BU Tracking
|
||||
|
||||
**User Story:** As a developer, I want the anomaly and BU tracking data stored in normalized SQLite tables, so that the data model supports efficient queries and integrates with the existing migration pattern.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE migration script SHALL create an `ivanti_sync_anomaly_log` table with columns for id (autoincrement primary key), sync_timestamp (datetime), open_count_delta (integer), closed_count_delta (integer), newly_archived_count (integer), returned_count (integer), classification_json (text storing the breakdown object), is_significant (boolean integer), and created_at (datetime).
|
||||
2. THE migration script SHALL create an `ivanti_finding_bu_history` table with columns for id (autoincrement primary key), finding_id (text), finding_title (text), host_name (text), previous_bu (text), new_bu (text), detected_at (datetime), and created_at (datetime).
|
||||
3. THE migration script SHALL create an index on `ivanti_sync_anomaly_log(sync_timestamp)` for efficient latest-record queries.
|
||||
4. THE migration script SHALL create an index on `ivanti_finding_bu_history(finding_id)` for efficient per-finding history lookups.
|
||||
5. THE migration script SHALL create an index on `ivanti_finding_bu_history(detected_at)` for efficient chronological queries.
|
||||
6. THE migration script SHALL be located at `backend/migrations/add_sync_anomaly_tables.js` and use `CREATE TABLE IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS` to be idempotent.
|
||||
|
||||
### Requirement 5: Anomaly Banner UI
|
||||
|
||||
**User Story:** As a security analyst, I want a banner on the Vulnerability Triage page that surfaces the latest sync anomaly summary, so that significant count changes are immediately visible without navigating to a separate page.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Vulnerability Triage page loads, THE Anomaly_Banner SHALL fetch the latest Anomaly_Summary from `/api/ivanti/findings/anomaly/latest`.
|
||||
2. WHEN the latest Anomaly_Summary has `is_significant` set to true, THE Anomaly_Banner SHALL display a warning banner showing the total count change and the classification breakdown (e.g., "45 findings archived — 38 BU reassignment, 5 closed, 2 decommissioned").
|
||||
3. WHEN the latest Anomaly_Summary has `is_significant` set to false, THE Anomaly_Banner SHALL not display a banner.
|
||||
4. THE Anomaly_Banner SHALL include a dismiss button that hides the banner for the current session.
|
||||
5. THE Anomaly_Banner SHALL use amber (#F59E0B) background tint and the AlertTriangle icon from Lucide, consistent with the existing dashboard warning patterns.
|
||||
6. THE Anomaly_Banner SHALL use monospace typography and the dark theme color palette defined in DESIGN_SYSTEM.md.
|
||||
7. WHEN the user clicks the classification breakdown text in the Anomaly_Banner, THE Anomaly_Banner SHALL expand to show a detailed list of affected findings grouped by classification.
|
||||
|
||||
### Requirement 6: Archive Transition Reason Enhancement
|
||||
|
||||
**User Story:** As a security analyst, I want archive transitions to record the specific reason a finding disappeared (BU reassignment, severity drift, decommission, closure), so that the archive history provides actionable context instead of a generic "severity_score_drift" label.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the BU_Drift_Checker classifies a newly archived finding as `bu_reassignment`, THE Archive_Detector SHALL update the corresponding `ivanti_archive_transitions` row's reason field to `bu_reassignment:<new_bu>` where `<new_bu>` is the BU the finding was reassigned to.
|
||||
2. WHEN the BU_Drift_Checker classifies a newly archived finding as `severity_drift`, THE Archive_Detector SHALL update the corresponding `ivanti_archive_transitions` row's reason field to `severity_drift:<new_severity>` where `<new_severity>` is the finding's current severity score.
|
||||
3. WHEN the BU_Drift_Checker classifies a newly archived finding as `decommissioned`, THE Archive_Detector SHALL update the corresponding `ivanti_archive_transitions` row's reason field to `decommissioned`.
|
||||
4. WHEN the BU_Drift_Checker classifies a newly archived finding as `closed_on_platform`, THE Archive_Detector SHALL update the corresponding `ivanti_archive_transitions` row's reason field to `closed_on_platform`.
|
||||
5. THE existing archive transition rows with reason `severity_score_drift` SHALL remain unchanged — the enhanced reasons apply only to transitions created after this feature is deployed.
|
||||
|
||||
### Requirement 7: Anomaly History API for Trend Analysis
|
||||
|
||||
**User Story:** As a security analyst, I want to view anomaly history over time, so that I can identify patterns in BU reassignments and score drift across multiple sync cycles.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a GET request is made to `/api/ivanti/findings/anomaly/history` with optional query parameters `from` and `to` (ISO date strings), THE Sync_Pipeline SHALL return Anomaly_Summary rows within the specified date range.
|
||||
2. WHEN no `from` or `to` parameters are provided, THE Sync_Pipeline SHALL return the last 30 Anomaly_Summary rows.
|
||||
3. WHEN an unauthenticated request is made to any anomaly or BU history endpoint, THE Sync_Pipeline SHALL return a 401 status code.
|
||||
4. THE anomaly history response SHALL include each row's sync_timestamp, open_count_delta, closed_count_delta, newly_archived_count, returned_count, classification_json (parsed as an object), and is_significant flag.
|
||||
178
.kiro/specs/sync-anomaly-detection/tasks.md
Normal file
178
.kiro/specs/sync-anomaly-detection/tasks.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# Implementation Plan: Sync Anomaly Detection and BU Drift Monitoring
|
||||
|
||||
## Overview
|
||||
|
||||
This plan implements the sync anomaly detection feature in incremental steps: database migration first, then core classification and summary logic, BU tracking in the sync pipeline, new API endpoints, archive transition enhancement, and finally the React anomaly banner. Each task builds on the previous, with property-based tests validating correctness properties from the design document.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 1. Create database migration script
|
||||
- [x] 1.1 Create `backend/migrations/add_sync_anomaly_tables.js`
|
||||
- Create `ivanti_sync_anomaly_log` table with columns: id (autoincrement PK), sync_timestamp (datetime NOT NULL DEFAULT CURRENT_TIMESTAMP), open_count_delta (integer NOT NULL DEFAULT 0), closed_count_delta (integer NOT NULL DEFAULT 0), newly_archived_count (integer NOT NULL DEFAULT 0), returned_count (integer NOT NULL DEFAULT 0), classification_json (text NOT NULL DEFAULT '{}'), is_significant (integer NOT NULL DEFAULT 0), created_at (datetime DEFAULT CURRENT_TIMESTAMP)
|
||||
- Create `ivanti_finding_bu_history` table with columns: id (autoincrement PK), finding_id (text NOT NULL), finding_title (text NOT NULL DEFAULT ''), host_name (text NOT NULL DEFAULT ''), previous_bu (text NOT NULL), new_bu (text NOT NULL), detected_at (datetime NOT NULL DEFAULT CURRENT_TIMESTAMP), created_at (datetime DEFAULT CURRENT_TIMESTAMP)
|
||||
- Create index `idx_anomaly_sync_timestamp` on `ivanti_sync_anomaly_log(sync_timestamp)`
|
||||
- Create index `idx_bu_history_finding_id` on `ivanti_finding_bu_history(finding_id)`
|
||||
- Create index `idx_bu_history_detected_at` on `ivanti_finding_bu_history(detected_at)`
|
||||
- Use `CREATE TABLE IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS` for idempotency
|
||||
- Follow the standalone Node script pattern from `add_closed_gone_state.js` (open DB directly, promise-based helpers, run/all wrappers)
|
||||
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5, 4.6_
|
||||
|
||||
- [x] 1.2 Run migration and verify tables exist
|
||||
- Execute `node backend/migrations/add_sync_anomaly_tables.js`
|
||||
- Verify both tables and all three indexes were created
|
||||
- Run migration a second time to confirm idempotency (no errors on re-run)
|
||||
- _Requirements: 4.6_
|
||||
|
||||
- [x] 2. Implement BU drift classifier and batch logic
|
||||
- [x] 2.1 Implement `runBUDriftChecker` function in `backend/routes/ivantiFindings.js`
|
||||
- Add `runBUDriftChecker(db, newlyArchivedIds, apiKey, clientId, skipTls)` async function
|
||||
- Chunk `newlyArchivedIds` into batches of 50
|
||||
- For each batch, call `ivantiPost()` with a filter on `id` field only (no BU, severity, or state filters) using the unfiltered query pattern from `bu-reassignment-check.js`
|
||||
- Classify each finding: BU not in {NTS-AEO-ACCESS-ENG, NTS-AEO-STEAM} → `bu_reassignment`; BU matches + severity < 8.5 → `severity_drift`; BU matches + state Closed → `closed_on_platform`; not found → `decommissioned`
|
||||
- Update the corresponding `ivanti_archive_transitions` row's reason field with the formatted classification
|
||||
- Return classification summary object: `{ bu_reassignment: N, severity_drift: N, closed_on_platform: N, decommissioned: N }`
|
||||
- Wrap each batch in try/catch — log errors, skip failed batches, never throw
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7_
|
||||
|
||||
- [ ]* 2.2 Write property test for classification correctness
|
||||
- **Property 1: Classification correctness**
|
||||
- Generate random {bu, severity, state, found} tuples, verify classifier produces the correct classification based on BU value, severity threshold (8.5), and state
|
||||
- **Validates: Requirements 1.2, 1.3, 1.4, 1.5**
|
||||
|
||||
- [ ]* 2.3 Write property test for archive transition reason formatting
|
||||
- **Property 2: Archive transition reason formatting**
|
||||
- Generate random classification results with BU values and severity scores, verify reason string format: `bu_reassignment:B`, `severity_drift:S`, `closed_on_platform`, `decommissioned`
|
||||
- **Validates: Requirements 6.1, 6.2, 6.3, 6.4**
|
||||
|
||||
- [ ]* 2.4 Write property test for batch size constraint
|
||||
- **Property 3: Batch size constraint**
|
||||
- Generate random-length ID arrays (0 to 500), verify chunking produces ceil(N/50) batches, each batch has at most 50 IDs, and the union of all batches equals the original list
|
||||
- **Validates: Requirements 1.7**
|
||||
|
||||
- [x] 3. Implement anomaly summary computation
|
||||
- [x] 3.1 Implement `computeAnomalySummary` function in `backend/routes/ivantiFindings.js`
|
||||
- Add `computeAnomalySummary(db, openCountDelta, closedCountDelta, newlyArchivedCount, returnedCount, classificationBreakdown)` async function
|
||||
- Compute `is_significant`: true if `newlyArchivedCount > 5`
|
||||
- Insert a row into `ivanti_sync_anomaly_log` with all fields
|
||||
- Log the summary to console
|
||||
- Wrap in try/catch — log errors, never throw (anomaly summary is informational)
|
||||
- _Requirements: 2.1, 2.4, 2.7_
|
||||
|
||||
- [ ]* 3.2 Write property test for significance threshold
|
||||
- **Property 4: Significance threshold**
|
||||
- Generate random non-negative integers for `newly_archived_count`, verify `is_significant` is true if and only if `newly_archived_count > 5`
|
||||
- **Validates: Requirements 2.7**
|
||||
|
||||
- [ ]* 3.3 Write property test for count delta computation
|
||||
- **Property 5: Count delta computation**
|
||||
- Generate random pairs of non-negative integers (previous_count, current_count), verify delta equals `current_count - previous_count` for both open and closed counts
|
||||
- **Validates: Requirements 2.1**
|
||||
|
||||
- [x] 4. Checkpoint — Verify core logic
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 5. Integrate BU comparison into syncFindings
|
||||
- [x] 5.1 Add per-finding BU comparison logic to `syncFindings()` in `backend/routes/ivantiFindings.js`
|
||||
- After reading `previousFindings` and before writing the new cache, compare each finding's `buOwnership` against the previous finding's `buOwnership`
|
||||
- When both values are non-empty and differ, insert a row into `ivanti_finding_bu_history` with finding_id, finding_title, host_name, previous_bu, new_bu, and detected_at
|
||||
- When a finding appears for the first time (no previous entry), store the BU without recording a change event
|
||||
- Wrap in try/catch per finding — log errors, continue processing remaining findings
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.6_
|
||||
|
||||
- [ ]* 5.2 Write property test for BU extraction preservation
|
||||
- **Property 6: BU extraction preservation**
|
||||
- Generate random raw Ivanti finding objects with varying `assetCustomAttributes['1550_host_1']` arrays, verify `extractFinding` produces a finding whose `buOwnership` equals the first element of that array
|
||||
- **Validates: Requirements 3.1**
|
||||
|
||||
- [ ]* 5.3 Write property test for BU change detection
|
||||
- **Property 7: BU change detection and recording**
|
||||
- Generate random previous/current finding pairs with varying BU values (same, different, empty), verify that a BU history row is inserted only when both values are non-empty and differ
|
||||
- **Validates: Requirements 3.2, 3.3, 3.6**
|
||||
|
||||
- [x] 6. Wire drift checker and anomaly summary into sync pipeline
|
||||
- [x] 6.1 Integrate `runBUDriftChecker` and `computeAnomalySummary` into `syncFindings()` flow
|
||||
- Collect `newlyArchivedIds` from `detectArchiveChanges` (modify it to return the list of disappeared IDs)
|
||||
- Collect `returnedCount` from `detectArchiveChanges` (count of ARCHIVED → RETURNED transitions)
|
||||
- After `detectClosedGoneFindings`, call `runBUDriftChecker` with the newly archived IDs
|
||||
- Compute `openCountDelta` and `closedCountDelta` by comparing current counts against previous counts from `ivanti_counts_cache`
|
||||
- Call `computeAnomalySummary` with all collected metrics
|
||||
- Wrap both calls in try/catch — failures are non-fatal and must not block sync completion
|
||||
- Export `runBUDriftChecker`, `computeAnomalySummary`, and `extractFinding` from the module for testing
|
||||
- _Requirements: 1.1, 2.1, 2.2, 2.3, 2.4, 2.7_
|
||||
|
||||
- [x] 7. Checkpoint — Verify pipeline integration
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 8. Add anomaly and BU history API endpoints
|
||||
- [x] 8.1 Add `GET /anomaly/latest` endpoint to `createIvantiFindingsRouter`
|
||||
- Query `ivanti_sync_anomaly_log` for the row with the maximum `sync_timestamp`
|
||||
- Parse `classification_json` into an object in the response
|
||||
- Return `{ anomaly: row }` or `{ anomaly: null }` if no records exist
|
||||
- _Requirements: 2.5_
|
||||
|
||||
- [x] 8.2 Add `GET /anomaly/history` endpoint to `createIvantiFindingsRouter`
|
||||
- Accept optional `from` and `to` query parameters (ISO date strings)
|
||||
- If date params provided, filter by `sync_timestamp` range (inclusive)
|
||||
- If no date params, return last 30 rows ordered by `sync_timestamp` descending
|
||||
- Parse `classification_json` into an object for each row
|
||||
- Return each row with: sync_timestamp, open_count_delta, closed_count_delta, newly_archived_count, returned_count, classification (parsed object), is_significant
|
||||
- _Requirements: 2.6, 7.1, 7.2, 7.3, 7.4_
|
||||
|
||||
- [x] 8.3 Add `GET /bu-changes` endpoint to `createIvantiFindingsRouter`
|
||||
- Query all rows from `ivanti_finding_bu_history` ordered by `detected_at` descending
|
||||
- Return `{ changes: rows }`
|
||||
- _Requirements: 3.4_
|
||||
|
||||
- [x] 8.4 Add `GET /:findingId/bu-history` endpoint to `createIvantiFindingsRouter`
|
||||
- Query `ivanti_finding_bu_history` where `finding_id` matches the URL param, ordered by `detected_at` descending
|
||||
- Return `{ finding_id, history: rows }`
|
||||
- Place this route definition carefully to avoid conflicts with existing `/:findingId/note` and `/:findingId/override` routes
|
||||
- _Requirements: 3.5_
|
||||
|
||||
- [ ]* 8.5 Write property tests for API query behaviors
|
||||
- **Property 8: Latest anomaly returns most recent** — Generate random sequences of anomaly rows with distinct timestamps, verify `/anomaly/latest` returns the row with the maximum timestamp
|
||||
- **Property 9: Anomaly history ordering and limit** — Generate random sets of N anomaly rows, verify `/anomaly/history` returns min(N, 30) rows ordered by timestamp descending
|
||||
- **Property 10: Date-range filtering with complete response shape** — Generate random date ranges and anomaly rows, verify only rows within range are returned with correct fields
|
||||
- **Property 11: BU changes endpoint ordering** — Generate random BU change rows, verify `/bu-changes` returns all rows ordered by `detected_at` descending
|
||||
- **Property 12: Per-finding BU history filtering** — Generate random BU history rows across multiple findings, verify `/:findingId/bu-history` returns only matching rows ordered by `detected_at` descending
|
||||
- **Validates: Requirements 2.5, 2.6, 3.4, 3.5, 7.1, 7.2, 7.4**
|
||||
|
||||
- [x] 9. Checkpoint — Verify endpoints and properties
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 10. Implement Anomaly Banner UI component
|
||||
- [x] 10.1 Create `frontend/src/components/pages/AnomalyBanner.js`
|
||||
- Fetch latest anomaly summary from `/api/ivanti/findings/anomaly/latest` on mount
|
||||
- If `is_significant` is false or no anomaly exists, render nothing
|
||||
- If `is_significant` is true, render a warning banner with:
|
||||
- Amber background tint (`rgba(245, 158, 11, 0.15)`) with amber border (`rgba(245, 158, 11, 0.3)`)
|
||||
- `AlertTriangle` icon from lucide-react
|
||||
- Summary text showing total count change and classification breakdown (e.g., "45 findings archived — 38 BU reassignment, 5 severity drift, 2 decommissioned")
|
||||
- Expandable detail section (click to toggle) for affected findings grouped by classification
|
||||
- Dismiss button (X icon) that hides the banner for the current session via `useState`
|
||||
- Use monospace typography (`JetBrains Mono`) and dark theme colors per `DESIGN_SYSTEM.md`
|
||||
- Match the inline style pattern used by `IvantiCountsChart.js`
|
||||
- _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7_
|
||||
|
||||
- [x] 10.2 Integrate `AnomalyBanner` into the Vulnerability Triage page
|
||||
- Import and render `AnomalyBanner` above the `IvantiCountsChart` component on the Vulnerability Triage page
|
||||
- _Requirements: 5.1_
|
||||
|
||||
- [x] 11. Enhance archive transition reasons
|
||||
- [x] 11.1 Verify archive transition reason updates from `runBUDriftChecker`
|
||||
- Confirm that `runBUDriftChecker` (task 2.1) correctly updates `ivanti_archive_transitions.reason` with formatted values: `bu_reassignment:<new_bu>`, `severity_drift:<new_severity>`, `closed_on_platform`, `decommissioned`
|
||||
- Confirm existing rows with `severity_score_drift` are not modified — enhanced reasons apply only to new transitions
|
||||
- _Requirements: 6.1, 6.2, 6.3, 6.4, 6.5_
|
||||
|
||||
- [x] 12. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation after each major integration point
|
||||
- Property tests validate the 12 correctness properties defined in the design document
|
||||
- The migration must be run before any other tasks (task 1)
|
||||
- All new functions are added to the existing `ivantiFindings.js` module — no new route files
|
||||
- The BU comparison in `syncFindings` (task 5) must happen before the cache is overwritten, which is the only point where both old and new BU values are in memory
|
||||
1
.kiro/specs/user-profile/.config.kiro
Normal file
1
.kiro/specs/user-profile/.config.kiro
Normal file
@@ -0,0 +1 @@
|
||||
{"specId": "74f6201d-ed0f-4df3-86a2-4a0767dd497c", "workflowType": "requirements-first", "specType": "feature"}
|
||||
361
.kiro/specs/user-profile/design.md
Normal file
361
.kiro/specs/user-profile/design.md
Normal file
@@ -0,0 +1,361 @@
|
||||
# Design Document: User Profile
|
||||
|
||||
## Overview
|
||||
|
||||
This feature adds a self-service user profile to the STEAM Security Dashboard. It introduces three capabilities: a profile panel accessible from the UserMenu dropdown (displaying account details and a password change form), a dedicated backend API endpoint for fetching profile data, and visual fixes to the UserMenu component to match the dark dashboard theme.
|
||||
|
||||
The scope is intentionally narrow — no new database tables or migrations are required. The existing `users` table already stores all needed fields (`username`, `email`, `user_group`, `created_at`, `last_login`). The backend adds two new routes to the existing auth router. The frontend adds one new component (`UserProfilePanel`) and modifies the existing `UserMenu` component for theming and profile access.
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
1. **Profile endpoint on the auth router** — The profile data is user-scoped and session-authenticated, so it belongs alongside `/api/auth/me` rather than on the admin-only `/api/users` router. This avoids granting non-admin users access to the users management routes.
|
||||
|
||||
2. **Password change on the auth router** — Self-service password change is an auth concern, not a user-management concern. Placing it at `POST /api/auth/change-password` keeps it separate from the admin `PATCH /api/users/:id` endpoint that already supports admin-initiated password resets.
|
||||
|
||||
3. **Rate limiting via express-rate-limit** — The project already uses `express-rate-limit` for login throttling. The password change endpoint reuses the same library with a tighter limit (5 attempts per 15 minutes) scoped per session cookie using a custom `keyGenerator`.
|
||||
|
||||
4. **No new database tables or migrations** — All required data already exists in the `users` table. The `created_at` and `last_login` columns are present in the schema. No schema changes are needed.
|
||||
|
||||
5. **Modal-based profile panel** — The profile panel is implemented as a modal overlay (consistent with existing modals like NvdSyncModal, UserManagement) rather than a separate page, since the app uses no client-side router.
|
||||
|
||||
6. **Inline style objects for theming** — Consistent with the project's existing pattern where components define style constants as JavaScript objects. The UserMenu theming fix converts Tailwind utility classes to inline styles matching the design system.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as User
|
||||
participant UM as UserMenu
|
||||
participant UPP as UserProfilePanel
|
||||
participant API as Auth API
|
||||
participant DB as SQLite
|
||||
|
||||
U->>UM: Clicks "My Profile"
|
||||
UM->>UPP: Opens modal (showProfile=true)
|
||||
UPP->>API: GET /api/auth/profile
|
||||
API->>DB: SELECT user by session
|
||||
DB-->>API: User row
|
||||
API-->>UPP: { id, username, email, group, created_at, last_login }
|
||||
UPP-->>U: Displays profile data
|
||||
|
||||
U->>UPP: Submits password change form
|
||||
UPP->>UPP: Client-side validation (match, length)
|
||||
UPP->>API: POST /api/auth/change-password
|
||||
API->>API: Rate limit check (5/15min)
|
||||
API->>DB: SELECT password_hash WHERE id = ?
|
||||
DB-->>API: password_hash
|
||||
API->>API: bcrypt.compare(currentPassword, hash)
|
||||
API->>API: bcrypt.hash(newPassword, 10)
|
||||
API->>DB: UPDATE users SET password_hash = ?
|
||||
API->>DB: INSERT audit_logs (password_change)
|
||||
API-->>UPP: { message: 'Password changed successfully' }
|
||||
UPP-->>U: Success message, form cleared
|
||||
```
|
||||
|
||||
### Component Hierarchy
|
||||
|
||||
```
|
||||
App.js
|
||||
├── UserMenu.js (modified — dark theme, "My Profile" option)
|
||||
│ └── UserProfilePanel.js (new — modal component)
|
||||
│ ├── Profile Info Section
|
||||
│ └── Password Change Form
|
||||
```
|
||||
|
||||
### Backend Route Structure
|
||||
|
||||
```
|
||||
/api/auth/
|
||||
├── POST /login (existing)
|
||||
├── POST /logout (existing)
|
||||
├── GET /me (existing)
|
||||
├── GET /profile (new — full profile data)
|
||||
├── POST /change-password (new — self-service password change)
|
||||
└── POST /cleanup-sessions (existing)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Components and Interfaces
|
||||
|
||||
### Backend: New Routes in `routes/auth.js`
|
||||
|
||||
#### `GET /api/auth/profile`
|
||||
|
||||
Returns the full profile for the authenticated user.
|
||||
|
||||
| Aspect | Detail |
|
||||
|--------|--------|
|
||||
| Auth | `requireAuth(db)` |
|
||||
| Query | `SELECT id, username, email, user_group, created_at, last_login FROM users WHERE id = ? AND is_active = 1` |
|
||||
| Success | `200 { id, username, email, group, created_at, last_login }` |
|
||||
| Inactive account | `401 { error }` + clear session cookie |
|
||||
| No session | `401 { error: 'Authentication required' }` |
|
||||
|
||||
#### `POST /api/auth/change-password`
|
||||
|
||||
Allows the authenticated user to change their own password.
|
||||
|
||||
| Aspect | Detail |
|
||||
|--------|--------|
|
||||
| Auth | `requireAuth(db)` |
|
||||
| Rate limit | 5 requests per 15 minutes, keyed by `req.cookies.session_id` |
|
||||
| Body | `{ currentPassword: string, newPassword: string }` |
|
||||
| Validation | `newPassword.length >= 8` (server-side) |
|
||||
| Flow | 1. Verify account active 2. `bcrypt.compare` current password 3. `bcrypt.hash` new password (cost 10) 4. `UPDATE users SET password_hash` 5. `logAudit` with action `password_change` |
|
||||
| Success | `200 { message: 'Password changed successfully' }` |
|
||||
| Wrong password | `401 { error: 'Current password is incorrect' }` |
|
||||
| Too short | `400 { error: 'New password must be at least 8 characters' }` |
|
||||
| Rate limited | `429 { error: 'Too many password change attempts. Please try again later.' }` |
|
||||
| Inactive | `401 { error: 'Account is disabled' }` |
|
||||
|
||||
### Frontend: New Component `UserProfilePanel.js`
|
||||
|
||||
A modal component rendered when the user clicks "My Profile" in the UserMenu dropdown.
|
||||
|
||||
**Props:**
|
||||
|
||||
| Prop | Type | Description |
|
||||
|------|------|-------------|
|
||||
| `isOpen` | `boolean` | Controls modal visibility |
|
||||
| `onClose` | `function` | Callback to close the modal |
|
||||
|
||||
**Internal State:**
|
||||
|
||||
| State | Type | Purpose |
|
||||
|-------|------|---------|
|
||||
| `profile` | `object \| null` | Profile data from API |
|
||||
| `loading` | `boolean` | Loading state for profile fetch |
|
||||
| `error` | `string \| null` | Error message from profile fetch |
|
||||
| `currentPassword` | `string` | Current password field |
|
||||
| `newPassword` | `string` | New password field |
|
||||
| `confirmPassword` | `string` | Confirm password field |
|
||||
| `changeLoading` | `boolean` | Loading state for password change |
|
||||
| `changeError` | `string \| null` | Error from password change API |
|
||||
| `changeSuccess` | `string \| null` | Success message after password change |
|
||||
|
||||
**Behavior:**
|
||||
- On open (`isOpen` transitions to `true`), fetches `GET /api/auth/profile`
|
||||
- Displays profile fields in a read-only info section
|
||||
- Password change form validates client-side before submitting:
|
||||
- New password and confirm must match
|
||||
- New password must be >= 8 characters
|
||||
- On successful password change, shows success message and clears form fields
|
||||
- Click-outside or X button closes the modal
|
||||
- Uses design system dark theme styling (intel-card background, accent borders, light text)
|
||||
|
||||
### Frontend: Modified Component `UserMenu.js`
|
||||
|
||||
**Changes:**
|
||||
1. Add "My Profile" menu item with `User` icon between the dropdown header and admin actions
|
||||
2. Convert all Tailwind light-theme classes to inline dark-theme styles:
|
||||
- Button: `hover:bg-gray-100` → `hover: rgba(14, 165, 233, 0.1)`
|
||||
- Username text: `text-gray-900` → `color: var(--text-primary)` / `#F8FAFC`
|
||||
- Group text: `text-gray-500` → `color: var(--text-secondary)` / `#E2E8F0`
|
||||
- Chevron: `text-gray-500` → `color: var(--text-secondary)` / `#E2E8F0`
|
||||
- Dropdown panel: `bg-white` → intel-card gradient background
|
||||
- Dropdown border: `border-gray-200` → `rgba(14, 165, 233, 0.3)`
|
||||
- Menu items: `text-gray-700` → `color: var(--text-primary)` / `#F8FAFC`
|
||||
- Menu hover: `hover:bg-gray-50` → `rgba(14, 165, 233, 0.1)`
|
||||
- Sign out: `text-red-600` → `#F87171` (design system danger text)
|
||||
3. Add state and handler for profile panel visibility
|
||||
4. Render `UserProfilePanel` component
|
||||
|
||||
---
|
||||
|
||||
## Data Models
|
||||
|
||||
No new database tables or migrations are required. The feature reads from the existing `users` table:
|
||||
|
||||
```sql
|
||||
-- Existing users table (relevant columns)
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username VARCHAR(50) UNIQUE NOT NULL,
|
||||
email VARCHAR(255) UNIQUE NOT NULL,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
role VARCHAR(20) NOT NULL DEFAULT 'viewer',
|
||||
user_group VARCHAR(20) NOT NULL DEFAULT 'Read_Only',
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
last_login TIMESTAMP
|
||||
);
|
||||
```
|
||||
|
||||
### API Response Shapes
|
||||
|
||||
**GET /api/auth/profile response:**
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"username": "admin",
|
||||
"email": "admin@localhost",
|
||||
"group": "Admin",
|
||||
"created_at": "2026-01-15 10:30:00",
|
||||
"last_login": "2026-07-20 14:22:00"
|
||||
}
|
||||
```
|
||||
|
||||
**POST /api/auth/change-password request:**
|
||||
```json
|
||||
{
|
||||
"currentPassword": "oldpass123",
|
||||
"newPassword": "newpass456"
|
||||
}
|
||||
```
|
||||
|
||||
**POST /api/auth/change-password success response:**
|
||||
```json
|
||||
{
|
||||
"message": "Password changed successfully"
|
||||
}
|
||||
```
|
||||
|
||||
**Audit log entry for password change:**
|
||||
```json
|
||||
{
|
||||
"userId": 1,
|
||||
"username": "admin",
|
||||
"action": "password_change",
|
||||
"entityType": "auth",
|
||||
"entityId": null,
|
||||
"details": null,
|
||||
"ipAddress": "::1"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 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: Profile panel displays all required fields
|
||||
|
||||
*For any* valid profile object (with arbitrary username, email, group, created_at, and last_login values), rendering the UserProfilePanel with that data SHALL result in all five field values being present in the rendered output.
|
||||
|
||||
**Validates: Requirements 1.2**
|
||||
|
||||
### Property 2: Profile API returns complete user data matching database
|
||||
|
||||
*For any* active user record in the database, a GET request to `/api/auth/profile` with that user's valid session SHALL return an object containing `id`, `username`, `email`, `group`, `created_at`, and `last_login` fields, where each value matches the corresponding column in the `users` table.
|
||||
|
||||
**Validates: Requirements 4.1**
|
||||
|
||||
### Property 3: Password change round-trip
|
||||
|
||||
*For any* valid current password and *any* new password of 8 or more characters, after a successful `POST /api/auth/change-password`, the stored `password_hash` in the database SHALL be a valid bcrypt hash and `bcrypt.compare(newPassword, storedHash)` SHALL return `true`.
|
||||
|
||||
**Validates: Requirements 2.2, 2.7**
|
||||
|
||||
### Property 4: Incorrect current password is always rejected
|
||||
|
||||
*For any* password string that does not match the user's current password, submitting it as `currentPassword` to `POST /api/auth/change-password` SHALL return HTTP 401 and the user's stored `password_hash` SHALL remain unchanged.
|
||||
|
||||
**Validates: Requirements 2.3**
|
||||
|
||||
### Property 5: Mismatched password confirmation is rejected client-side
|
||||
|
||||
*For any* two distinct strings used as `newPassword` and `confirmPassword` in the Password_Change_Form, the form SHALL display a validation error and SHALL NOT submit a request to the Auth_API.
|
||||
|
||||
**Validates: Requirements 2.4**
|
||||
|
||||
### Property 6: Short passwords are rejected at both client and server
|
||||
|
||||
*For any* string of length 0 through 7, the Password_Change_Form SHALL display a minimum-length validation error (client-side), and `POST /api/auth/change-password` SHALL return HTTP 400 (server-side). In both cases, the user's stored `password_hash` SHALL remain unchanged.
|
||||
|
||||
**Validates: Requirements 2.5, 5.4**
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Backend Errors
|
||||
|
||||
| Scenario | HTTP Status | Response | Behavior |
|
||||
|----------|-------------|----------|----------|
|
||||
| No session cookie on `/profile` | 401 | `{ error: 'Authentication required' }` | Handled by `requireAuth` middleware |
|
||||
| Expired session on `/profile` | 401 | `{ error: 'Session expired or invalid' }` | Handled by `requireAuth` middleware |
|
||||
| Deactivated account on `/profile` | 401 | `{ error: 'Account is disabled' }` | Clear session cookie, return 401 |
|
||||
| No session on `/change-password` | 401 | `{ error: 'Authentication required' }` | Handled by `requireAuth` middleware |
|
||||
| Rate limit exceeded on `/change-password` | 429 | `{ error: 'Too many password change attempts. Please try again later.' }` | `express-rate-limit` middleware |
|
||||
| Missing `currentPassword` or `newPassword` | 400 | `{ error: 'Current password and new password are required' }` | Early return validation |
|
||||
| New password < 8 characters | 400 | `{ error: 'New password must be at least 8 characters' }` | Early return validation |
|
||||
| Incorrect current password | 401 | `{ error: 'Current password is incorrect' }` | After `bcrypt.compare` fails |
|
||||
| Deactivated account on `/change-password` | 401 | `{ error: 'Account is disabled' }` | Check `is_active` before processing |
|
||||
| Database error during profile fetch | 500 | `{ error: 'Failed to fetch profile' }` | Catch block, log to console |
|
||||
| Database error during password update | 500 | `{ error: 'Failed to change password' }` | Catch block, log to console |
|
||||
|
||||
### Frontend Error Handling
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| Profile fetch fails (network error) | Display error message in panel, offer retry |
|
||||
| Profile fetch returns 401 | Redirect to login (session expired) |
|
||||
| Password change returns 401 (wrong password) | Display "Current password is incorrect" in form |
|
||||
| Password change returns 429 | Display "Too many attempts. Please try again later." in form |
|
||||
| Password change returns 400 | Display server validation error message in form |
|
||||
| Password change returns 500 | Display "An error occurred. Please try again." in form |
|
||||
| Client-side validation failure (mismatch) | Display "Passwords do not match" below confirm field |
|
||||
| Client-side validation failure (too short) | Display "Password must be at least 8 characters" below new password field |
|
||||
|
||||
---
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Property-Based Tests
|
||||
|
||||
This feature is suitable for property-based testing. The password change logic involves pure input/output behavior (password validation, hashing, comparison) with a large input space (arbitrary strings). The profile data retrieval has clear invariants (all fields present, values match database).
|
||||
|
||||
**Library:** [fast-check](https://github.com/dubzzz/fast-check) — the standard PBT library for JavaScript.
|
||||
|
||||
**Configuration:**
|
||||
- Minimum 100 iterations per property test
|
||||
- Each test tagged with: `Feature: user-profile, Property {number}: {property_text}`
|
||||
|
||||
**Properties to implement:**
|
||||
1. Profile panel renders all fields (Property 1) — generate random profile objects, render component, assert all values present
|
||||
2. Profile API returns complete data (Property 2) — generate random user records, insert into test DB, fetch profile, assert field match
|
||||
3. Password change round-trip (Property 3) — generate random valid passwords, change password, verify bcrypt.compare succeeds
|
||||
4. Wrong password rejection (Property 4) — generate random wrong passwords, attempt change, verify 401 and hash unchanged
|
||||
5. Mismatched confirmation rejection (Property 5) — generate pairs of distinct strings, verify client validation rejects
|
||||
6. Short password rejection (Property 6) — generate strings of length 0-7, verify rejection at both client and server
|
||||
|
||||
### Unit Tests (Example-Based)
|
||||
|
||||
| Test | What it verifies |
|
||||
|------|-----------------|
|
||||
| "My Profile" click opens panel | Requirement 1.1 — UI interaction |
|
||||
| Close button dismisses panel | Requirement 1.3 — close mechanism |
|
||||
| Click-outside dismisses panel | Requirement 1.3 — close mechanism |
|
||||
| Password form has three fields | Requirement 2.1 — form structure |
|
||||
| Success message shown after change | Requirement 2.6 — success feedback |
|
||||
| Form fields cleared after success | Requirement 2.6 — form reset |
|
||||
| Unauthenticated profile request returns 401 | Requirement 4.2 — auth guard |
|
||||
| Deactivated account profile request returns 401 | Requirement 4.3 — account check |
|
||||
| Deactivated account password change rejected | Requirement 5.3 — account check |
|
||||
| Rate limit triggers after 5 attempts | Requirements 5.1, 5.2 — rate limiting |
|
||||
|
||||
### Integration Tests
|
||||
|
||||
| Test | What it verifies |
|
||||
|------|-----------------|
|
||||
| Audit log entry created on password change | Requirement 2.8 — audit logging |
|
||||
| Rate limiter resets after 15-minute window | Requirement 5.1 — rate limit window |
|
||||
|
||||
### Manual Testing
|
||||
|
||||
| Test | What it verifies |
|
||||
|------|-----------------|
|
||||
| Username visible on dark header without hover | Requirement 3.1 — WCAG AA contrast |
|
||||
| Group label visible on dark header | Requirement 3.2 — contrast |
|
||||
| Hover state uses dark-themed highlight | Requirement 3.3 — theming |
|
||||
| Chevron icon uses light color | Requirement 3.4 — theming |
|
||||
| Dropdown uses dark background | Requirement 6.1 — theming |
|
||||
| Dropdown text uses light colors | Requirement 6.2 — theming |
|
||||
| Dropdown hover uses accent highlight | Requirement 6.3 — theming |
|
||||
| Dropdown border uses accent style | Requirement 6.4 — theming |
|
||||
| Group badge retains color coding | Requirement 6.5 — theming |
|
||||
87
.kiro/specs/user-profile/requirements.md
Normal file
87
.kiro/specs/user-profile/requirements.md
Normal file
@@ -0,0 +1,87 @@
|
||||
# Requirements Document
|
||||
|
||||
## Introduction
|
||||
|
||||
The STEAM Security Dashboard currently lacks a self-service user profile. Users cannot view their own account details or change their own password — only admins can reset passwords through the User Management panel. Additionally, the username text in the top-right UserMenu is rendered in black (`text-gray-900`) against the dark dashboard background, making it invisible until hovered. This feature adds a user profile panel accessible from the UserMenu, enables self-service password changes for all authenticated users, and fixes the username visibility issue in the header.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Dashboard**: The STEAM Security Dashboard application, consisting of a React 19 SPA frontend and a Node.js/Express backend with SQLite3 storage.
|
||||
- **User_Profile_Panel**: A modal or slide-over panel that displays the authenticated user's account information and provides a password change form.
|
||||
- **UserMenu**: The existing dropdown component (`UserMenu.js`) in the top-right corner of the header that shows the user icon, username, group badge, and navigation actions (Manage Users, Audit Log, Sign Out).
|
||||
- **Password_Change_Form**: A form within the User_Profile_Panel that accepts the current password and a new password (with confirmation) to allow users to change their own credentials.
|
||||
- **Auth_API**: The backend Express routes under `/api/auth` that handle login, logout, session validation, and (with this feature) self-service password changes.
|
||||
- **Authenticated_User**: Any user with a valid, non-expired session cookie and an active account.
|
||||
- **Header_Username_Display**: The text element in the UserMenu button that shows the current user's username and group label.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: User Profile Panel Access
|
||||
|
||||
**User Story:** As an authenticated user, I want to access a profile panel from the UserMenu dropdown, so that I can view my account details without needing admin assistance.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Authenticated_User clicks the "My Profile" option in the UserMenu dropdown, THE Dashboard SHALL display the User_Profile_Panel.
|
||||
2. THE User_Profile_Panel SHALL display the following account fields: username, email address, user group, account creation date, and last login timestamp.
|
||||
3. WHEN the User_Profile_Panel is open, THE Dashboard SHALL provide a visible close mechanism (close button or click-outside) to dismiss the panel.
|
||||
4. THE User_Profile_Panel SHALL use the dark theme styling defined in the Dashboard design system (intel-card backgrounds, accent borders, light text colors).
|
||||
|
||||
### Requirement 2: Self-Service Password Change
|
||||
|
||||
**User Story:** As an authenticated user, I want to change my own password from my profile, so that I can maintain my account security without requesting an admin to reset it.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE User_Profile_Panel SHALL include a Password_Change_Form with three fields: current password, new password, and confirm new password.
|
||||
2. WHEN the Authenticated_User submits the Password_Change_Form with a valid current password and matching new password fields, THE Auth_API SHALL update the password hash for that user in the database.
|
||||
3. WHEN the Authenticated_User submits the Password_Change_Form with an incorrect current password, THE Auth_API SHALL return an error and THE Password_Change_Form SHALL display a message stating the current password is incorrect.
|
||||
4. WHEN the new password and confirm new password fields do not match, THE Password_Change_Form SHALL display a validation error before submitting to the Auth_API.
|
||||
5. WHEN the new password is fewer than 8 characters, THE Password_Change_Form SHALL display a validation error stating the minimum length requirement.
|
||||
6. WHEN a password change succeeds, THE Dashboard SHALL display a success confirmation message and clear the Password_Change_Form fields.
|
||||
7. THE Auth_API SHALL hash the new password using bcryptjs before storing it in the database.
|
||||
8. WHEN a password change succeeds, THE Auth_API SHALL log an audit entry with action `password_change` for the Authenticated_User.
|
||||
|
||||
### Requirement 3: Header Username Visibility Fix
|
||||
|
||||
**User Story:** As a user, I want to see my username in the top-right header area at all times, so that I can confirm which account is logged in without hovering.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Header_Username_Display SHALL render the username text using a light color (design system `--text-primary` or equivalent) that meets WCAG AA contrast ratio against the dark header background.
|
||||
2. THE Header_Username_Display SHALL render the group label text using a secondary light color (design system `--text-secondary` or equivalent) that is visible against the dark header background.
|
||||
3. THE UserMenu button hover state SHALL use a dark-themed highlight (e.g., `rgba(14, 165, 233, 0.1)`) instead of the current light-themed `hover:bg-gray-100`.
|
||||
4. THE UserMenu dropdown chevron icon SHALL use a light color consistent with the header text colors.
|
||||
|
||||
### Requirement 4: Profile API Endpoint
|
||||
|
||||
**User Story:** As a frontend developer, I want a dedicated API endpoint that returns the full profile data for the currently authenticated user, so that the User_Profile_Panel can display account details not available in the session payload.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the Authenticated_User requests their profile, THE Auth_API SHALL return the user's id, username, email, user group, account creation date, and last login timestamp.
|
||||
2. IF an unauthenticated request is made to the profile endpoint, THEN THE Auth_API SHALL return HTTP 401 with an error message.
|
||||
3. IF the Authenticated_User's account has been deactivated, THEN THE Auth_API SHALL return HTTP 401 and clear the session cookie.
|
||||
|
||||
### Requirement 5: Password Change Security
|
||||
|
||||
**User Story:** As a security-conscious administrator, I want password changes to be rate-limited and validated, so that brute-force attempts against the current password field are mitigated.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE Auth_API SHALL enforce a rate limit on the password change endpoint of no more than 5 attempts per 15-minute window per session.
|
||||
2. IF the rate limit is exceeded, THEN THE Auth_API SHALL return HTTP 429 with a message indicating the user should try again later.
|
||||
3. THE Auth_API SHALL verify that the Authenticated_User's account is active before processing a password change.
|
||||
4. THE Auth_API SHALL validate that the new password is at least 8 characters long on the server side.
|
||||
|
||||
### Requirement 6: UserMenu Dropdown Theming
|
||||
|
||||
**User Story:** As a user, I want the UserMenu dropdown to match the dark dashboard theme, so that the interface is visually consistent.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. THE UserMenu dropdown panel SHALL use a dark background consistent with the Dashboard design system (intel-card gradient or equivalent dark surface).
|
||||
2. THE UserMenu dropdown text items SHALL use light text colors from the design system (`--text-primary` for labels, `--text-secondary` for metadata).
|
||||
3. THE UserMenu dropdown hover states SHALL use a subtle accent highlight (e.g., `rgba(14, 165, 233, 0.1)`) instead of the current light-themed `hover:bg-gray-50`.
|
||||
4. THE UserMenu dropdown border SHALL use the design system accent border style (`rgba(14, 165, 233, 0.3)` or equivalent).
|
||||
5. THE UserMenu group badge in the dropdown header SHALL retain its existing color-coded styling for group identification.
|
||||
119
.kiro/specs/user-profile/tasks.md
Normal file
119
.kiro/specs/user-profile/tasks.md
Normal file
@@ -0,0 +1,119 @@
|
||||
# Implementation Plan: User Profile
|
||||
|
||||
## Overview
|
||||
|
||||
This plan implements the user profile feature in three phases: backend API routes first (profile endpoint and password change endpoint on the existing auth router), then the frontend components (UserProfilePanel modal and UserMenu theming/integration), and finally wiring everything together. Each task builds incrementally on the previous one, and testing tasks are placed close to the code they validate.
|
||||
|
||||
## Tasks
|
||||
|
||||
- [ ] 1. Add backend profile and password change routes to `routes/auth.js`
|
||||
- [x] 1.1 Add `GET /api/auth/profile` route
|
||||
- Add a new route inside `createAuthRouter` that queries the `users` table for `id, username, email, user_group, created_at, last_login` using the session user's ID
|
||||
- Return `{ id, username, email, group, created_at, last_login }` on success
|
||||
- Return 401 if the account is inactive (with `is_active = 0`), clearing the session cookie
|
||||
- Use the existing `requireAuth(db)` middleware for authentication
|
||||
- _Requirements: 4.1, 4.2, 4.3_
|
||||
|
||||
- [x] 1.2 Add `POST /api/auth/change-password` route with rate limiting
|
||||
- Add `express-rate-limit` middleware scoped to this route: 5 requests per 15-minute window, keyed by `req.cookies.session_id`
|
||||
- Validate request body has `currentPassword` and `newPassword` fields; return 400 if missing
|
||||
- Validate `newPassword` is at least 8 characters; return 400 if too short
|
||||
- Query the user's `password_hash` and `is_active` from the database; return 401 if account is inactive
|
||||
- Use `bcrypt.compare` to verify `currentPassword`; return 401 if incorrect
|
||||
- Hash the new password with `bcrypt.hash(newPassword, 10)` and update the `password_hash` column
|
||||
- Call `logAudit` with action `password_change`, entityType `auth`
|
||||
- Return `{ message: 'Password changed successfully' }` on success
|
||||
- Return 429 with appropriate message when rate limit is exceeded
|
||||
- _Requirements: 2.2, 2.3, 2.7, 2.8, 5.1, 5.2, 5.3, 5.4_
|
||||
|
||||
- [x] 1.3 Write property tests for password change round-trip (backend)
|
||||
- **Property 3: Password change round-trip** — For any valid current password and any new password of 8+ characters, after a successful change, `bcrypt.compare(newPassword, storedHash)` returns true
|
||||
- **Validates: Requirements 2.2, 2.7**
|
||||
|
||||
- [x] 1.4 Write property tests for incorrect password rejection (backend)
|
||||
- **Property 4: Incorrect current password is always rejected** — For any password string that does not match the user's current password, the endpoint returns 401 and the stored hash remains unchanged
|
||||
- **Validates: Requirements 2.3**
|
||||
|
||||
- [x] 1.5 Write property tests for short password rejection (backend)
|
||||
- **Property 6 (server-side): Short passwords are rejected** — For any string of length 0–7, `POST /api/auth/change-password` returns 400 and the stored hash remains unchanged
|
||||
- **Validates: Requirements 2.5, 5.4**
|
||||
|
||||
- [x] 2. Checkpoint — Verify backend routes
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 3. Create `UserProfilePanel.js` frontend component
|
||||
- [x] 3.1 Create the `UserProfilePanel` modal component
|
||||
- Create `frontend/src/components/UserProfilePanel.js`
|
||||
- Accept `isOpen` and `onClose` props
|
||||
- On open, fetch `GET /api/auth/profile` with `credentials: 'include'` and display loading state
|
||||
- Render profile info section showing: username, email, group, created_at (formatted), last_login (formatted)
|
||||
- Use dark theme inline styles matching the design system (intel-card gradient background, accent borders, light text colors from `DESIGN_SYSTEM.md`)
|
||||
- Include a close button (X icon from lucide-react) and click-outside-to-close behavior
|
||||
- Display error state with retry option if profile fetch fails
|
||||
- Use icons from lucide-react (User, Mail, Shield, Calendar, Clock)
|
||||
- _Requirements: 1.1, 1.2, 1.3, 1.4_
|
||||
|
||||
- [x] 3.2 Add password change form to `UserProfilePanel`
|
||||
- Add a password change section below the profile info with three fields: current password, new password, confirm new password
|
||||
- Implement client-side validation: new password must match confirm password; new password must be >= 8 characters
|
||||
- Display inline validation errors below the relevant fields
|
||||
- On submit, call `POST /api/auth/change-password` with `{ currentPassword, newPassword }`
|
||||
- Handle API error responses (401 wrong password, 429 rate limited, 400 validation, 500 server error) and display appropriate messages
|
||||
- On success, show success message and clear all form fields
|
||||
- Style the form with dark theme inline styles (intel-input styling, intel-button-primary for submit)
|
||||
- _Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 2.6_
|
||||
|
||||
- [x] 3.3 Write property test for profile panel field rendering
|
||||
- **Property 1: Profile panel displays all required fields** — For any valid profile object with arbitrary username, email, group, created_at, and last_login values, rendering UserProfilePanel displays all five values in the output
|
||||
- **Validates: Requirements 1.2**
|
||||
|
||||
- [x] 3.4 Write property test for mismatched password confirmation
|
||||
- **Property 5: Mismatched password confirmation is rejected client-side** — For any two distinct strings used as newPassword and confirmPassword, the form displays a validation error and does not submit a request
|
||||
- **Validates: Requirements 2.4**
|
||||
|
||||
- [x] 3.5 Write property test for short password client-side rejection
|
||||
- **Property 6 (client-side): Short passwords are rejected** — For any string of length 0–7, the form displays a minimum-length validation error and does not submit a request
|
||||
- **Validates: Requirements 2.5**
|
||||
|
||||
- [x] 4. Checkpoint — Verify frontend component
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
- [x] 5. Modify `UserMenu.js` for dark theming and profile integration
|
||||
- [x] 5.1 Convert `UserMenu.js` from light theme to dark theme
|
||||
- Replace Tailwind light-theme classes with inline dark-theme style objects
|
||||
- Button: `hover:bg-gray-100` → `rgba(14, 165, 233, 0.1)` hover background
|
||||
- Username text: `text-gray-900` → `#F8FAFC` (design system `--text-primary`)
|
||||
- Group label text: `text-gray-500` → `#E2E8F0` (design system `--text-secondary`)
|
||||
- Chevron icon: `text-gray-500` → `#E2E8F0`
|
||||
- Dropdown panel: `bg-white` → intel-card gradient background; `border-gray-200` → `rgba(14, 165, 233, 0.3)`
|
||||
- Dropdown items: `text-gray-700` → `#F8FAFC`; `hover:bg-gray-50` → `rgba(14, 165, 233, 0.1)`
|
||||
- Sign out text: `text-red-600` → `#F87171`; `hover:bg-red-50` → `rgba(239, 68, 68, 0.1)`
|
||||
- Dropdown header: `text-gray-900` → `#F8FAFC`; `text-gray-500` → `#94A3B8`; `border-gray-100` → `rgba(14, 165, 233, 0.2)`
|
||||
- Retain existing group badge color-coding logic
|
||||
- _Requirements: 3.1, 3.2, 3.3, 3.4, 6.1, 6.2, 6.3, 6.4, 6.5_
|
||||
|
||||
- [x] 5.2 Add "My Profile" menu item and wire `UserProfilePanel`
|
||||
- Import `UserProfilePanel` component
|
||||
- Add `showProfile` state variable
|
||||
- Add a "My Profile" menu item with `User` icon between the dropdown header and the admin-only actions
|
||||
- On click, close the dropdown and set `showProfile` to `true`
|
||||
- Render `<UserProfilePanel isOpen={showProfile} onClose={() => setShowProfile(false)} />` in the component output
|
||||
- _Requirements: 1.1, 1.3_
|
||||
|
||||
- [x] 5.3 Write property test for profile API data completeness
|
||||
- **Property 2: Profile API returns complete user data matching database** — For any active user record, a GET request to `/api/auth/profile` with that user's valid session returns an object with `id`, `username`, `email`, `group`, `created_at`, and `last_login` fields matching the database
|
||||
- **Validates: Requirements 4.1**
|
||||
|
||||
- [x] 6. Final checkpoint — Ensure all tests pass
|
||||
- Ensure all tests pass, ask the user if questions arise.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tasks marked with `*` are optional and can be skipped for faster MVP
|
||||
- Each task references specific requirements for traceability
|
||||
- Checkpoints ensure incremental validation
|
||||
- Property tests use `fast-check` (already installed in `frontend/package.json` as a devDependency)
|
||||
- Backend tests for properties 3, 4, and 6 (server-side) will need `fast-check` added to the root `package.json` devDependencies
|
||||
- The existing `express-rate-limit` package (already in root `package.json`) is used for the password change rate limiter
|
||||
- No database migrations are needed — the existing `users` table has all required columns
|
||||
- All styling follows the dark theme design system documented in `DESIGN_SYSTEM.md`
|
||||
190
.kiro/steering/doc-standards.md
Normal file
190
.kiro/steering/doc-standards.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# Documentation Standards — CVE Dashboard
|
||||
|
||||
These standards are reverse-engineered from the existing README.md and should be treated as the canonical style guide for all documentation in this repository. When updating docs, match these conventions exactly — consistency matters more than any individual stylistic preference.
|
||||
|
||||
---
|
||||
|
||||
## Language and Style
|
||||
|
||||
- Write in **present tense, active voice**. "The sync fetches findings" — not "Findings will be fetched by the sync."
|
||||
- Do not use marketing language. No "powerful", "seamless", "robust", "cutting-edge", "unleash". Describe what the thing does, not how great it is.
|
||||
- No emoji anywhere in documentation. None.
|
||||
- Prefer precise technical vocabulary over casual phrasing. "Session tokens are stored in `httpOnly` cookies" — not "we keep the login thing in a secure cookie."
|
||||
- **Spelling:** match whatever spelling variant already appears in the surrounding prose. Do not rewrite existing words to switch between US and British English — consistency within a section matters more than which variant is used.
|
||||
|
||||
---
|
||||
|
||||
## Punctuation and Formatting
|
||||
|
||||
- **Em-dashes (—)** for mid-sentence clarifications or appositives, surrounded by spaces: `sync requires Admin or Standard_User group — the sync then fetches findings`.
|
||||
- **En-dashes (–)** for numeric ranges: `8.5–9.9 VRR`, `20 attempts per 15-minute window`.
|
||||
- Use **inline backticks** for: file paths, environment variables, CLI flags, function names, field names, HTTP status codes, and any literal value the reader should type or recognise verbatim.
|
||||
- Use **bold** (`**text**`) for UI element names (button labels, tab names, form fields) and for label-style emphasis at the start of a sub-point.
|
||||
- Avoid italics except for rare genuine emphasis. Do not use italics decoratively.
|
||||
|
||||
---
|
||||
|
||||
## Heading Hierarchy
|
||||
|
||||
Use a strict three-tier hierarchy per document:
|
||||
|
||||
```
|
||||
# Document Title (one per file, matches repo/feature name)
|
||||
## Top-Level Section (Overview, Features, Architecture, etc.)
|
||||
### Subsection (a named feature, page, or concept)
|
||||
**Sub-subsection label** (bold paragraph labels — NOT an #### heading)
|
||||
```
|
||||
|
||||
- Do **not** use `####` or deeper headings. If you need a fourth level, it should be a bold inline label followed by content, matching the existing README pattern.
|
||||
- Separate top-level `##` sections with a horizontal rule (`---`) on its own line, with blank lines above and below.
|
||||
- Do not place horizontal rules between `###` subsections unless visually necessary.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- Any document over ~200 lines should open with a Table of Contents using markdown anchor links.
|
||||
- Nest TOC entries to match heading depth (`##` entries flush-left, `###` entries indented two spaces).
|
||||
- Anchor slugs: lowercase, spaces become hyphens, em-dashes become `--` (two hyphens). Example: `## Home — CVE Management` becomes `#home--cve-management`.
|
||||
|
||||
---
|
||||
|
||||
## Tables
|
||||
|
||||
Use tables for any reference material with two or more parallel attributes. This includes:
|
||||
|
||||
- Permission matrices (group → capabilities)
|
||||
- Tech stack listings (layer → technology)
|
||||
- Column descriptions (column → meaning)
|
||||
- Environment variable references (name → purpose → default)
|
||||
- Route references (method + path → description → auth requirement)
|
||||
|
||||
Table format:
|
||||
|
||||
```markdown
|
||||
| Column | Description |
|
||||
|---|---|
|
||||
| `field_name` | What it does |
|
||||
```
|
||||
|
||||
- Always use `---` separators (not `:---:` centred alignment) unless centring is specifically warranted.
|
||||
- Keep cell content on a single line. If a value is long, prefer prose above or below the table.
|
||||
- Use inline backticks for literal values inside cells.
|
||||
|
||||
---
|
||||
|
||||
## Code Blocks
|
||||
|
||||
- **Always include a language tag** on fenced code blocks: ` ```bash `, ` ```javascript `, ` ```json `, ` ```python `, ` ```sql `. Bare ` ``` ` is not acceptable.
|
||||
- Shell commands use `bash` — even for single-line commands.
|
||||
- Place code blocks on their own line, with blank lines before and after.
|
||||
- Inside code blocks, do not use markdown formatting (no bold, no italics). Treat them as literal terminal/file content.
|
||||
- Prefer showing the actual command over describing what to do. "Run `node setup.js` from `backend/`" with a code block — not "initialize the database."
|
||||
|
||||
---
|
||||
|
||||
## Callouts and Warnings
|
||||
|
||||
- Use a blockquote (`>`) for callouts, notes, and warnings. Do not use GitHub-flavoured admonition syntax (`> [!NOTE]`), Docusaurus admonitions, or custom HTML.
|
||||
- Keep callouts to one or two sentences. If longer, promote to prose.
|
||||
- Example: `> IVANTI_API_KEY must be set in backend/.env for sync to work.`
|
||||
|
||||
Bold prefixes for emphasis are acceptable inside a blockquote: `> **Warning:** This deletes all audit records older than 90 days.`
|
||||
|
||||
---
|
||||
|
||||
## Feature Documentation Pattern
|
||||
|
||||
When documenting a feature or page, follow this structure:
|
||||
|
||||
1. **One-sentence summary** of what the feature is and who uses it.
|
||||
2. **Capability bullets** — what a user can do, grouped by role if access-controlled.
|
||||
3. **Workflow or interaction details** — how the feature is used in practice (inline editing behaviour, filter semantics, persistence rules).
|
||||
4. **Integration notes** — what external systems it touches, what credentials it needs, what it caches.
|
||||
5. **Edge cases and restrictions** — delete rules, rate limits, role requirements.
|
||||
|
||||
Bold paragraph labels (`**Inline editing:**`, `**CVE Tooltips:**`, `**Filtering:**`) are the preferred pattern for calling out sub-behaviours within a feature section.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting Entries
|
||||
|
||||
Every troubleshooting entry uses the **Symptom → Cause → Fix** triad:
|
||||
|
||||
```markdown
|
||||
### Short description of the problem
|
||||
|
||||
**Symptom:** What the user sees or experiences. Be specific about error messages, console output, and observed behaviour.
|
||||
|
||||
**Cause:** The underlying reason, explained in one or two sentences. Include the technical mechanism (cookie flag, rate limiter, missing migration) — not just "it's broken."
|
||||
|
||||
**Fix:** Either:
|
||||
1. Concrete action with a command or config change, **or**
|
||||
2. Alternative action.
|
||||
```
|
||||
|
||||
- Short entries (fix is one command) may collapse Cause into Fix, but Symptom must always appear explicitly.
|
||||
- Use **Fix:** as the label, not "Solution" or "Resolution."
|
||||
|
||||
---
|
||||
|
||||
## CHANGELOG
|
||||
|
||||
This project does not currently maintain a `CHANGELOG.md`. The doc-updater agent should **not** create one unless explicitly instructed.
|
||||
|
||||
When a change ships, rely instead on:
|
||||
|
||||
- **Git commit messages** as the primary change history. Write them as complete sentences describing user-observable behaviour, not implementation detail. "Add inline editing to CVE reporting table" — not "fix table.jsx."
|
||||
- **README updates** as the user-facing record of what the app does now. The README is the source of truth for current behaviour; git log is the source of truth for when and why it changed.
|
||||
|
||||
If a `CHANGELOG.md` is introduced later, this section should be rewritten to declare the chosen format. Until then, the agent should leave changelog concerns out of scope.
|
||||
|
||||
---
|
||||
|
||||
## Migration Documentation
|
||||
|
||||
When a feature requires a new database migration:
|
||||
|
||||
1. Add the migration filename to the README's **Migrations** section in the order it must be run.
|
||||
2. If the migration is required for an existing deployment (not just fresh installs), add a Troubleshooting entry using the Symptom → Cause → Fix pattern for the error users will see if they skip it.
|
||||
3. Note any data-transforming migrations explicitly — users need to know whether the migration is additive (safe to re-run) or transformative (destructive if re-run).
|
||||
|
||||
---
|
||||
|
||||
## API Reference Documentation
|
||||
|
||||
- Document routes as: `METHOD /path/with/:params`
|
||||
- Group routes by resource or page (CVE routes, Ivanti routes, Audit routes).
|
||||
- For each route, specify: purpose, required group, request body or query params, response shape summary. Keep it to 2–4 lines per route.
|
||||
- Do not duplicate route implementation details. Link to the source file if deeper reference is needed.
|
||||
- When a route enforces group-based authorisation, state the required group explicitly — do not imply it from context.
|
||||
|
||||
---
|
||||
|
||||
## What to Update When a Feature Ships
|
||||
|
||||
A new feature or meaningful change to existing behaviour should touch:
|
||||
|
||||
1. **README.md — Features section:** add or update the relevant `###` subsection, matching the Feature Documentation Pattern above.
|
||||
2. **README.md — Table of Contents:** if a new feature added a new heading, update the TOC to match.
|
||||
3. **README.md — Configuration:** if new env vars were introduced, add them to the Configuration table.
|
||||
4. **README.md — API Reference:** if new routes were added, document them under the appropriate resource group.
|
||||
5. **README.md — Database Schema:** if tables or columns changed, update the schema section.
|
||||
6. **README.md — Migrations:** if a new migration was added, append it to the ordered list.
|
||||
7. **docs/**: if the feature has its own standalone guide (setup guide, integration guide), create or update the relevant file in `docs/`.
|
||||
|
||||
If a change does not alter user-observable behaviour, configuration, data model, or API surface, it does not require doc changes. Internal refactors, test additions, and dependency bumps are exempt unless they change how the app is run or deployed.
|
||||
|
||||
---
|
||||
|
||||
## What NOT to Change
|
||||
|
||||
The doc-updater agent and human contributors alike should **leave alone**:
|
||||
|
||||
- Tone, voice, and spelling conventions of existing prose. Match, do not rewrite.
|
||||
- Section ordering in the README — the current order is deliberate and reader-tested.
|
||||
- Heading wording, unless the underlying feature has genuinely been renamed.
|
||||
- Examples and command snippets that still work, even if they could be "more elegant."
|
||||
- The overall shape of the Troubleshooting section — append new entries, do not reorganise existing ones.
|
||||
|
||||
Documentation churn is a cost. Only change what the code change requires.
|
||||
27
.kiro/steering/product.md
Normal file
27
.kiro/steering/product.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Product Overview
|
||||
|
||||
The STEAM Security Dashboard is a self-hosted vulnerability management tool for the NTS-AEO-STEAM and NTS-AEO-ACCESS-ENG business units. It centralizes CVE tracking, Ivanti host finding triage, AEO compliance posture monitoring, FP/Archer exception workflows, and internal documentation in a single interface.
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
- Searchable CVE list with per-vendor tracking and document storage
|
||||
- NVD API integration for auto-populating CVE metadata
|
||||
- Ivanti/RiskSense integration for syncing open host findings with FP workflow tracking
|
||||
- Reporting page with charts, advanced filtering, inline editing, and CSV/XLSX export
|
||||
- Ivanti Queue for batch-processing FP, Archer, and CARD workflows
|
||||
- AEO Compliance page with weekly xlsx upload, diff preview, per-team metric health cards, and device-level violation tracking
|
||||
- Archer risk acceptance ticket tracking (EXC numbers) linked to CVE/vendor pairs
|
||||
- Knowledge base for internal documentation and policies
|
||||
- Role-based access control (viewer, editor, admin) with full audit trail
|
||||
|
||||
## User Roles
|
||||
|
||||
| Role | Permissions |
|
||||
|------|------------|
|
||||
| viewer | Read-only access to all data |
|
||||
| editor | All viewer permissions plus create/update operations |
|
||||
| admin | All editor permissions plus delete, user management, and audit log access |
|
||||
|
||||
## Teams Tracked
|
||||
|
||||
Only **STEAM** and **ACCESS-ENG** teams are tracked in the compliance module.
|
||||
83
.kiro/steering/structure.md
Normal file
83
.kiro/steering/structure.md
Normal file
@@ -0,0 +1,83 @@
|
||||
# Project Structure & Conventions
|
||||
|
||||
## Directory Layout
|
||||
|
||||
```
|
||||
cve-dashboard/
|
||||
├── backend/ # Express API server
|
||||
│ ├── server.js # Main entry point — app setup, middleware, CVE/document routes inline
|
||||
│ ├── setup.js # One-time DB init + default admin creation
|
||||
│ ├── cve_database.db # SQLite database (gitignored)
|
||||
│ ├── uploads/ # File storage (gitignored)
|
||||
│ ├── routes/ # Express route modules (factory pattern)
|
||||
│ │ ├── auth.js
|
||||
│ │ ├── users.js
|
||||
│ │ ├── auditLog.js
|
||||
│ │ ├── nvdLookup.js
|
||||
│ │ ├── knowledgeBase.js
|
||||
│ │ ├── archerTickets.js
|
||||
│ │ ├── ivantiWorkflows.js
|
||||
│ │ ├── ivantiFindings.js
|
||||
│ │ ├── ivantiTodoQueue.js
|
||||
│ │ └── compliance.js
|
||||
│ ├── middleware/
|
||||
│ │ └── auth.js # requireAuth(db), requireRole(...roles)
|
||||
│ ├── helpers/
|
||||
│ │ └── auditLog.js # logAudit() — fire-and-forget DB insert
|
||||
│ ├── migrations/ # Sequential migration scripts (run manually with node)
|
||||
│ └── scripts/ # Python utilities (compliance parsing, CSV import)
|
||||
│
|
||||
├── frontend/ # React 19 SPA (Create React App)
|
||||
│ └── src/
|
||||
│ ├── App.js # Main dashboard — CVE list, filters, modals, inline styles
|
||||
│ ├── App.css # Global styles and CSS variables
|
||||
│ ├── contexts/
|
||||
│ │ └── AuthContext.js # Auth state provider (login, logout, role helpers)
|
||||
│ └── components/
|
||||
│ ├── LoginForm.js
|
||||
│ ├── NavDrawer.js
|
||||
│ ├── UserMenu.js
|
||||
│ ├── CalendarWidget.js
|
||||
│ ├── UserManagement.js
|
||||
│ ├── AuditLog.js
|
||||
│ ├── NvdSyncModal.js
|
||||
│ ├── KnowledgeBaseModal.js
|
||||
│ ├── KnowledgeBaseViewer.js
|
||||
│ └── pages/ # Full-page views
|
||||
│ ├── ReportingPage.js
|
||||
│ ├── CompliancePage.js
|
||||
│ ├── ComplianceUploadModal.js
|
||||
│ ├── ComplianceDetailPanel.js
|
||||
│ ├── ComplianceChartsPanel.js
|
||||
│ ├── IvantiCountsChart.js
|
||||
│ ├── KnowledgeBasePage.js
|
||||
│ └── ExportsPage.js
|
||||
│
|
||||
├── docs/ # Internal documentation (markdown)
|
||||
├── start-servers.sh # Start both servers in background
|
||||
├── stop-servers.sh # Stop both servers
|
||||
└── DESIGN_SYSTEM.md # UI design system reference (colors, typography, components)
|
||||
```
|
||||
|
||||
## Backend Conventions
|
||||
|
||||
- Route modules export a factory function: `function createXxxRouter(db, ...middleware)` that returns an Express Router.
|
||||
- The `db` (sqlite3 Database instance) is passed via dependency injection from `server.js`.
|
||||
- Auth middleware: `requireAuth(db)` validates session cookie, attaches `req.user`. `requireRole('editor', 'admin')` checks role.
|
||||
- All state-changing actions call `logAudit(db, { userId, username, action, entityType, entityId, details, ipAddress })`.
|
||||
- Input validation is done inline in route handlers with early-return error responses.
|
||||
- SQLite queries use the callback-based `db.run()`, `db.get()`, `db.all()` API.
|
||||
- API routes are prefixed with `/api`. All endpoints except login/logout require a valid session cookie.
|
||||
- CVE and document routes are defined inline in `server.js`; feature routes are in separate modules under `routes/`.
|
||||
|
||||
## Frontend Conventions
|
||||
|
||||
- Single-page app with page-level navigation managed in `App.js` (no React Router).
|
||||
- Auth state managed via React Context (`AuthContext`). Use `useAuth()` hook for login/logout/role checks.
|
||||
- API calls use `fetch()` with `credentials: 'include'` for cookie-based auth.
|
||||
- API base URL from `process.env.REACT_APP_API_BASE`.
|
||||
- Styling uses a mix of inline style objects (defined as constants in component files) and `App.css` global styles.
|
||||
- Dark theme with a "tactical intelligence" aesthetic — see `DESIGN_SYSTEM.md` for color palette, typography, and component specs.
|
||||
- Icons from `lucide-react`. Charts from `recharts`.
|
||||
- Page components live in `components/pages/`. Shared components live in `components/`.
|
||||
- No TypeScript — the project uses plain JavaScript throughout.
|
||||
78
.kiro/steering/tech.md
Normal file
78
.kiro/steering/tech.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# Tech Stack & Build System
|
||||
|
||||
## Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|-------|-----------|
|
||||
| Backend | Node.js 18+, Express 5 |
|
||||
| Database | SQLite3 (file: `backend/cve_database.db`) |
|
||||
| Auth | bcryptjs, cookie-based sessions (httpOnly, 24h expiry) |
|
||||
| File uploads | Multer 2 (10MB limit) |
|
||||
| Frontend | React 19 (Create React App / react-scripts 5) |
|
||||
| UI Icons | lucide-react |
|
||||
| Charts | recharts |
|
||||
| Spreadsheet parsing | xlsx (frontend), pandas + openpyxl (backend Python scripts) |
|
||||
| Markdown rendering | react-markdown |
|
||||
| Diagrams | mermaid |
|
||||
|
||||
## Common Commands
|
||||
|
||||
### Backend
|
||||
```bash
|
||||
cd backend
|
||||
node setup.js # Initialize DB, tables, indexes, default admin user
|
||||
node server.js # Start backend on port 3001
|
||||
```
|
||||
|
||||
### Frontend
|
||||
```bash
|
||||
cd frontend
|
||||
npm install # Install dependencies
|
||||
npm start # Dev server on port 3000
|
||||
npm run build # Production build
|
||||
npm test # Run tests (react-scripts test)
|
||||
```
|
||||
|
||||
### Both servers (from project root)
|
||||
```bash
|
||||
./start-servers.sh # Start backend + frontend in background
|
||||
./stop-servers.sh # Stop all servers
|
||||
```
|
||||
|
||||
### Database Migrations (run from `backend/` in order)
|
||||
```bash
|
||||
node migrations/add_knowledge_base_table.js
|
||||
node migrations/add_archer_tickets_table.js
|
||||
node migrations/add_ivanti_sync_table.js
|
||||
node migrations/add_ivanti_findings_tables.js
|
||||
node migrations/add_ivanti_todo_queue_table.js
|
||||
node migrations/add_card_workflow_type.js
|
||||
node migrations/add_todo_queue_ip_address.js
|
||||
node migrations/add_compliance_tables.js
|
||||
```
|
||||
|
||||
### Python Scripts (from `backend/scripts/`)
|
||||
```bash
|
||||
# Compliance xlsx parsing (called automatically by upload flow)
|
||||
python3 parse_compliance_xlsx.py <file>
|
||||
|
||||
# Bulk notes import
|
||||
python3 import_notes_from_csv.py input.csv --dry-run
|
||||
python3 import_notes_from_csv.py input.csv
|
||||
```
|
||||
|
||||
Python dependencies: `pandas>=2.0.0`, `openpyxl>=3.0.0` (install via apt or venv).
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
- `backend/.env` — PORT, CORS_ORIGINS, SESSION_SECRET, NVD_API_KEY, Ivanti API credentials
|
||||
- `frontend/.env` — REACT_APP_API_BASE, REACT_APP_API_HOST
|
||||
- Both `.env` files are gitignored; see `.env.example` files for templates.
|
||||
- React caches env vars at build/start time — restart the frontend process after changes.
|
||||
|
||||
## Default Ports
|
||||
|
||||
| Service | URL |
|
||||
|---------|-----|
|
||||
| Frontend | http://localhost:3000 |
|
||||
| Backend API | http://localhost:3001 |
|
||||
290
DESIGN_SYSTEM.md
Normal file
290
DESIGN_SYSTEM.md
Normal file
@@ -0,0 +1,290 @@
|
||||
# CVE Intelligence Dashboard - Design System Reference
|
||||
|
||||
## Color Palette
|
||||
|
||||
### Primary Colors
|
||||
```css
|
||||
--intel-darkest: #0F172A /* Slate 900 - Deepest background */
|
||||
--intel-dark: #1E293B /* Slate 800 - Card backgrounds */
|
||||
--intel-medium: #334155 /* Slate 700 - Elevated elements */
|
||||
```
|
||||
|
||||
### Accent & Status Colors
|
||||
```css
|
||||
--intel-accent: #0EA5E9 /* Sky Blue - Primary accent, links, interactive elements */
|
||||
--intel-warning: #F59E0B /* Amber - Warnings, high severity, open tickets */
|
||||
--intel-danger: #EF4444 /* Red - Critical severity, destructive actions */
|
||||
--intel-success: #10B981 /* Emerald - Success states, low severity, confirmations */
|
||||
```
|
||||
|
||||
### Text Colors
|
||||
```css
|
||||
--text-primary: #F8FAFC /* Slate 50 - Primary text */
|
||||
--text-secondary: #E2E8F0 /* Slate 200 - Secondary text */
|
||||
--text-tertiary: #CBD5E1 /* Slate 300 - Labels, metadata */
|
||||
--text-muted: #94A3B8 /* Slate 400 - Placeholders, disabled */
|
||||
```
|
||||
|
||||
### Severity Badge Colors
|
||||
| Severity | Border | Background | Text | Glow Dot |
|
||||
|----------|--------|------------|------|----------|
|
||||
| **Critical** | `#EF4444` | `rgba(239, 68, 68, 0.25)` | `#FCA5A5` | `#EF4444` |
|
||||
| **High** | `#F59E0B` | `rgba(245, 158, 11, 0.25)` | `#FCD34D` | `#F59E0B` |
|
||||
| **Medium** | `#0EA5E9` | `rgba(14, 165, 233, 0.25)` | `#7DD3FC` | `#0EA5E9` |
|
||||
| **Low** | `#10B981` | `rgba(16, 185, 129, 0.25)` | `#6EE7B7` | `#10B981` |
|
||||
|
||||
## Layout Structure
|
||||
|
||||
### Three-Column Grid Layout
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ HEADER & STATS BAR │
|
||||
│ CVE INTEL | [Stats: Total, Entries, Tickets, Critical] │
|
||||
├──────────────┬─────────────────────────┬────────────────────┤
|
||||
│ │ │ │
|
||||
│ LEFT PANEL │ CENTER PANEL │ RIGHT PANEL │
|
||||
│ (3 cols) │ (6 cols) │ (3 cols) │
|
||||
│ │ │ │
|
||||
│ Knowledge │ Quick CVE Lookup │ Calendar │
|
||||
│ Base │ Search & Filters │ Widget │
|
||||
│ - Wiki │ CVE Results List │ │
|
||||
│ - Docs │ - Expandable cards │ Open Tickets │
|
||||
│ - Policies │ - Vendor entries │ - Compact list │
|
||||
│ - Guides │ - Documents │ - Quick stats │
|
||||
│ │ - JIRA tickets │ │
|
||||
│ │ │ │
|
||||
└──────────────┴─────────────────────────┴────────────────────┘
|
||||
```
|
||||
|
||||
### Responsive Breakpoints
|
||||
- **Desktop (lg+)**: 3-column layout (3-6-3 grid)
|
||||
- **Tablet/Mobile**: Stacked single column
|
||||
|
||||
## Component Specifications
|
||||
|
||||
### Stat Cards
|
||||
```css
|
||||
Background: linear-gradient(135deg, rgba(30, 41, 59, 0.95), rgba(51, 65, 85, 0.9))
|
||||
Border: 2px solid [accent-color]
|
||||
Border Radius: 0.5rem
|
||||
Padding: 1rem
|
||||
Top Accent Line: 2px gradient, 0 0 8px glow
|
||||
Shadow: 0 4px 16px rgba(0, 0, 0, 0.5)
|
||||
Hover: translateY(-2px), enhanced shadow
|
||||
```
|
||||
|
||||
### Intel Cards (Main Content)
|
||||
```css
|
||||
Background: linear-gradient(135deg, rgba(30, 41, 59, 0.95), rgba(51, 65, 85, 0.9))
|
||||
Border: 2px solid rgba(14, 165, 233, 0.4)
|
||||
Shadow: 0 8px 24px rgba(0, 0, 0, 0.6), subtle glow
|
||||
Hover: Enhanced border (0.5 opacity), lift effect
|
||||
```
|
||||
|
||||
### Buttons
|
||||
```css
|
||||
/* Primary */
|
||||
Background: linear-gradient(135deg, rgba(14, 165, 233, 0.15), rgba(14, 165, 233, 0.1))
|
||||
Border: 1px solid #0EA5E9
|
||||
Color: #38BDF8
|
||||
Text Shadow: 0 0 6px rgba(14, 165, 233, 0.2)
|
||||
|
||||
/* Hover State */
|
||||
Background: linear-gradient(135deg, rgba(14, 165, 233, 0.25), rgba(14, 165, 233, 0.2))
|
||||
Shadow: 0 0 20px rgba(14, 165, 233, 0.25)
|
||||
Transform: translateY(-1px)
|
||||
Ripple Effect: 300px radial on click
|
||||
```
|
||||
|
||||
### Input Fields
|
||||
```css
|
||||
Background: rgba(30, 41, 59, 0.6)
|
||||
Border: 1px solid rgba(14, 165, 233, 0.25)
|
||||
Font: 'JetBrains Mono', monospace
|
||||
Focus: border #0EA5E9, ring 2px rgba(14, 165, 233, 0.15)
|
||||
```
|
||||
|
||||
### Badges (Status/Severity)
|
||||
```css
|
||||
Display: inline-flex
|
||||
Align Items: center
|
||||
Gap: 0.5rem
|
||||
Border: 2px solid [severity-color]
|
||||
Border Radius: 0.375rem
|
||||
Padding: 0.375rem 0.875rem
|
||||
Font: 'JetBrains Mono', 0.75rem, 700, uppercase
|
||||
Letter Spacing: 0.5px
|
||||
Glow Dot: 8px circle with pulse animation
|
||||
```
|
||||
|
||||
## Interactions & Animations
|
||||
|
||||
### Hover Effects
|
||||
- **Cards**: `translateY(-2px)`, enhanced border, subtle glow
|
||||
- **Buttons**: Radial ripple expand (300px), slight lift
|
||||
- **List Items**: Border color shift, background lighten
|
||||
|
||||
### Animations
|
||||
```css
|
||||
/* Pulse Glow (for dots) */
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 1; transform: scale(1); }
|
||||
50% { opacity: 0.7; transform: scale(1.2); }
|
||||
}
|
||||
|
||||
/* Scan Line */
|
||||
@keyframes scan {
|
||||
0%, 100% { transform: translateY(-100%); opacity: 0; }
|
||||
50% { transform: translateY(2000%); opacity: 0.5; }
|
||||
}
|
||||
|
||||
/* Spin (loading) */
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
```
|
||||
|
||||
### Transitions
|
||||
```css
|
||||
Standard: all 0.3s cubic-bezier(0.4, 0, 0.2, 1)
|
||||
Fast: all 0.2s ease
|
||||
Ripple: width/height 0.5s
|
||||
```
|
||||
|
||||
## Typography
|
||||
|
||||
### Font Families
|
||||
```css
|
||||
Primary (UI): 'Outfit', system-ui, sans-serif
|
||||
Monospace (Data/Code): 'JetBrains Mono', monospace
|
||||
```
|
||||
|
||||
### Font Sizes & Weights
|
||||
```css
|
||||
/* Headings */
|
||||
h1: 2.5rem (40px), 700, monospace
|
||||
h2: 1.125rem (18px), 600, uppercase, tracking-wider
|
||||
h3: 1.125rem (18px), 600
|
||||
|
||||
/* Body */
|
||||
Body: 0.875rem (14px), 400
|
||||
Small: 0.75rem (12px), 400
|
||||
Labels: 0.75rem (12px), 500, uppercase, tracking-wider
|
||||
```
|
||||
|
||||
### Text Shadows (Headings)
|
||||
```css
|
||||
Accent Headings: 0 0 16px rgba(14, 165, 233, 0.3), 0 0 32px rgba(14, 165, 233, 0.15)
|
||||
Badge Text: 0 0 8px rgba([color], 0.5)
|
||||
```
|
||||
|
||||
## Visual Effects
|
||||
|
||||
### Shadows
|
||||
```css
|
||||
/* Card Elevations */
|
||||
Level 1: 0 2px 6px rgba(0, 0, 0, 0.3)
|
||||
Level 2: 0 4px 12px rgba(0, 0, 0, 0.4)
|
||||
Level 3: 0 8px 24px rgba(0, 0, 0, 0.6)
|
||||
|
||||
/* Glows */
|
||||
Subtle: 0 0 12px rgba([color], 0.12)
|
||||
Medium: 0 0 20px rgba([color], 0.15)
|
||||
Strong: 0 0 28px rgba([color], 0.25)
|
||||
|
||||
/* Inset Highlights */
|
||||
Top: inset 0 1px 0 rgba(14, 165, 233, 0.15)
|
||||
Recessed: inset 0 2px 4px rgba(0, 0, 0, 0.3)
|
||||
```
|
||||
|
||||
### Border Styles
|
||||
```css
|
||||
/* Standard Cards */
|
||||
Border: 1.5-2px solid rgba(14, 165, 233, 0.3-0.4)
|
||||
|
||||
/* Accent Panels */
|
||||
Left Border: 3px solid [accent-color]
|
||||
|
||||
/* Vendor/Nested Cards */
|
||||
Border: 1px solid rgba(14, 165, 233, 0.25)
|
||||
```
|
||||
|
||||
### Gradients
|
||||
```css
|
||||
/* Backgrounds */
|
||||
Card: linear-gradient(135deg, rgba(30, 41, 59, 0.95), rgba(51, 65, 85, 0.9))
|
||||
Nested: linear-gradient(135deg, rgba(15, 23, 42, 0.95), rgba(30, 41, 59, 0.9))
|
||||
|
||||
/* Accent Lines */
|
||||
Top Bar: linear-gradient(90deg, transparent, [color], transparent)
|
||||
|
||||
/* Grid Background */
|
||||
linear-gradient(rgba(14, 165, 233, 0.025) 1px, transparent 1px)
|
||||
Size: 20px × 20px
|
||||
```
|
||||
|
||||
## Specific Component Patterns
|
||||
|
||||
### Wiki/Knowledge Base Entry
|
||||
```css
|
||||
Background: linear-gradient(135deg, rgba(30, 41, 59, 0.85), rgba(51, 65, 85, 0.75))
|
||||
Border: 1px solid rgba(16, 185, 129, 0.25)
|
||||
Padding: 0.75rem
|
||||
Cursor: pointer
|
||||
Hover: border-color shift to rgba(16, 185, 129, 0.4)
|
||||
```
|
||||
|
||||
### Calendar Widget
|
||||
```css
|
||||
Day Cells:
|
||||
- Text: white, font-mono, 0.75rem
|
||||
- Hover: bg rgba(14, 165, 233, 0.2)
|
||||
- Current Day: bg rgba(14, 165, 233, 0.3), border 1px #0EA5E9
|
||||
- Other Month: text rgba(148, 163, 184, 0.5)
|
||||
```
|
||||
|
||||
### Ticket Cards (Compact)
|
||||
```css
|
||||
Background: linear-gradient(135deg, rgba(30, 41, 59, 0.85), rgba(51, 65, 85, 0.75))
|
||||
Border: 1px solid rgba(245, 158, 11, 0.25)
|
||||
Padding: 0.5rem
|
||||
Status Badge: Reduced size (0.65rem, 0.25rem padding)
|
||||
Glow Dot: 6px diameter
|
||||
```
|
||||
|
||||
### CVE Expandable Cards
|
||||
```css
|
||||
Header: Clickable, cursor pointer
|
||||
Collapsed: Show summary (severity, vendor count, doc count)
|
||||
Expanded: Full description, metadata, vendor entries
|
||||
Chevron: Rotate -90deg (collapsed) to 0deg (expanded)
|
||||
Vendor Cards: Nested with reduced opacity borders
|
||||
```
|
||||
|
||||
## Accessibility
|
||||
|
||||
### Contrast Ratios
|
||||
- Primary text on dark: 18.5:1 (AAA)
|
||||
- Secondary text on dark: 12.3:1 (AAA)
|
||||
- Accent colors: All meet WCAG AA minimum
|
||||
|
||||
### Interactive States
|
||||
- Focus rings: 2px solid accent color
|
||||
- Hover: Visible border/background changes
|
||||
- Active: Transform feedback
|
||||
|
||||
### Typography
|
||||
- Minimum size: 12px (0.75rem)
|
||||
- Line height: 1.5 for body text
|
||||
- Letter spacing: Generous for uppercase labels
|
||||
|
||||
## Design Principles
|
||||
|
||||
1. **Professional Sophistication**: Modern enterprise feel, not arcade
|
||||
2. **Tactical Intelligence**: Purpose-driven, information-dense
|
||||
3. **Refined Depth**: Layers and elevation without harsh neon
|
||||
4. **Purposeful Color**: Accent colors convey meaning (status, severity)
|
||||
5. **Smooth Interactions**: Polished micro-interactions and transitions
|
||||
6. **Monospace Data**: Technical data uses JetBrains Mono for clarity
|
||||
7. **Generous Spacing**: Breathing room prevents overwhelming density
|
||||
|
||||
7
Ivanti_config_template.ini
Normal file
7
Ivanti_config_template.ini
Normal file
@@ -0,0 +1,7 @@
|
||||
[platform]
|
||||
url = https://platform4.risksense.com
|
||||
api_ver = /api/v1
|
||||
# PROD 1550 | UAT 1551
|
||||
client_id = <pick 1550 or 1551>
|
||||
[secrets]
|
||||
api_key = <your API key here>
|
||||
222
TEST_PLAN_AUDIT_LOG.md
Normal file
222
TEST_PLAN_AUDIT_LOG.md
Normal file
@@ -0,0 +1,222 @@
|
||||
# Audit Logging Feature - User Acceptance Test Plan
|
||||
|
||||
## Test Environment Setup
|
||||
|
||||
**Prerequisites:**
|
||||
- Fresh database via `node backend/setup.js`, OR existing database migrated via `node backend/migrate-audit-log.js`
|
||||
- Backend running on port 3001
|
||||
- Frontend running on port 3000
|
||||
- Three test accounts created:
|
||||
- `admin` / `admin123` (role: admin)
|
||||
- `editor1` (role: editor)
|
||||
- `viewer1` (role: viewer)
|
||||
|
||||
**Verify setup:** Run `sqlite3 backend/cve_database.db ".tables"` and confirm `audit_logs` is listed.
|
||||
|
||||
---
|
||||
|
||||
## 1. Database & Schema
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 1.1 | Fresh install creates table | Run `node setup.js` on a new DB. Query `SELECT sql FROM sqlite_master WHERE name='audit_logs'` | Table exists with columns: id, user_id, username, action, entity_type, entity_id, details, ip_address, created_at | |
|
||||
| 1.2 | Indexes created | Query `SELECT name FROM sqlite_master WHERE type='index' AND name LIKE 'idx_audit%'` | Four indexes: idx_audit_user_id, idx_audit_action, idx_audit_entity_type, idx_audit_created_at | |
|
||||
| 1.3 | Migration is idempotent | Run `node migrate-audit-log.js` twice on the same DB | Second run prints "already exists, nothing to do". No errors. Backup file created each run. | |
|
||||
| 1.4 | Migration backs up DB | Run `node migrate-audit-log.js` | Backup file `cve_database_backup_<timestamp>.db` created in backend directory | |
|
||||
| 1.5 | Setup summary updated | Run `node setup.js` | Console output lists `audit_logs` in the tables line | |
|
||||
|
||||
---
|
||||
|
||||
## 2. Authentication Audit Logging
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 2.1 | Successful login logged | Log in as `admin`. Query `SELECT * FROM audit_logs WHERE action='login' ORDER BY id DESC LIMIT 1` | Row with user_id=admin's ID, username='admin', action='login', entity_type='auth', details contains `{"role":"admin"}`, ip_address populated | |
|
||||
| 2.2 | Failed login - wrong password | Attempt login with `admin` / `wrongpass`. Query audit_logs. | Row with action='login_failed', username='admin', details contains `{"reason":"invalid_password"}` | |
|
||||
| 2.3 | Failed login - unknown user | Attempt login with `nonexistent` / `anypass`. Query audit_logs. | Row with action='login_failed', user_id=NULL, username='nonexistent', details contains `{"reason":"user_not_found"}` | |
|
||||
| 2.4 | Failed login - disabled account | Disable a user account via admin, then attempt login as that user. Query audit_logs. | Row with action='login_failed', details contains `{"reason":"account_disabled"}` | |
|
||||
| 2.5 | Logout logged | Log in as admin, then log out. Query audit_logs. | Row with action='logout', entity_type='auth', username='admin' | |
|
||||
| 2.6 | Login does not block on audit error | Verify login succeeds even if audit_logs table had issues (non-critical path) | Login response returns normally regardless of audit insert result | |
|
||||
|
||||
---
|
||||
|
||||
## 3. CVE Operation Audit Logging
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 3.1 | CVE create logged | Log in as editor or admin. Add a new CVE (e.g., CVE-2025-TEST-1 / Microsoft / Critical). Query audit_logs. | Row with action='cve_create', entity_type='cve', entity_id='CVE-2025-TEST-1', details contains `{"vendor":"Microsoft","severity":"Critical"}` | |
|
||||
| 3.2 | CVE status update logged | Update a CVE's status to "Addressed" via the API (`PATCH /api/cves/CVE-2025-TEST-1/status`). Query audit_logs. | Row with action='cve_update_status', entity_id='CVE-2025-TEST-1', details contains `{"status":"Addressed"}` | |
|
||||
| 3.3 | CVE status update bug fix | Update a CVE's status. Verify the CVE record in the `cves` table. | Status is correctly updated. No SQL error (the old `vendor` reference bug is fixed). | |
|
||||
| 3.4 | Audit captures acting user | Log in as `editor1`, create a CVE. Query audit_logs. | username='editor1' on the cve_create row | |
|
||||
|
||||
---
|
||||
|
||||
## 4. Document Operation Audit Logging
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 4.1 | Document upload logged | Upload a document to a CVE via the UI. Query audit_logs. | Row with action='document_upload', entity_type='document', entity_id=CVE ID, details contains vendor, type, and filename | |
|
||||
| 4.2 | Document delete logged | Delete a document (admin only) via the UI. Query audit_logs. | Row with action='document_delete', entity_type='document', entity_id=document DB ID, details contains file_path | |
|
||||
| 4.3 | Upload captures file metadata | Upload a file named `advisory.pdf` of type `advisory` for vendor `Cisco`. Query audit_logs. | details = `{"vendor":"Cisco","type":"advisory","filename":"advisory.pdf"}` | |
|
||||
|
||||
---
|
||||
|
||||
## 5. User Management Audit Logging
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 5.1 | User create logged | As admin, create a new user `testuser` with role `viewer`. Query audit_logs. | Row with action='user_create', entity_type='user', entity_id=new user's ID, details contains `{"created_username":"testuser","role":"viewer"}` | |
|
||||
| 5.2 | User update logged | As admin, change `testuser`'s role to `editor`. Query audit_logs. | Row with action='user_update', entity_id=testuser's ID, details contains `{"role":"editor"}` | |
|
||||
| 5.3 | User update - password change | As admin, change `testuser`'s password. Query audit_logs. | details contains `{"password_changed":true}` (password itself is NOT logged) | |
|
||||
| 5.4 | User update - multiple fields | Change username and role at the same time. Query audit_logs. | details contains both changed fields | |
|
||||
| 5.5 | User delete logged | As admin, delete `testuser`. Query audit_logs. | Row with action='user_delete', details contains `{"deleted_username":"testuser"}` | |
|
||||
| 5.6 | User deactivation logged | As admin, set a user's is_active to false. Query audit_logs. | Row with action='user_update', details contains `{"is_active":false}` | |
|
||||
| 5.7 | Self-delete prevented, no log | As admin, attempt to delete your own account. Query audit_logs. | 400 error returned. NO audit_log entry created for the attempt. | |
|
||||
|
||||
---
|
||||
|
||||
## 6. API Access Control
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 6.1 | Admin can query audit logs | Log in as admin. `GET /api/audit-logs`. | 200 response with logs array and pagination object | |
|
||||
| 6.2 | Editor denied audit logs | Log in as editor. `GET /api/audit-logs`. | 403 response with `{"error":"Insufficient permissions"}` | |
|
||||
| 6.3 | Viewer denied audit logs | Log in as viewer. `GET /api/audit-logs`. | 403 response | |
|
||||
| 6.4 | Unauthenticated denied | Without a session cookie, `GET /api/audit-logs`. | 401 response | |
|
||||
| 6.5 | Admin can get actions list | `GET /api/audit-logs/actions` as admin. | 200 response with array of distinct action strings | |
|
||||
| 6.6 | Non-admin denied actions list | `GET /api/audit-logs/actions` as editor. | 403 response | |
|
||||
|
||||
---
|
||||
|
||||
## 7. API Filtering & Pagination
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 7.1 | Default pagination | `GET /api/audit-logs` (no params). | Returns up to 25 entries, page=1, correct total count and totalPages | |
|
||||
| 7.2 | Custom page size | `GET /api/audit-logs?limit=5`. | Returns exactly 5 entries (if >= 5 exist). Pagination reflects limit=5. | |
|
||||
| 7.3 | Page size capped at 100 | `GET /api/audit-logs?limit=999`. | Returns at most 100 entries per page | |
|
||||
| 7.4 | Navigate to page 2 | `GET /api/audit-logs?page=2&limit=5`. | Returns entries 6-10 (offset=5). Entries differ from page 1. | |
|
||||
| 7.5 | Filter by username | `GET /api/audit-logs?user=admin`. | Only entries where username contains "admin" | |
|
||||
| 7.6 | Partial username match | `GET /api/audit-logs?user=adm`. | Matches "admin" (LIKE search) | |
|
||||
| 7.7 | Filter by action | `GET /api/audit-logs?action=login`. | Only entries with action='login' (exact match) | |
|
||||
| 7.8 | Filter by entity type | `GET /api/audit-logs?entityType=auth`. | Only auth-related entries | |
|
||||
| 7.9 | Filter by date range | `GET /api/audit-logs?startDate=2025-01-01&endDate=2025-12-31`. | Only entries within the date range (inclusive) | |
|
||||
| 7.10 | Combined filters | `GET /api/audit-logs?user=admin&action=login&entityType=auth`. | Only entries matching ALL filters simultaneously | |
|
||||
| 7.11 | Empty result set | `GET /api/audit-logs?user=nonexistentuser`. | `{"logs":[],"pagination":{"page":1,"limit":25,"total":0,"totalPages":0}}` | |
|
||||
| 7.12 | Ordering | Query audit logs without filters. | Entries ordered by created_at DESC (newest first) | |
|
||||
|
||||
---
|
||||
|
||||
## 8. Frontend - Audit Log Menu Access
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 8.1 | Admin sees Audit Log menu item | Log in as admin. Click user avatar to open dropdown menu. | "Audit Log" option visible with clock icon, positioned between "Manage Users" and "Sign Out" | |
|
||||
| 8.2 | Editor does NOT see Audit Log | Log in as editor. Click user avatar. | No "Audit Log" or "Manage Users" options visible | |
|
||||
| 8.3 | Viewer does NOT see Audit Log | Log in as viewer. Click user avatar. | No "Audit Log" or "Manage Users" options visible | |
|
||||
| 8.4 | Clicking Audit Log opens modal | As admin, click "Audit Log" in the menu. | Modal overlay appears with audit log table. Menu dropdown closes. | |
|
||||
| 8.5 | Menu closes on outside click | Open the user menu, then click outside the dropdown. | Dropdown closes | |
|
||||
|
||||
---
|
||||
|
||||
## 9. Frontend - Audit Log Modal
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 9.1 | Modal displays header | Open the Audit Log modal. | Title "Audit Log", subtitle "Track all user actions across the system", X close button visible | |
|
||||
| 9.2 | Close button works | Click the X button on the modal. | Modal closes, returns to dashboard | |
|
||||
| 9.3 | Loading state shown | Open the modal (observe briefly). | Spinner with "Loading audit logs..." appears before data loads | |
|
||||
| 9.4 | Table columns correct | Open modal with data present. | Six columns visible: Time, User, Action, Entity, Details, IP Address | |
|
||||
| 9.5 | Time formatting | Check the Time column. | Dates display in local format (e.g., "1/29/2026, 3:45:00 PM"), not raw ISO strings | |
|
||||
| 9.6 | Action badges color-coded | View entries with different action types. | login=green, logout=gray, login_failed=red, cve_create=blue, cve_update_status=yellow, document_upload=purple, document_delete=red, user_create=blue, user_update=yellow, user_delete=red | |
|
||||
| 9.7 | Entity column format | View entries with entity_type and entity_id. | Shows "cve CVE-2025-TEST-1" or "auth" (no ID for auth entries) | |
|
||||
| 9.8 | Details column formatting | View an entry with JSON details. | Displays "key: value, key: value" format, not raw JSON | |
|
||||
| 9.9 | Details truncation | View entry with long details. | Text truncated with ellipsis. Full text visible on hover (title attribute). | |
|
||||
| 9.10 | IP address display | View entries. | IP addresses shown in monospace font. Null IPs show "-" | |
|
||||
| 9.11 | Empty state | Apply filters that return no results. | "No audit log entries found." message displayed | |
|
||||
| 9.12 | Error state | (Simulate: stop backend while modal is open, then apply filters.) | Error icon with error message displayed | |
|
||||
|
||||
---
|
||||
|
||||
## 10. Frontend - Filters
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 10.1 | Username filter | Type "admin" in username field, click Apply Filters. | Only entries with "admin" in username shown | |
|
||||
| 10.2 | Action dropdown populated | Click the Action dropdown. | Lists all distinct actions present in the database (from `/api/audit-logs/actions`) | |
|
||||
| 10.3 | Action filter | Select "login" from Action dropdown, click Apply. | Only login entries shown | |
|
||||
| 10.4 | Entity type dropdown | Click the Entity Type dropdown. | Lists: auth, cve, document, user | |
|
||||
| 10.5 | Entity type filter | Select "cve", click Apply. | Only CVE-related entries shown | |
|
||||
| 10.6 | Date range filter | Set start date to today, set end date to today, click Apply. | Only entries from today shown | |
|
||||
| 10.7 | Combined filters | Set username="admin", action="login", click Apply. | Only admin login entries shown | |
|
||||
| 10.8 | Reset button | Set multiple filters, click Reset. | All filter fields cleared. (Note: table does not auto-refresh until Apply is clicked again.) | |
|
||||
| 10.9 | Apply after reset | Click Reset, then click Apply Filters. | Full unfiltered results shown | |
|
||||
| 10.10 | Filter resets to page 1 | Navigate to page 2, then apply a filter. | Results start from page 1 | |
|
||||
|
||||
---
|
||||
|
||||
## 11. Frontend - Pagination
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 11.1 | Pagination info displayed | Open modal with >25 entries. | Shows "Showing 1 - 25 of N entries" and "Page 1 of X" | |
|
||||
| 11.2 | Next page button | Click the right chevron. | Page advances. Entry range updates. "Page 2 of X" shown. | |
|
||||
| 11.3 | Previous page button | Navigate to page 2, then click left chevron. | Returns to page 1 | |
|
||||
| 11.4 | First page - prev disabled | On page 1, check left chevron. | Button is disabled (grayed out, not clickable) | |
|
||||
| 11.5 | Last page - next disabled | Navigate to the last page. | Right chevron is disabled | |
|
||||
| 11.6 | Pagination hidden for few entries | Open modal with <= 25 total entries. | No pagination controls shown (totalPages <= 1) | |
|
||||
| 11.7 | Entry count accuracy | Compare "Showing X - Y of Z" with actual table rows. | Row count matches Y - X + 1. Total Z matches database count. | |
|
||||
|
||||
---
|
||||
|
||||
## 12. Fire-and-Forget Behavior
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 12.1 | Audit failure does not break login | (Requires code-level test or corrupting audit_logs table temporarily.) Rename audit_logs table, attempt login. | Login succeeds. Console shows "Audit log error:" message. | |
|
||||
| 12.2 | Audit failure does not break CVE create | With corrupted audit table, create a CVE. | CVE created successfully. Error logged to console only. | |
|
||||
| 12.3 | Response not delayed by audit | Create a CVE and observe response time. | Response returns immediately; audit insert is non-blocking. | |
|
||||
|
||||
---
|
||||
|
||||
## 13. Data Integrity
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 13.1 | Audit survives user deletion | Create user, perform actions, delete user. Query audit_logs for that username. | Audit entries remain with the username preserved (denormalized). No foreign key cascade. | |
|
||||
| 13.2 | Details stored as valid JSON | Query `SELECT details FROM audit_logs WHERE details IS NOT NULL LIMIT 5`. Parse each. | All non-null details values are valid JSON strings | |
|
||||
| 13.3 | IP address captured | Query entries created via browser. | ip_address field contains the client IP (e.g., `::1` for localhost or `127.0.0.1`) | |
|
||||
| 13.4 | Timestamps auto-populated | Query entries without explicitly setting created_at. | All rows have a created_at value, not NULL | |
|
||||
| 13.5 | Null entity_id for auth actions | Query `SELECT * FROM audit_logs WHERE entity_type='auth'`. | entity_id is NULL for login/logout/login_failed entries | |
|
||||
|
||||
---
|
||||
|
||||
## 14. End-to-End Workflow
|
||||
|
||||
| # | Test Case | Steps | Expected Result | Pass/Fail |
|
||||
|---|-----------|-------|-----------------|-----------|
|
||||
| 14.1 | Full user lifecycle | 1. Admin logs in 2. Creates user "testuser2" 3. testuser2 logs in 4. testuser2 creates a CVE 5. Admin updates testuser2's role 6. Admin deletes testuser2 7. Open Audit Log and review | All 6 actions visible in the audit log in reverse chronological order. Each entry has correct user, action, entity, and details. | |
|
||||
| 14.2 | Filter down to one user's actions | Perform test 14.1, then filter by username="testuser2". | Only testuser2's own actions shown (login, cve_create). Admin actions on testuser2 show admin as the actor. | |
|
||||
| 14.3 | Security audit trail | Attempt 3 failed logins with wrong password, then succeed. Open Audit Log, filter action="login_failed". | All 3 failed attempts visible with timestamps and IP addresses. Useful for detecting brute force. | |
|
||||
|
||||
---
|
||||
|
||||
## Test Summary
|
||||
|
||||
| Section | Tests | Description |
|
||||
|---------|-------|-------------|
|
||||
| 1. Database & Schema | 5 | Table creation, indexes, migration idempotency |
|
||||
| 2. Auth Logging | 6 | Login success/failure variants, logout |
|
||||
| 3. CVE Logging | 4 | Create, status update, bug fix verification |
|
||||
| 4. Document Logging | 3 | Upload, delete, metadata capture |
|
||||
| 5. User Mgmt Logging | 7 | Create, update, delete, edge cases |
|
||||
| 6. API Access Control | 6 | Admin-only enforcement on all endpoints |
|
||||
| 7. API Filtering | 12 | Pagination, filters, combined queries |
|
||||
| 8. Menu Access | 5 | Role-based UI visibility |
|
||||
| 9. Modal Display | 12 | Table rendering, formatting, states |
|
||||
| 10. Frontend Filters | 10 | Filter UI interaction and behavior |
|
||||
| 11. Pagination UI | 7 | Navigation, boundary conditions |
|
||||
| 12. Fire-and-Forget | 3 | Non-blocking audit behavior |
|
||||
| 13. Data Integrity | 5 | Denormalization, JSON, timestamps |
|
||||
| 14. End-to-End | 3 | Full workflow validation |
|
||||
| **Total** | **88** | |
|
||||
838
architecture.excalidraw
Normal file
838
architecture.excalidraw
Normal file
@@ -0,0 +1,838 @@
|
||||
{
|
||||
"type": "excalidraw",
|
||||
"version": 2,
|
||||
"source": "https://excalidraw.com",
|
||||
"elements": [
|
||||
{
|
||||
"id": "title-text",
|
||||
"type": "text",
|
||||
"x": 400,
|
||||
"y": 30,
|
||||
"width": 400,
|
||||
"height": 45,
|
||||
"angle": 0,
|
||||
"strokeColor": "#1971c2",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 1,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "CVE Dashboard Architecture",
|
||||
"fontSize": 36,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "center",
|
||||
"verticalAlign": "top",
|
||||
"baseline": 32,
|
||||
"containerId": null,
|
||||
"originalText": "CVE Dashboard Architecture"
|
||||
},
|
||||
{
|
||||
"id": "users-box",
|
||||
"type": "ellipse",
|
||||
"x": 500,
|
||||
"y": 120,
|
||||
"width": 200,
|
||||
"height": 80,
|
||||
"angle": 0,
|
||||
"strokeColor": "#1971c2",
|
||||
"backgroundColor": "#e7f5ff",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 2,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": [
|
||||
{
|
||||
"type": "text",
|
||||
"id": "users-text"
|
||||
},
|
||||
{
|
||||
"id": "arrow-users-frontend",
|
||||
"type": "arrow"
|
||||
}
|
||||
],
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false
|
||||
},
|
||||
{
|
||||
"id": "users-text",
|
||||
"type": "text",
|
||||
"x": 505,
|
||||
"y": 145,
|
||||
"width": 190,
|
||||
"height": 30,
|
||||
"angle": 0,
|
||||
"strokeColor": "#1971c2",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 3,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "Users\n(Admin/Editor/Viewer)",
|
||||
"fontSize": 16,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "center",
|
||||
"verticalAlign": "middle",
|
||||
"baseline": 23,
|
||||
"containerId": "users-box",
|
||||
"originalText": "Users\n(Admin/Editor/Viewer)"
|
||||
},
|
||||
{
|
||||
"id": "frontend-box",
|
||||
"type": "rectangle",
|
||||
"x": 450,
|
||||
"y": 250,
|
||||
"width": 300,
|
||||
"height": 120,
|
||||
"angle": 0,
|
||||
"strokeColor": "#1971c2",
|
||||
"backgroundColor": "#a5d8ff",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 4,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": [
|
||||
{
|
||||
"type": "text",
|
||||
"id": "frontend-text"
|
||||
},
|
||||
{
|
||||
"id": "arrow-users-frontend",
|
||||
"type": "arrow"
|
||||
},
|
||||
{
|
||||
"id": "arrow-frontend-backend",
|
||||
"type": "arrow"
|
||||
}
|
||||
],
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false
|
||||
},
|
||||
{
|
||||
"id": "frontend-text",
|
||||
"type": "text",
|
||||
"x": 455,
|
||||
"y": 255,
|
||||
"width": 290,
|
||||
"height": 110,
|
||||
"angle": 0,
|
||||
"strokeColor": "#1971c2",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 5,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "Frontend (React)\nPort: 3000\n\n• React 18 + Tailwind CSS\n• Auth Context\n• Components: Login, UserMenu,\n UserManagement, CVE Views",
|
||||
"fontSize": 14,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "left",
|
||||
"verticalAlign": "middle",
|
||||
"baseline": 103,
|
||||
"containerId": "frontend-box",
|
||||
"originalText": "Frontend (React)\nPort: 3000\n\n• React 18 + Tailwind CSS\n• Auth Context\n• Components: Login, UserMenu,\n UserManagement, CVE Views"
|
||||
},
|
||||
{
|
||||
"id": "backend-box",
|
||||
"type": "rectangle",
|
||||
"x": 400,
|
||||
"y": 420,
|
||||
"width": 400,
|
||||
"height": 180,
|
||||
"angle": 0,
|
||||
"strokeColor": "#7048e8",
|
||||
"backgroundColor": "#d0bfff",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 6,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": [
|
||||
{
|
||||
"type": "text",
|
||||
"id": "backend-text"
|
||||
},
|
||||
{
|
||||
"id": "arrow-frontend-backend",
|
||||
"type": "arrow"
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-db",
|
||||
"type": "arrow"
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-storage",
|
||||
"type": "arrow"
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-nvd",
|
||||
"type": "arrow"
|
||||
}
|
||||
],
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false
|
||||
},
|
||||
{
|
||||
"id": "backend-text",
|
||||
"type": "text",
|
||||
"x": 405,
|
||||
"y": 425,
|
||||
"width": 390,
|
||||
"height": 170,
|
||||
"angle": 0,
|
||||
"strokeColor": "#7048e8",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 7,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "Backend API (Express.js)\nPort: 3001\n\nRoutes:\n• /api/auth - Authentication (login/logout)\n• /api/users - User management\n• /api/cves - CVE operations\n• /api/documents - Document upload/download\n• /api/audit-log - Audit logging\n• /api/nvd-lookup - NVD integration",
|
||||
"fontSize": 14,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "left",
|
||||
"verticalAlign": "middle",
|
||||
"baseline": 163,
|
||||
"containerId": "backend-box",
|
||||
"originalText": "Backend API (Express.js)\nPort: 3001\n\nRoutes:\n• /api/auth - Authentication (login/logout)\n• /api/users - User management\n• /api/cves - CVE operations\n• /api/documents - Document upload/download\n• /api/audit-log - Audit logging\n• /api/nvd-lookup - NVD integration"
|
||||
},
|
||||
{
|
||||
"id": "db-box",
|
||||
"type": "rectangle",
|
||||
"x": 200,
|
||||
"y": 680,
|
||||
"width": 280,
|
||||
"height": 140,
|
||||
"angle": 0,
|
||||
"strokeColor": "#2f9e44",
|
||||
"backgroundColor": "#b2f2bb",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 8,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": [
|
||||
{
|
||||
"type": "text",
|
||||
"id": "db-text"
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-db",
|
||||
"type": "arrow"
|
||||
}
|
||||
],
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false
|
||||
},
|
||||
{
|
||||
"id": "db-text",
|
||||
"type": "text",
|
||||
"x": 205,
|
||||
"y": 685,
|
||||
"width": 270,
|
||||
"height": 130,
|
||||
"angle": 0,
|
||||
"strokeColor": "#2f9e44",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 9,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "SQLite Database\ncve_database.db\n\nTables:\n• cves\n• documents\n• users\n• sessions\n• required_documents\n• audit_log",
|
||||
"fontSize": 14,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "left",
|
||||
"verticalAlign": "middle",
|
||||
"baseline": 123,
|
||||
"containerId": "db-box",
|
||||
"originalText": "SQLite Database\ncve_database.db\n\nTables:\n• cves\n• documents\n• users\n• sessions\n• required_documents\n• audit_log"
|
||||
},
|
||||
{
|
||||
"id": "storage-box",
|
||||
"type": "rectangle",
|
||||
"x": 550,
|
||||
"y": 680,
|
||||
"width": 280,
|
||||
"height": 140,
|
||||
"angle": 0,
|
||||
"strokeColor": "#f08c00",
|
||||
"backgroundColor": "#ffec99",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 10,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": [
|
||||
{
|
||||
"type": "text",
|
||||
"id": "storage-text"
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-storage",
|
||||
"type": "arrow"
|
||||
}
|
||||
],
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false
|
||||
},
|
||||
{
|
||||
"id": "storage-text",
|
||||
"type": "text",
|
||||
"x": 555,
|
||||
"y": 685,
|
||||
"width": 270,
|
||||
"height": 130,
|
||||
"angle": 0,
|
||||
"strokeColor": "#f08c00",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 11,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "File Storage\nuploads/\n\nStructure:\nCVE-ID/\n Vendor/\n documents.pdf\n\n• Multi-vendor support\n• Timestamped filenames",
|
||||
"fontSize": 14,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "left",
|
||||
"verticalAlign": "middle",
|
||||
"baseline": 123,
|
||||
"containerId": "storage-box",
|
||||
"originalText": "File Storage\nuploads/\n\nStructure:\nCVE-ID/\n Vendor/\n documents.pdf\n\n• Multi-vendor support\n• Timestamped filenames"
|
||||
},
|
||||
{
|
||||
"id": "nvd-box",
|
||||
"type": "rectangle",
|
||||
"x": 900,
|
||||
"y": 420,
|
||||
"width": 220,
|
||||
"height": 100,
|
||||
"angle": 0,
|
||||
"strokeColor": "#e03131",
|
||||
"backgroundColor": "#ffc9c9",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 12,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": [
|
||||
{
|
||||
"type": "text",
|
||||
"id": "nvd-text"
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-nvd",
|
||||
"type": "arrow"
|
||||
}
|
||||
],
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false
|
||||
},
|
||||
{
|
||||
"id": "nvd-text",
|
||||
"type": "text",
|
||||
"x": 905,
|
||||
"y": 425,
|
||||
"width": 210,
|
||||
"height": 90,
|
||||
"angle": 0,
|
||||
"strokeColor": "#e03131",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 13,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "NVD API\n(External)\n\nNational Vulnerability\nDatabase\n\nAutomatic CVE lookup",
|
||||
"fontSize": 14,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "center",
|
||||
"verticalAlign": "middle",
|
||||
"baseline": 83,
|
||||
"containerId": "nvd-box",
|
||||
"originalText": "NVD API\n(External)\n\nNational Vulnerability\nDatabase\n\nAutomatic CVE lookup"
|
||||
},
|
||||
{
|
||||
"id": "arrow-users-frontend",
|
||||
"type": "arrow",
|
||||
"x": 600,
|
||||
"y": 200,
|
||||
"width": 0,
|
||||
"height": 50,
|
||||
"angle": 0,
|
||||
"strokeColor": "#1971c2",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "round",
|
||||
"seed": 14,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"points": [
|
||||
[0, 0],
|
||||
[0, 50]
|
||||
],
|
||||
"lastCommittedPoint": null,
|
||||
"startBinding": {
|
||||
"elementId": "users-box",
|
||||
"focus": 0,
|
||||
"gap": 1
|
||||
},
|
||||
"endBinding": {
|
||||
"elementId": "frontend-box",
|
||||
"focus": 0,
|
||||
"gap": 1
|
||||
},
|
||||
"startArrowhead": null,
|
||||
"endArrowhead": "arrow",
|
||||
"elbowed": false,
|
||||
"roundness": null
|
||||
},
|
||||
{
|
||||
"id": "arrow-frontend-backend",
|
||||
"type": "arrow",
|
||||
"x": 600,
|
||||
"y": 370,
|
||||
"width": 0,
|
||||
"height": 50,
|
||||
"angle": 0,
|
||||
"strokeColor": "#7048e8",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "round",
|
||||
"seed": 15,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"points": [
|
||||
[0, 0],
|
||||
[0, 50]
|
||||
],
|
||||
"lastCommittedPoint": null,
|
||||
"startBinding": {
|
||||
"elementId": "frontend-box",
|
||||
"focus": 0,
|
||||
"gap": 1
|
||||
},
|
||||
"endBinding": {
|
||||
"elementId": "backend-box",
|
||||
"focus": 0,
|
||||
"gap": 1
|
||||
},
|
||||
"startArrowhead": null,
|
||||
"endArrowhead": "arrow",
|
||||
"elbowed": false,
|
||||
"roundness": null
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-db",
|
||||
"type": "arrow",
|
||||
"x": 500,
|
||||
"y": 600,
|
||||
"width": -140,
|
||||
"height": 80,
|
||||
"angle": 0,
|
||||
"strokeColor": "#2f9e44",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "round",
|
||||
"seed": 16,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"points": [
|
||||
[0, 0],
|
||||
[-140, 0],
|
||||
[-140, 80]
|
||||
],
|
||||
"lastCommittedPoint": null,
|
||||
"startBinding": {
|
||||
"elementId": "backend-box",
|
||||
"focus": 0,
|
||||
"gap": 1
|
||||
},
|
||||
"endBinding": {
|
||||
"elementId": "db-box",
|
||||
"focus": 0,
|
||||
"gap": 1
|
||||
},
|
||||
"startArrowhead": null,
|
||||
"endArrowhead": "arrow",
|
||||
"elbowed": true,
|
||||
"roundness": null
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-storage",
|
||||
"type": "arrow",
|
||||
"x": 700,
|
||||
"y": 600,
|
||||
"width": 0,
|
||||
"height": 80,
|
||||
"angle": 0,
|
||||
"strokeColor": "#f08c00",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "round",
|
||||
"seed": 17,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"points": [
|
||||
[0, 0],
|
||||
[0, 80]
|
||||
],
|
||||
"lastCommittedPoint": null,
|
||||
"startBinding": {
|
||||
"elementId": "backend-box",
|
||||
"focus": 0.5,
|
||||
"gap": 1
|
||||
},
|
||||
"endBinding": {
|
||||
"elementId": "storage-box",
|
||||
"focus": 0.5,
|
||||
"gap": 1
|
||||
},
|
||||
"startArrowhead": null,
|
||||
"endArrowhead": "arrow",
|
||||
"elbowed": false,
|
||||
"roundness": null
|
||||
},
|
||||
{
|
||||
"id": "arrow-backend-nvd",
|
||||
"type": "arrow",
|
||||
"x": 800,
|
||||
"y": 480,
|
||||
"width": 100,
|
||||
"height": 0,
|
||||
"angle": 0,
|
||||
"strokeColor": "#e03131",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "round",
|
||||
"seed": 18,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"points": [
|
||||
[0, 0],
|
||||
[100, 0]
|
||||
],
|
||||
"lastCommittedPoint": null,
|
||||
"startBinding": {
|
||||
"elementId": "backend-box",
|
||||
"focus": 0,
|
||||
"gap": 1
|
||||
},
|
||||
"endBinding": {
|
||||
"elementId": "nvd-box",
|
||||
"focus": 0,
|
||||
"gap": 1
|
||||
},
|
||||
"startArrowhead": null,
|
||||
"endArrowhead": "arrow",
|
||||
"elbowed": false,
|
||||
"roundness": null
|
||||
},
|
||||
{
|
||||
"id": "label-http",
|
||||
"type": "text",
|
||||
"x": 610,
|
||||
"y": 390,
|
||||
"width": 100,
|
||||
"height": 20,
|
||||
"angle": 0,
|
||||
"strokeColor": "#7048e8",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 19,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "HTTP/REST API",
|
||||
"fontSize": 12,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "left",
|
||||
"verticalAlign": "top",
|
||||
"baseline": 17,
|
||||
"containerId": null,
|
||||
"originalText": "HTTP/REST API"
|
||||
},
|
||||
{
|
||||
"id": "label-https",
|
||||
"type": "text",
|
||||
"x": 820,
|
||||
"y": 460,
|
||||
"width": 60,
|
||||
"height": 20,
|
||||
"angle": 0,
|
||||
"strokeColor": "#e03131",
|
||||
"backgroundColor": "transparent",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 2,
|
||||
"strokeStyle": "solid",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 20,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "HTTPS",
|
||||
"fontSize": 12,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "left",
|
||||
"verticalAlign": "top",
|
||||
"baseline": 17,
|
||||
"containerId": null,
|
||||
"originalText": "HTTPS"
|
||||
},
|
||||
{
|
||||
"id": "auth-note",
|
||||
"type": "text",
|
||||
"x": 100,
|
||||
"y": 250,
|
||||
"width": 280,
|
||||
"height": 80,
|
||||
"angle": 0,
|
||||
"strokeColor": "#495057",
|
||||
"backgroundColor": "#f8f9fa",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 1,
|
||||
"strokeStyle": "dashed",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 21,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "Authentication:\n• Session-based auth\n• bcrypt password hashing\n• Role-based access control\n (Admin/Editor/Viewer)",
|
||||
"fontSize": 12,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "left",
|
||||
"verticalAlign": "top",
|
||||
"baseline": 73,
|
||||
"containerId": null,
|
||||
"originalText": "Authentication:\n• Session-based auth\n• bcrypt password hashing\n• Role-based access control\n (Admin/Editor/Viewer)"
|
||||
},
|
||||
{
|
||||
"id": "features-note",
|
||||
"type": "text",
|
||||
"x": 900,
|
||||
"y": 580,
|
||||
"width": 280,
|
||||
"height": 120,
|
||||
"angle": 0,
|
||||
"strokeColor": "#495057",
|
||||
"backgroundColor": "#f8f9fa",
|
||||
"fillStyle": "solid",
|
||||
"strokeWidth": 1,
|
||||
"strokeStyle": "dashed",
|
||||
"roughness": 0,
|
||||
"opacity": 100,
|
||||
"groupIds": [],
|
||||
"strokeSharpness": "sharp",
|
||||
"seed": 22,
|
||||
"version": 1,
|
||||
"versionNonce": 1,
|
||||
"isDeleted": false,
|
||||
"boundElements": null,
|
||||
"updated": 1,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
"text": "Key Features:\n• Quick CVE status check\n• Multi-vendor support\n• Document management\n• Compliance tracking\n• Search & filter\n• Audit logging",
|
||||
"fontSize": 12,
|
||||
"fontFamily": 1,
|
||||
"textAlign": "left",
|
||||
"verticalAlign": "top",
|
||||
"baseline": 113,
|
||||
"containerId": null,
|
||||
"originalText": "Key Features:\n• Quick CVE status check\n• Multi-vendor support\n• Document management\n• Compliance tracking\n• Search & filter\n• Audit logging"
|
||||
}
|
||||
],
|
||||
"appState": {
|
||||
"gridSize": null,
|
||||
"viewBackgroundColor": "#ffffff"
|
||||
},
|
||||
"files": {}
|
||||
}
|
||||
@@ -2,3 +2,42 @@
|
||||
PORT=3001
|
||||
API_HOST=localhost
|
||||
CORS_ORIGINS=http://localhost:3000
|
||||
|
||||
# NVD API Key (optional - increases rate limit from 5 to 50 requests per 30s)
|
||||
# Request one at https://nvd.nist.gov/developers/request-an-api-key
|
||||
NVD_API_KEY=
|
||||
|
||||
# Ivanti / RiskSense API (platform4.risksense.com)
|
||||
# API key from your profile settings — does not expire like session cookies
|
||||
IVANTI_API_KEY=
|
||||
IVANTI_CLIENT_ID=1550
|
||||
IVANTI_FIRST_NAME=
|
||||
IVANTI_LAST_NAME=
|
||||
# Set to true if behind Charter's SSL inspection proxy (replicates Python verify=False)
|
||||
IVANTI_SKIP_TLS=false
|
||||
|
||||
# Atlas InfoSec API (atlas-infosec.caas.charterlab.com)
|
||||
# Service account credentials for Basic Auth — used to sync and manage action plans
|
||||
ATLAS_API_URL=
|
||||
ATLAS_API_USER=
|
||||
ATLAS_API_PASS=
|
||||
# Set to true if behind Charter's SSL inspection proxy (disables TLS cert verification)
|
||||
ATLAS_SKIP_TLS=false
|
||||
|
||||
# Jira Data Center REST API
|
||||
# VPN or Charter Network connection required for all Jira instances.
|
||||
# Service accounts use Basic Auth (JIRA_API_USER + JIRA_API_TOKEN).
|
||||
# PATs require ATLSUP approval and naming convention: Function - Team - ATLSUP-XXXXX
|
||||
# Rate limits: 1440 requests/day, burst of 60/minute.
|
||||
JIRA_BASE_URL=
|
||||
JIRA_AUTH_METHOD=basic
|
||||
# Basic Auth — service account credentials
|
||||
JIRA_API_USER=
|
||||
JIRA_API_TOKEN=
|
||||
# PAT Auth — set JIRA_AUTH_METHOD=pat to use
|
||||
JIRA_PAT=
|
||||
# Default project key and issue type for creating issues from the dashboard
|
||||
JIRA_PROJECT_KEY=
|
||||
JIRA_ISSUE_TYPE=Task
|
||||
# Set to true if behind Charter's SSL inspection proxy
|
||||
JIRA_SKIP_TLS=false
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user