Audit permissions

From microsoft/power-platform-skills · View interactive version

Audit permissions is an AI agent skill from the GitHub repository microsoft/power-platform-skills. Audits existing table permissions on a Power Pages site by analyzing them against site code and Dataverse metadata, then GRADES the configuration with deterministic 1–5 scores across 3 security/usability/correctness categories (9 dimensions). Detection is anchored by a recurring-issue catalog so fin

How to use this skill

Skill file

Plugin check: Run node "${PLUGIN_ROOT}/scripts/check-version.js" — if it outputs a message, show it to the user before proceeding.

Audit Permissions

Audit existing table permissions on a Power Pages code site. Analyze permissions against the site code and Dataverse metadata, then generate a visual HTML report with deterministic 1–5 category scores, an advisory verdict, findings, reasoning, and suggested fixes.

The skill has two parts:

  1. Audit checks (evidence + remediation) — the per-table A–K checklist that compares every permission against real code usage and Dataverse metadata. It is the primary issue detector: it catches concrete, code-grounded problems (missing CRUD, append/appendto, $expand gaps, broken parent chains, over-provisioned grants) and emits each as a major/minor issue with concrete evidence and a fix.
  2. Scoring (reproducible result) — a 3-category rubric (9 dimensions) anchored by a recurring-issue catalog of fixed detection triggers + severities, followed by a single consolidation into root causes and one batched root-cause attribution pass for major issues. It turns the findings into pure-formula 1–5 category scores so two runs on the same configuration yield the same numbers.

Golden rule of scoring: you only ever find and label issues (major / minor). You do NOT invent the numeric score. The 1–5 numbers come from a fixed formula applied to the issue counts (see Appendix A). Same issue set ⇒ same score.

Site type routing

Before reading or executing the workflow below, perform the existing SPA project lookup first.

existing file-search patterns.

```bash

node "${PLUGIN_ROOT}/scripts/lib/detect-project-context.js"

```

${PLUGIN_ROOT}/skills/audit-permissions/references/non-spa-site-workflow.md.

Do not execute the SPA workflow below.

Workflow

  1. Verify Site Deployment — Check that .powerpages-site folder and table permissions exist
  2. Gather Configuration — Read web roles, table permissions, site code, run the shared schema validator, and build the deterministic preflight cross-reference
  3. Analyze & Discover — Query Dataverse for relationships and lookup columns using deterministic scripts
  4. Run Audit Checks — Compare permissions against code usage and best practices (A–K checklist)
  5. Score the Configuration — Detect/label issues by the 3 categories using the recurring-issue catalog, consolidate to distinct root causes (major/minor), compute the 1–5 category scores and the verdict
  6. Root-cause attribution — In a single batched pass, label every major issue as permissions-only or caused by an upstream artifact, with a one-sentence justification shown in the report
  7. Generate Report — Create the HTML report (score overview + findings + inventory) and validate it
  8. Present Findings & Track — Summarize, record skill usage, and ask the user if they want to fix issues

Important: Do NOT ask the user questions during analysis. Autonomously gather all data, then present findings.

Audit completion telemetry

At the very start of Step 1, before site verification, initialize local run state:

node "${PLUGIN_ROOT}/scripts/emit-audit-permissions-telemetry.js" --action start

Parse the JSON stdout and retain its auditRunId as <AUDIT_RUN_ID> for this invocation. The command does not emit a telemetry event; the existing generic skill invocation event is the start signal. The local run state provides the opaque random ID and start time needed for completion telemetry. Never derive the ID from, or replace it with, a site, environment, tenant, user, path, or report value.

Telemetry is best-effort and must never block the audit. If the initialization command fails or returns no auditRunId, continue the audit without completion telemetry. Do not invent an id and do not search local state for the latest run.

On every controlled terminal failure after a run id was returned, close the run before stopping:

node "${PLUGIN_ROOT}/scripts/emit-audit-permissions-telemetry.js" \
  --action complete \
  --runId "<AUDIT_RUN_ID>" \
  --outcome failure \
  --failureStage "<FAILURE_STAGE>"

Use exactly one of these fixed failure stages:

Do not pass error messages, paths, table names, finding content, or other user/site data to the telemetry script. A telemetry completion failure does not change the audit outcome and must not trigger a second completion attempt.

Task Tracking

At the start of Step 1, create all tasks upfront using TaskCreate. Mark each task in_progress when starting and completed when done.

| Task subject | activeForm | Description |

|-------------|------------|-------------|

| Verify site deployment | Verifying site deployment | Check .powerpages-site folder and table permissions exist |

| Gather configuration | Gathering configuration | Read web roles, table permissions, site code; run validator; build preflight |

| Discover relationships | Discovering relationships | Query Dataverse for lookup columns and relationships |

| Run audit checks | Running audit checks | Create per-table tasks and run checklist (A–K) for each table, then cross-validate |

| Score configuration | Scoring configuration | Detect/label by the 3 categories via the recurring-issue catalog, consolidate to root causes, compute 1–5 scores |

| Root-cause attribution | Attributing root causes | Label every major issue permissions-only or upstream-caused in a single pass |

| Generate report | Generating report | Create and validate the HTML report and display it in browser |

| Present findings | Presenting findings | Summarize results, record usage, and offer to fix issues |

Note: The "Run audit checks" phase creates additional per-table tasks dynamically in Step 4.2. These per-table tasks track the systematic A–K checklist for each table independently.


Step 1: Verify Site Deployment

Use Glob to find:

If no .powerpages-site folder exists, stop and tell the user to deploy first using /deploy-site.

If no table permissions exist, note this as a critical finding (the site may have no data access configured) and continue the audit — there may still be code references that need permissions.

Before stopping because .powerpages-site is absent, close completion telemetry with failureStage: site_verification as described above.


Step 2: Gather Configuration

Single-pass performance contract

Gather all local evidence in one bounded pass before making judgments:

  1. Read web roles, table permissions, site settings, and .datamodel-manifest.json in grouped operations.
  2. Scan source files once for API operations, entity sets, selects, filters, lookups, expands, uploads, routes, imports, and feature/auth gates. Prefer one grouped search plus targeted reads of only the matching regions; never read an entire source tree file-by-file.
  3. Locate the permission plan once. Extract all authorization-relevant statements in one operation into planClaims; do not reopen or re-extract the plan later.
  4. Freeze these facts in audit-evidence.json. Steps 4–6 consume only this ledger plus any gated Dataverse results.

Do not rescan source code or the plan to gain confidence. A second read is allowed only when a specific ledger field is missing and the exact file/region needed is known. Record the added evidence once, then continue. Never perform multiple searches for differently worded versions of the same plan claim.

2.1 Read Web Roles

Read all files matching **/.powerpages-site/web-roles/*.yml. Keys may carry a publisher prefix — try mspp_<key>, then adx_<key>, then the bare <key> (first found wins). Extract id, name, anonymoususersrole, authenticatedusersrole from each. If YAML fails to parse or its root isn't an object, record a parse error (feeds preflight IS).

2.2 Read Table Permissions

Read all files matching **/.powerpages-site/table-permissions/*.tablepermission.yml. Using the same prefix rule, for each permission extract:

Record a parse error on failure (feeds preflight IS).

2.3 Analyze Site Code

In the single source pass, search the site source code for:

Also check for .datamodel-manifest.json in the project root for the authoritative table list. It has { environmentUrl?, tables: [{ logicalName, displayName, status?, columns: [{ logicalName, type }] }] }. If missing or tables isn't an array, treat the data model as absent.

Additionally scan Web API artifacts (used by the root-cause attribution in Step 6 — best-effort):

Also scan authentication/registration site settings in .powerpages-site/site-settings/ regardless of filename. Parse name + value for settings under Authentication/Registration/, including Enabled, OpenRegistrationEnabled, ExternalLoginEnabled, and InvitationEnabled. Also parse each external provider's Authentication/<Type>/<Provider>/RegistrationEnabled; a configured provider (any settings under Authentication/<Type>/<Provider>/) without that setting counts as true, the server default. Compare names case-insensitively and treat a value as enabled only when its trimmed value is case-insensitively "true". Record missing settings as unknown, not false.

Build an audience reachability profile before judging permissions:

Build a map of: which tables are referenced in code, which CRUD operations are performed on each, which lookup relationships are used, and which related tables are fetched via $expand (these need read permissions too).

Also build a capability matrix before judging missing access. One row per authorization-relevant capability:

persona | route/component | reachability | table | operation | current grant | plan claim | evidence

Classify reachability mechanically:

A UI condition based on the signed-in user's own data (for example an isAccountAdmin field or a role flag on their profile record) never makes a capability disabled — it identifies the persona that uses it. Plan or comment wording such as "deferred", "future phase" or "not yet supported" never makes a routed capability disabled or ambiguous.

Use this evidence precedence everywhere in the audit: reachable implementation > explicit runtime gate/build exclusion > implementation plan > comments/names. A plan cannot make a routed, callable feature hypothetical merely by calling its persona "back-office." Conversely, dead, unregistered, explicitly disabled, or server-gated code does not establish a required portal permission. If reachability is ambiguous and conflicts with the plan, emit at most one minor internal-consistency issue for the conflict; do not presume a broken flow.

After the source pass, do not reopen routes, pages, services, or the permission plan during scoring. Reachability and plan claims are frozen ledger facts, not questions to reconsider in Step 5.

2.4 Run Shared Schema Validator

Run the shared validator against the existing site:

node "${PLUGIN_ROOT}/scripts/validate-permissions-schema.js" --projectRoot "<PROJECT_ROOT>"

Parse the JSON output and carry the findings into the audit as major/minor issues. Map:

These findings should be included in the final report even if the later code/Dataverse analysis also finds additional issues. Exception: drop the validator's "no associated web roles" warning for a Parent-scope child permission whose parent chain is valid (see check B).

If the validator reports wildcard field access in a Webapi/<table>/fields setting, add this finding as a major security-posture issue (one per affected setting):

After Step 3.1 determines the environment URL, rerun the shared validator with live relationship verification only when the Step 3 discovery gate is open. Merge any additional findings:

node "${PLUGIN_ROOT}/scripts/validate-permissions-schema.js" --projectRoot "<PROJECT_ROOT>" --validate-dataverse-relationships --envUrl "<envUrl>"

Use this Dataverse-backed relationship validation only for local runs that need relationship evidence. Do not require it in CI or other offline contexts, and do not run it for Global-only/read-only designs with no relationship-dependent reachable flow.

2.5 Deterministic preflight cross-reference (grader ground truth)

Purely mechanical cross-checks over the parsed YAML + data model + Web API artifacts. Emit ALL that apply. Number IDs per prefix in encounter order (IS1, IS2, DM1, …). These are ground truth: carry them into the right dimension's issue list in Step 5 and never drop or downgrade them.

| Condition | id prefix | dimension | severity |

|---|---|---|---|

| Web-role YAML parse error | IS | internal-consistency | major |

| Table-permission YAML parse error | IS | internal-consistency | major |

| Permission references a web-role GUID not defined in any role | IS | internal-consistency | major |

| Web role has a blank id | IS | internal-consistency | major |

| Permission has a blank entitylogicalname | DM | data-model-alignment | major |

| Permission grants no privileges (all 6 CRUD bits false) | TC | table-coverage | major |

| Permission has no scope (scope < 0) | SC | scope-correctness | major |

| Permission scope code unrecognized (Unknown(code)) | SC | scope-correctness | minor |

| Permission grants write/create/delete to an Anonymous role | AH | anonymous-access-hygiene | major |

| Permission targets a table not in the data model (only when a valid data-model manifest exists) | DM | data-model-alignment | major |

| Web API site-setting YAML parse error | IS | internal-consistency | major |

| -enabled entity set with no matching -fields whitelist | IS | internal-consistency | major |

| -fields whitelist with no matching -enabled setting | IS | internal-consistency | major |

| Type file declaring 1–6 properties absent from the data model (only when a valid data-model manifest exists) | DM | data-model-alignment | minor |


2.6 Freeze the Evidence Ledger

<OUTPUT_DIR> is <PROJECT_ROOT>/docs/ when working in a website (a project root with powerpages.config.json); otherwise it is the system temp directory. The temporary files and the final report all go there.

Before running judgment-based checks, write a temporary <OUTPUT_DIR>/audit-evidence.json containing the normalized facts gathered so far: roles, permissions, data-model tables/columns, service operations, route/component reachability, capability matrix, lookup/expand usage, client-side row filters, implementation-plan claims, authentication reachability, and preflight issues. Sort tables, permissions, routes, and capabilities by stable identifiers.

Steps 4–6 MUST reason from this ledger instead of rescanning and selectively rediscovering evidence. If live Dataverse discovery adds facts in Step 3, append those facts and rewrite the ledger once before Step 4. Do not change a reachability classification during scoring unless new evidence is added to the ledger. Delete audit-evidence.json after the final HTML report passes validation.


Step 3: Analyze & Discover (Dataverse API)

Use deterministic Node.js scripts for all Dataverse API calls. These scripts handle auth token acquisition, HTTP requests, and JSON parsing consistently.

Dataverse discovery gate

Before calling pac env who or any Dataverse query script, compute needsLiveDiscovery. It is true only when at least one reachable capability has one of these unresolved dependencies:

It is false when none of those dependencies apply — for example, Global-only/read-only flows, explicit Administrator-only CRUD unused by reachable site code, and cases fully resolved by the manifest and local source. When false, skip all of Step 3, record liveDiscovery: "not-needed" in the evidence ledger, and continue to Step 4. When true, first confirm the active Dataverse environment URL matches the manifest environment URL; if it does not, skip live queries and record the mismatch instead of querying the wrong environment.

3.1 Get Environment URL

pac env who

Extract the Environment URL (e.g., https://org12345.crm.dynamics.com) and use it as <envUrl> in subsequent script calls.

3.2 Query Lookup Columns

For each table that has permissions with create or write enabled, use the lookup query script:

node "${PLUGIN_ROOT}/skills/audit-permissions/scripts/query-table-lookups.js" --envUrl "<envUrl>" --table "<table_logical_name>"

The script returns a JSON array of { logicalName, targets } for each lookup column. Capture this output for the maps described below.

After querying all tables with create or write permissions, build two maps from the combined results:

  1. Source map (table → lookup columns): For each queried table, record which lookup columns it has and their targets. Used in Section H2 to check appendto on the source table.
  2. Reverse target map (target table → list of source tables): For each target table found in any lookup's targets array, record which source table(s) reference it. Used in Section H to check append on the target table.

Example: querying order_item returns [{ logicalName: "cr4fc_orderid", targets: ["cr4fc_order"] }]

Both maps are used in Sections H and H2:

3.3 Query Relationships

For tables with parent-scope permissions, verify the relationship names using the relationship query script:

node "${PLUGIN_ROOT}/skills/audit-permissions/scripts/query-table-relationships.js" --envUrl "<envUrl>" --table "<parent_table>"

The script returns a JSON array of { schemaName, referencedEntity, referencingEntity, referencingAttribute }. Use schemaName to validate the parentrelationship value in parent-scope permissions.

Error Handling

If any script exits with code 1, skip the API-dependent checks and note which checks were skipped in the report. Do NOT stop the entire audit for auth errors. Use the data model manifest and code analysis as fallback.


Step 4: Run Audit Checks

Use per-table task tracking to systematically run every audit check. These code- and Dataverse-grounded checks are the primary issue detectors — they catch concrete problems (missing CRUD, append/appendto, $expand gaps, broken parent chains, over-provisioned grants) that rubric judgment alone would miss, which is what makes the issue set richer and the score more faithful. Each failed check emits one provisional candidate (title, responsible table, evidence, and a suggested fix); Step 5 assigns its final major/minor severity and dimension. A check that passes produces no candidate. Where a check says to search the service code, look the fact up in the evidence ledger (Step 2.6); search the source only when the ledger lacks it.

4.1 Build Audit Inventory

First, build a combined list of all tables to audit from two sources:

  1. Tables referenced in code (from Step 2.3) — these may or may not have permissions
  2. Tables with existing permissions (from Step 2.2) — these may or may not be referenced in code

The union of these two sets is the complete audit scope. Each table will be audited from both directions: "does the code need a permission that doesn't exist?" and "does the permission match what the code actually does?"

4.2 Create Per-Table Audit Tasks

For each table in the audit inventory, create a task:

TaskCreate:
  subject: "Audit <table_logical_name>"
  activeForm: "Auditing <table_display_name> permissions"
  description: "Run all audit checks for <table_logical_name>"

Also create a summary task:

TaskCreate:
  subject: "Compile audit findings"
  activeForm: "Compiling audit findings"
  description: "Combine all per-table findings into the final report"

Use TaskList at any point to review progress and see which tables still need auditing.

4.3 Per-Table Audit Checklist

For each table, mark its task in_progress and run through the following checks in order. For every issue, note the specific evidence (file path, permission name, code pattern) that supports it. Skip checks that don't apply to this table.

Do not finalize severity or dimension in Step 4. Each check below carries a provisional audit tier (critical, warning, or info) and emits a factual candidate as { sourceId, auditTier, title, table, reasoning, fix, evidence, reachability? }. A check that passes yields no candidate. Step 5 is the only place that assigns the final major|minor severity and canonical dimension, using fixed catalog rules before generic policy. This prevents whichever audit path runs first from locking in a different score.

A. Permission Existence

Does this table have a table permission?

B. Web Role Association

Does the permission have web role(s) assigned?

C. Scope Appropriateness

Is the scope the least-privileged option that fits?

D. Read Permission

Is read correctly set?

E. Create Permission

Is create correctly set?

F. Write Permission

Is write correctly set?

G. Delete Permission

Is delete correctly set?

H. Append (target table check)

Does this table need append: true? Append is required on the target table — the table that other records link TO via lookup columns.

H2. AppendTo (source table check)

Does this table need appendto: true? AppendTo is required on the source table — the table that has lookup columns linking TO other records.

I. Parent Chain Integrity

If the permission has Parent scope (756150003):

J. $expand Related Table Coverage

Is this table fetched via $expand on another table's query?

K. Record Findings & Complete

After all checks, mark the table's task as completed via TaskUpdate.

4.4 Cross-Table Validation

After all per-table audits are complete, run these cross-table checks:

  1. Append/AppendTo consistency: Using the source map and reverse target map from Step 3.2, verify: (a) every source table (with lookups and create/write) has appendto: true, (b) every target table in the reverse map has append: true, (c) no table has appendto: true without lookup columns in the source map, (d) no table has append: true without being in the reverse target map
  2. $expand coverage: For every $expand usage, verify the expanded table has read: true
  3. Parent chain completeness: For every Parent scope permission, verify the parent permission exists and is valid
  4. Web role consistency: If two related tables (e.g., parent and child) are accessed by the same feature, verify they share the same web role assignment

Use TaskList to review all completed audits, then mark the "Compile audit findings" task as in_progress and proceed to Step 5.


Step 5: Score the Configuration

This is the scoring overlay. You already have the evidence: the audit issues (Step 4) and the deterministic preflight issues (Step 2.5). Now turn them into a category-organized issue set and a reproducible 1–5 score. The audit checks supply most of the detected issues; the recurring-issue catalog below plus the grader severity policy (Appendix C) finalize major/minor; the formula (Appendix A) decides the number. Detection and scoring are organized by CATEGORY (each category owns 3 dimensions — Appendix A / Appendix B).

5.1 Detect & label issues by category (catalog-anchored)

Assess the 3 categories; within each, reason across its 3 dimensions together. Populate each issue from three sources:

  1. Preflight issues (Step 2.5) — keep each with its fixed id, dimension, and severity verbatim.
  2. Audit candidates (Step 4, plus the Step 1 no-permissions observation) — these are factual observations, not final labels. Match each candidate against the recurring catalog first. Only unmatched candidates use the generic Appendix C policy. Step 5 assigns every final severity and dimension exactly once.
  3. Recurring-issue catalog + rubric judgment — run the catalog below as a CHECKLIST, then add anything the A–K checks didn't already cover (e.g., an entirely read-only management site → an intent-coverage failure).

RECURRING ISSUE CATALOG — DETECTION + SEVERITY (the primary lever for run-to-run consistency). Test EACH pattern against the artifacts; whenever a pattern's TRIGGER holds, raise exactly ONE issue for it in the stated dimension with the FIXED severity — on every run, no matter how obvious or minor it seems. Match on the described SHAPE, not on specific table/role names (names in parentheses are illustrations). Patterns are evaluated PER affected table-group and are NOT mutually exclusive: if one table hits a MAJOR pattern and a different table hits a similar MINOR pattern (e.g. C2 on a PII table AND C14 minor on a draft-content table), raise BOTH as separate issues — the ordering only resolves severity WITHIN one table-group, it never suppresses a finding on a different table.

ADMINISTRATORS EXCEPTION (respect strongly). By design, a site should not create table permissions for the Administrators web role — admin authoring normally happens outside the portal (the model-driven app or Dataverse directly), so explicit Administrators CRUD permissions are unnecessary and add security noise. The Administrators web role does not bypass table permissions for portal data access. Therefore:

NOVEL ISSUES (not covered by C1–C18): still detect them — do NOT restrict yourself to the catalog. Assign severity by the Appendix C security-first policy. A novel issue is NOT automatically minor: if it exposes data to the wrong audience, over-scopes access, or breaks a required flow, it is major.

Number LLM-derived issue ids per canonical dimension prefix (IC, PC, SC, RC, TC, AH, DM, IS, SP). Within each dimension, continue after the highest preflight id already used for that prefix (or start at 1 when there is none), so generated ids never collide with fixed preflight ids. The issue id prefix MUST match the issue's final dimension after consolidation. Record each issue as {id, dimension, severity, title, reasoning, fix} plus the evidence that supports it — the shape of a report finding (Step 7.2). Do not assign a per-dimension 1–5 score — scoring happens at the category level after consolidation.

5.2 Consolidate to distinct root causes (major/minor)

Consolidate the full pooled issue list into distinct root causes, then classify each into exactly ONE category by dominant impact. The number of issues after this step equals the number of root causes.

The consolidated issues are what feed scoring and all later phases. Re-bucket each under its (possibly reassigned) dimension. This single consolidated major/minor list is the one issue set for everything downstream — it becomes the report's FINDINGS_DATA (Step 7.2), the Overview's Major/Minor counts, and the input to the score. One issue set, one tally, so more issues ⇒ lower score.

5.3 Compute scores (pure formula)

Apply Appendix A exactly: one 1–5 score per category from its pooled issues (no overall score), the verdict from the major count, and issue counts { major, minor, total } over all consolidated issues.

5.4 Verdict (prose)

Write a 2–3 sentence grader verdict: the top thing the config gets right, the top thing it gets wrong, and the verdict. State the verdict verbatim — "Safe to go" when there are zero major issues, "Needs revision" when there is at least one major issue. Minor issues never change it. Do NOT tell the user whether to deploy, release, or ship — the verdict summarises the findings; the decision is theirs. Prose only. Use it as the report's SUMMARY (Step 7.2).

If the data-model manifest is missing (SCORECARD_DATA is null), skip the verdict: write a 2–3 sentence summary that says this is a partial audit, and use neither verdict phrase.


Step 6: Root-cause Attribution (batched)

Analyze all MAJOR issues in a SINGLE batched pass (after consolidation; skip minors). The site evidence is shared, so classify every major issue together in one reasoning step. For each, decide whether it is purely a permissions-design fault or is caused, wholly or partly, by an upstream artifact. Be conservative — default to permissions unless upstream evidence is clear (false upstream attribution is worse than missing one).

Root-cause values:

For each major issue decide rootCause and write explanation; they become the finding's rootCause and rootCauseReason in Step 7.2.

explanation is shown to the user next to the major issue, so write one plain-language sentence that justifies the label: for permissions, say why the permission configuration alone is at fault; otherwise, name the specific upstream file or setting and what it forces.


Step 7: Generate Report

7.1 Determine Output Location

This folder is the <OUTPUT_DIR> defined in Step 2.6.

7.2 Prepare Data

Do NOT generate HTML manually or read/modify the template yourself. Use the render-audit-report.js script which mechanically reads the template and replaces placeholder tokens with your data.

Write a temporary JSON data file (e.g., <OUTPUT_DIR>/audit-data.json) with these keys:

{
  "SITE_NAME": "The site name (from powerpages.config.json or folder name)",
  "AUDIT_DESC": "Security audit of table permissions for Contoso Portal",
  "SUMMARY": "2-3 sentence summary of the audit results",
  "FINDINGS_DATA": [/* array of finding objects */],
  "INVENTORY_DATA": [/* array of current permission objects */],
  "SCORECARD_DATA": {/* grader overlay — see below; use null if scoring was skipped */}
}

SITE_NAME, AUDIT_DESC, SUMMARY, FINDINGS_DATA, INVENTORY_DATA are the required keys the render script validates. SCORECARD_DATA is an extra key the enhanced template consumes — always include it (object or null) so no placeholder is left unreplaced. In SCORECARD_DATA.reportPaths, list the absolute path to the HTML report — the Overview tab renders it so the user can open the report.

FINDINGS_DATA format — this is the single consolidated major/minor issue list from Step 5.2 (one entry per issue; it is exactly what the score is computed from). Use the canonical issue id from Step 5 (e.g. AH1). For major issues, copy rootCause and explanation from that issue's Step 6 entry; omit both fields for minor issues:

{
  "id": "AH1",
  "severity": "major",
  "title": "Staff email/phone readable by Anonymous",
  "table": "contoso_staff",
  "dimension": "anonymous-access-hygiene",
  "scope": "Global",
  "permission": "Staff - Public Read",
  "reasoning": "Staff email/phone are in the $select and the Webapi field whitelist, and Staff-Public-Read grants the Anonymous role Global read — public internet can read staff PII.",
  "fix": "Restrict staff read to a purpose-specific role assigned only to verified users, or drop contoso_email/contoso_phone from the whitelist and $select.",
  "details": "Staff-Public-Read.tablepermission.yml; Webapi-contoso_staff-fields.sitesetting.yml; src/shared/services/staffService.ts:85",
  "rootCause": "mixed",
  "rootCauseReason": "The anonymous Global read grant is a permission mistake, and the Web API fields setting also whitelists contoso_email and contoso_phone."
}

INVENTORY_DATA format:

{
  "name": "Product - Anonymous Read",
  "table": "cra5b_product",
  "scope": "Global",
  "roles": ["Anonymous Users"],
  "read": true,
  "create": false,
  "write": false,
  "delete": false,
  "append": true,
  "appendto": false
}

SCORECARD_DATA format (from Step 5; the report reads only these fields):

{
  "categories": [
    { "name": "Over-Exposure (Security)", "score": 3.10 },
    { "name": "Under-Exposure (Usability & Coverage)", "score": 4.21 },
    { "name": "Correctness (Validity & Alignment)", "score": 3.48 }
  ],
  "reportPaths": [
    { "label": "HTML report", "path": "<PROJECT_ROOT>/docs/permissions-audit.html" }
  ]
}

The report surfaces this data automatically. The Overview tab leads with the Audit Summary, then an Issues row (major and minor counts — the single problem tally, which is exactly what drives the score) and a Verdict section (Safe to go / Needs revision, computed from the major count in FINDINGS_DATA, plus the per-category 1–5 score bars), plus the report paths. Every issue is major or minor — there is no critical/warning/info/pass tier anywhere in the report. The Issues tab lists each major/minor issue with its evidence and fix; each major issue also shows a root-cause badge (Permissions only, Permissions + upstream, or Upstream: data model / site code / Web API settings) and the one-sentence justification.

7.3 Render the HTML File

Run the render script (it creates the output directory if needed):

node "${PLUGIN_ROOT}/scripts/render-audit-report.js" --output "<OUTPUT_PATH>" --data "<DATA_JSON_PATH>"

The render script refuses to overwrite existing files. Before calling it, check if the default output path (<PROJECT_ROOT>/docs/permissions-audit.html) already exists. If it does, choose a new descriptive filename based on context — e.g., permissions-audit-apr-2026.html, permissions-audit-post-migration.html. Pass the chosen name via --output, and use the same path in reportPaths.

7.4 Validate the report

Run the semantic validator on the rendered report:

node "${PLUGIN_ROOT}/skills/audit-permissions/scripts/validate-audit.js" \
  --report "<OUTPUT_PATH>" \
  --data "<DATA_JSON_PATH>" \
  --auditRunId "<AUDIT_RUN_ID>"

When local run initialization returned no run id, omit --data and --auditRunId; report validation must still run.

Do not present or copy a report until validation succeeds. The validator reads FINDINGS_DATA, INVENTORY_DATA, and SCORECARD_DATA from the report and checks unique issue ids whose prefix matches the dimension, major/minor severities, non-empty title/reasoning/fix, a valid rootCause and rootCauseReason on every major finding (and none on minor findings), that the inventory is an array, the three category scores recomputed from the findings, that SUMMARY states the verdict matching the major count (and neither verdict phrase on a partial audit), and leftover placeholders. When the run id and data path are supplied, the same deterministic command revalidates the source data, derives the closed aggregate metrics, and records successful completion and elapsed duration.

If validation fails, delete the report you just rendered, fix the named problem in the data file, render again to the same path, and rerun the validator. Do not repeat evidence gathering to fix a validation error.

The validator reports telemetryStatus as recorded_success, recorded_failure (the report is valid but its source data could not be reconciled, so the run was recorded with failureStage: metrics_validation), disabled (telemetry is hard-disabled for this plugin, so nothing was recorded), failed, or not_requested. Telemetry is best-effort: none of recorded_failure, disabled, or failed invalidates the report. Do not retry with a reduced payload and do not expose report data in diagnostic output.

Delete the temporary audit-data.json and audit-evidence.json files only after report validation succeeds. The telemetry status does not affect cleanup.

7.5 Open in Browser

Open the actual HTML output path in the user's default browser.


Step 8: Present Findings & Track

8.1 Record Skill Usage

Reference: ${PLUGIN_ROOT}/references/skill-tracking-reference.md

Follow the skill tracking instructions in the reference to record this skill's usage. Use --skillName "AuditPermissions".

8.2 Present Summary

<!-- gate: audit-permissions:6.fix-offer | category=plan | cancel-leaves=nothing -->

🚦 Gate (plan · audit-permissions:6.fix-offer): Offer to apply auto-fixes for major/minor issues. The report has already been written; declining here just leaves the HTML report in place — no Dataverse / filesystem mutation.

Trigger: Phase 8 has tallied findings and the report is saved.

Why we ask: Tooling could silently invoke the table-permissions-architect agent — accept-by-default would write or mutate permission YAML against the user's intent.

Cancel leaves: Nothing — the report stays at its saved path. No web-role / table-permission files written.

Present a summary to the user:

  1. Verdict — when SCORECARD_DATA is non-null, show Safe to go or Needs revision plus the three category scores; otherwise state that this is a partial audit and omit both verdict phrases and scores.
  2. Major issues count — these need immediate attention
  3. Minor issues count — nice-to-have / forward-looking
  4. Report location — where the HTML report was saved
  5. Ask the user using AskUserQuestion: "Would you like me to fix any of these issues? I can create or update table permissions to resolve the major issues."

If the user wants fixes applied:


Appendix A — Scoring model

Scoring is a pure function of the consolidated issues — reproduce it exactly.

Categories

| Category | Dimensions |

|---|---|

| Over-Exposure (Security) | privilege-calibration, anonymous-access-hygiene, security-posture |

| Under-Exposure (Usability & Coverage) | intent-coverage, table-coverage, role-completeness |

| Correctness (Validity & Alignment) | scope-correctness, data-model-alignment, internal-consistency |

Score-from-issues formula

For a set of issues, let nMajor and nMinor be the counts. Then:

load    = 1.0 * nMajor + 0.25 * nMinor
penalty = tanh(0.2 * load)          # tanh maps [0,∞) → [0,1); penalty(0)=0
score   = 5 - 4 * penalty           # 0 issues → 5.00 ; grows → 1.00
score   = round(score * 100) / 100  # 2 decimals

Constants: MAJOR_LOAD = 1.0, MINOR_LOAD = 0.25, PENALTY_STEEPNESS = 0.2.

Reference points (0.2 steepness): 0 issues → 5.00; 1 major → 4.21; 2 major → 3.48; 3 major → 2.85; 1 minor → 4.80; the first major always hurts most (diminishing returns).

Final verdict

The verdict is driven by severity, not by any score:

| Condition | Verdict | Meaning |

|---|---|---|

| 0 major issues | Safe to go | No major issues were identified. |

| ≥ 1 major issue | Needs revision | One or more major issues were identified; review and address them. |

Minor issues never change the verdict — they are still recorded and still lower their category score, but they are left to the user's judgement. State the verdict phrase verbatim in Step 5.4 and in the report.

The verdict is advisory. It summarises what the audit found; it is not an approval or a release gate, and the decision to act on it rests with the human reviewer. Never instruct the user to deploy or not deploy.


Appendix B — The 9 dimensions

Use each dimension's definition to decide where an issue belongs. Order is canonical for output.

1. Intent Coverage — IC · Under-Exposure — Does every authorization-relevant capability in the request map to at least one (role × table × op) grant? Usability rule: if the request implies managing/authoring records but NO role has ANY Create/Write/Delete on the relevant tables (read-only everywhere), that's a coverage FAILURE → a major issue.

2. Privilege Calibration — PC · Over-Exposure — Per (role, table, op): is each CRUD bit right-sized — not over- or under-granted?

3. Scope Correctness — SC · Correctness — Does scope (Global/Contact/Account/Parent/Self) match the data-ownership model? Per-user → Contact; public bulletin → Global; child records reached through a parent record → Parent; the user's own contact record → Self.

4. Role Completeness — RC · Under-Exposure — Are all personas implied by the request present as web roles? Spurious roles? Anonymous + Authenticated correct?

5. Table Coverage (Permissions) — TC · Under-Exposure — Every user-facing table has ≥1 permission; system/non-user-facing tables correctly excluded.

6. Anonymous Access Hygiene — AH · Over-Exposure — Anonymous gets minimal read only where the request implies public content; no anonymous write/create/delete unless justified.

7. Data Model Alignment — DM · Correctness — Every table referenced in a permission resolves to a real data-model table; no phantom/misnamed tables.

8. Internal Consistency — IS · Correctness — YAML valid; every web-role GUID in a permission resolves; permissions-plan.html aligns with the YAML.

9. Security Posture — SP · Over-Exposure — Overall least-privilege. No surprising broad grants on sensitive tables (Contact, system tables); no avoidable delete/write on shared records. If Web API field whitelists exist, check they don't broadly expose sensitive PII columns.


Appendix C — Severity policy & audit↔grader bridge

Severity policy (apply rules IN ORDER; first match wins)

Only two severities exist: major (a real problem — breaks the site or leaks data, or a genuinely sub-optimal config that should be fixed) and minor (cosmetic / forward-looking / nice-to-have). There is no "info" tier in the grader (audit info findings map to minor).

Default stance — SECURITY FIRST / LEAST PRIVILEGE. Access should be granted only where the role's real-world use case requires it, scoped as narrowly as possible. Reaching or mutating records beyond that need is over-granted → major, even for an otherwise-"authorized" role.

  1. Realized vs hypothetical. Major = the problem is true right now (a flow is broken, or data is exposed to an audience that shouldn't see it). Minor = only matters under a hypothetical future change, or is cosmetic. Tell-tale minor language: "if … later", "could", "should be revisited".
  2. Need-to-know / over-scope. Major = a role can read/mutate records beyond its need — EITHER an unauthorized audience (Anonymous, or a role outside the data's intended audience) reaches it, OR an authorized role gets Global scope over per-owner / per-relationship data (personal records, PII, grades, rosters, guardian contact) so it reaches every record instead of its own subset. Especially severe for PII (email, phone, guardian contact, addresses). Minor = over-broad scope only on genuinely public/shared reference data (announcements, facilities, public directory). Staff roles working a shared work queue follow C16, and child tables matching their parent's reach follow C17.
  3. Mutation vs read. Major = an unwanted mutating grant (write/create/delete for a role that shouldn't have it; anonymous mutation is always major). An over-broad read is minor unless rule (2) makes it major. Absence of needed mutation (a management/authoring site with NO Create/Write/Delete anywhere) is a broken flow → major under rule (1).

Anchor examples. The recurring-issue catalog (C1–C18, Step 5.1) is the primary anchor set — label any case it covers exactly as the catalog says. Two further recurring cases:

Audit finding → grader dimension bridge

Map each Step-4 finding into a dimension, then apply the severity policy above to set major/minor. (Audit critical almost always → major; audit info → minor; audit warning → apply the policy.)

| Audit check / finding | Grader dimension | Typical grader severity |

|---|---|---|

| A. Missing permission for referenced table | intent-coverage (+ table-coverage) | major |

| A. Unused permission (not referenced in code) | privilege-calibration (C18, one issue per role) | minor |

| B. Permission has no web role | role-completeness | major; none for a Parent-scope child with a valid parent chain |

| C. Global scope with write/delete | privilege-calibration / security-posture | major, except staff shared work queues (C16) and child-table parity (C17) |

| C. Scope could be narrower | scope-correctness | major if per-owner/PII, else minor |

| D. Missing read | intent-coverage | major |

| E. Missing create · F. Missing write · G. Missing delete | intent-coverage | major |

| E/F/G. Enabled-but-not-used | privilege-calibration (C18, one issue per role) | minor |

| F. File upload but write disabled | intent-coverage | major |

| F. Write without read | privilege-calibration | major |

| H. Missing append · H2. Missing appendto | privilege-calibration / intent-coverage | major |

| H. Append enabled but not needed | privilege-calibration (C18, one issue per role) | minor |

| I. Broken parent chain | internal-consistency | major |

| J. Missing read on $expand table | intent-coverage | major |

| PII readable by anonymous | anonymous-access-hygiene / security-posture | major |

| Schema-validator error / warning / info | internal-consistency (or the specific dimension) | error→major, warning→policy, info→minor |


Critical Constraints

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.